body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I'm trying to write a code where a charged particle (charge=+20 called dimers), after a certain time, will split into a neutral particle and a smaller charged particle (charge=-10 called monomer). I split position and velocity into x,y,z component matrices along with charge and fragmentation time matrices for each species (monomers, dimers, and neutrals). </p>
<p>The way the code works is 1 dimer is supposed to be injected per time step, but whenever the fragmentation time of that dimer is reached it will turn into a monomer and neutral particle. I got the injection and pos/vel update portions to work, but the fragmentation portion is causing a lot of trouble. Every time a fragmentation time is reached I move the dimer data (pos,vel) to the end of the monomer and neutral matrices and move the last dimer data to the destroyed dimer to overwrite it. </p>
<p>However, when I run the code the simulation appears to work correctly but then after about 17 cycles the monomers and neutrals will jump back to the original point where they split and rewrite over the correct pos/vel from before. </p>
<p>The error seems to be in indexing in passing information from the dimer to the neutrals and monomers but I'm not sure why it's happening.</p>
<p>The code is shown below with the main while loop stopping the simulation once a certain number of particles are injected. Inside the while loop are three for loops that inject particles, update vel/pos, and check for fragmentation (this is the loop causing trouble).</p>
<pre class="lang-matlab prettyprint-override"><code>f_ind = [0,0,0];
qms0 = [-10,20]; %peak position (q/m)
t=0;
np = 0; %number of particles total
npnew = [1,1]; %!injected particles for each species
%_______________________Main loop__________________________________________
while (np+sum(npnew) <= npmax) %if particles injected is less than max particle limit
%INJECT PARTICLES
for k=1:npeaks %cycle through monomers (1) and dimers (2)
for i=1:npnew(k)
posx(i+f_ind(k),k)=0.0; %x-pos
posy(i+f_ind(k),k)=i*3; %y-pos
posz(i+f_ind(k),k)=k; %z-pos
velx(i+f_ind(k),k) = 0.01;
vely(i+f_ind(k),k) = 0.0;
velz(i+f_ind(k),k) = 0.0;
q_m(i+f_ind(k),k)=qms0(k); %assign charge
if (k==2) %for dimers
tfrag(i+f_ind(k),k)=t + 0.05; %only set a fragmentation time for dimers
end
end
f_ind(k) = f_ind(k) + npnew(k); %add to index to keep species particle count
np = np + npnew(k); %add particle count of each injected species to total particle count
end
%UPDATE VELOCITY AND POSITION
for k=1:(npeaks+1) %cycle through monomer, dimers, and neutrals
for i=1:f_ind(k) %only cycle up to the last index of each species(saves time not cycling empty spaces)
velx(i,k) = velx(i,k) + Epx*(q_m(i,k))*dt;
vely(i,k) = vely(i,k) + Epy*(q_m(i,k))*dt;
velz(i,k) = velz(i,k) + Epz*(q_m(i,k))*dt;
posx(i,k) = posx(i,k) + velx(i,k)*dt; %x-pos
posy(i,k) = posy(i,k) + vely(i,k)*dt; %y-pos
posz(i,k) = posz(i,k) + velz(i,k)*dt; %z-pos
end
end
%Fragment dimer if it reaches fragmentation time (ERROR IN THIS PORTION)
for i=1:f_ind(2)
if((t >= tfrag(i,2))&&(tfrag(i,2)>0))
%pass dimer information to monomer
posx(f_ind(1)+1,1) = posx(i,2);
posy(f_ind(1)+1,1) = posy(i,2);
posz(f_ind(1)+1,1) = posz(i,2);
velx(f_ind(1)+1,1) = velx(i,2);
vely(f_ind(1)+1,1) = vely(i,2);
velz(f_ind(1)+1,1) = velz(i,2);
%assign monomer charge and update counter
q_m(f_ind(1)+1,1) = -10;
f_ind(1) = f_ind(1) + 1; %update monomer index
%pass dimer information to neutral
posx(f_ind(3)+1,3) = posx(i,2);
posy(f_ind(3)+1,3) = posy(i,2);
posz(f_ind(3)+1,3) = posz(i,2);
velx(f_ind(3)+1,3) = velx(i,2);
vely(f_ind(3)+1,3) = vely(i,2);
velz(f_ind(3)+1,3) = velz(i,2);
%assign neutral charge and update counter
q_m(f_ind(3)+1,3) = 0;
f_ind(3) = f_ind(3) + 1; %update neutral index
%destroy dimer and replace with the last dimer
posx(i,2) = posx(f_ind(2),2);
posy(i,2) = posy(f_ind(2),2);
posz(i,2) = posz(f_ind(2),2);
velx(i,2) = velx(f_ind(2),2);
vely(i,2) = vely(f_ind(2),2);
velz(i,2) = velz(f_ind(2),2);
q_m(i,2) = q_m(f_ind(2),2);
tfrag(i,2) = tfrag(f_ind(2),2);
f_ind(2) = f_ind(2) - 1; %update dimer index
end
end
t = t + dt; %progress time for ALL species not EACH species
end
</code></pre>
<p>The picture below shows the dimers being injected then breaking up into neutrals and monomers once their time is reached. The simulation works up to a point, but then it appears to double back and put particles at the dimer fragmentation point.</p>
<p><a href="https://i.stack.imgur.com/PGhJV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PGhJV.png" alt="enter image description here"></a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-03T22:54:38.480",
"Id": "225491",
"Score": "2",
"Tags": [
"simulation",
"matlab"
],
"Title": "Simulation of splitting particles (MATLAB - Fortran)"
}
|
225491
|
<p>We had a long HTML string with information about the makers of our software. However, for i18n this was unwieldy. So I started to refactor, so only each person's description is translateable, not all HTML tags, nor contact info. I am beginner, so probably not used the best data structure, etc.</p>
<p>This was the code before:</p>
<pre><code> QString aboutMudletBody(
tr("<p align=\"center\"><big><b>Original author: <span style=\"color:#bc8942;\">Heiko Köhn</span></b> (<b><span style=\"color:#0000ff;\">KoehnHeiko@googlemail.com</span></b>)</big></p>\n"
"<p align=\"center\"><big><b>Credits:</b></big></p>"
"<p><span style=\"color:#bc8942;\"><big><b>Vadim Peretokin</b></big></span> (<span style=\"color:#7289DA;\">Vadi#3695</span> <span style=\"color:#40b040;\">vadi2</span> <span style=\"color:#0000ff;\">vadim.peretokin@mudlet.org</span>) GUI design and initial feature planning. He is responsible for the project homepage and the user manual. Maintainer of the Windows, macOS, Ubuntu and generic Linux installers. Maintains the Mudlet wiki, Lua API, and handles project management, public relations &amp; user help. With the project from the very beginning and is an official spokesman of the project. Since the retirement of Heiko, he has become the head of the Mudlet project.</p>\n"
"<p><span style=\"color:#bc8942;\"><big><b>Stephen Lyons</b></big></span> (<span style=\"color:#7289DA;\">SlySven#2703</span> <span style=\"color:#40b040;\">SlySven</span> <span style=\"color:#0000ff;\">slysven@virginmedia.com</span>) after joining in 2013, has been poking various bits of the C++ code and GUI with a pointy stick; subsequently trying to patch over some of the holes made/found. Most recently he has been working on I18n and L10n for Mudlet 4.0.0 so if you are playing Mudlet in a language other than American English you will be seeing the results of him getting fed up with the spelling differences between what was being used and the British English his brain wanted to see.</p>\n"
"<p><span style=\"color:#bc8942;\"><b>Ahmed Charles</b></span> (<span style=\"color:#40b040;\">ahmedcharles</span> <span style=\"color:#0000ff;\">acharles@outlook.com</span>) contributions to the Travis integration, CMake and Visual C++ build, a lot of code quality and memory management improvements.</p>\n"
"<p><span style=\"color:#bc8942;\"><b>Chris Mitchell</b></span> (<span style=\"color:#40b040;\">Chris7</span> <span style=\"color:#0000ff;\">chrismudlet@gmail.com</span>) has developed a shared module system that allows script packages to be shared among profiles, a UI for viewing Lua variables, improvements in the mapper and all around.</p>\n"
"<p>Others too, have make their mark on different aspects of the Mudlet project and if they have not been mentioned here it is by no means intentional! For past contributors you may see them mentioned in the <b><a href=\"https://launchpad.net/~mudlet-makers/+members#active\">Mudlet Makers</a></b> list (on our former bug-tracking site), or for on-going contributors they may well be included in the <b><a href=\"https://github.com/Mudlet/Mudlet/graphs/contributors\">Contributors</a></b> list on GitHub.</p>\n"
"<br>\n"
"<p>Many icons are taken from the <span style=\"color:#bc8942;\"><b><u>KDE4 oxygen icon theme</u></b></span> at <a href=\"https://web.archive.org/web/20130921230632/http://www.oxygen-icons.org/\">www.oxygen-icons.org <sup>{wayback machine archive}</sup></a> or <a href=\"http://www.kde.org\">www.kde.org</a>. Most of the rest are from Thorsten Wilms, or from Stephen Lyons combining bits of Thorsten's work with the other sources.</p>\n"));
</code></pre>
<p>I have omitted some names, just kept enough to show small example.</p>
<p>This is the code now:</p>
<pre><code> QVector<QStringList> aboutBigMakers; // [name, discord, github, email, description (HTML escaped)]
aboutBigMakers.append({QStringLiteral("Heiko Köhn"),
QString(),
QString(),
QStringLiteral("KoehnHeiko@googlemail.com"),
tr("Original author.",
"about:Heiko")});
aboutBigMakers.append({QStringLiteral("Vadim Peretokin"),
QStringLiteral("Vadi#3695"),
QStringLiteral("vadi2"),
QStringLiteral("vadim.peretokin@mudlet.org"),
tr("GUI design and initial feature planning. He is responsible for the project homepage and the user manual. "
"Maintainer of the Windows, macOS, Ubuntu and generic Linux installers. "
"Maintains the Mudlet wiki, Lua API, and handles project management, public relations &amp; user help. "
"With the project from the very beginning and is an official spokesman of the project. "
"Since the retirement of Heiko, he has become the head of the Mudlet project.",
"about:Vadi")});
aboutBigMakers.append({QStringLiteral("Stephen Lyons"),
QStringLiteral("SlySven#2703"),
QStringLiteral("SlySven"),
QStringLiteral("slysven@virginmedia.com"),
tr("After joining in 2013, he has been poking various bits of the C++ code and GUI with a pointy stick; "
"subsequently trying to patch over some of the holes made/found. "
"Most recently he has been working on I18n and L10n for Mudlet 4.0.0 so if you are playing Mudlet in a language "
"other than American English you will be seeing the results of him getting fed up with the spelling differences "
"between what was being used and the British English his brain wanted to see.",
"about:SlySven")});
QVector<QStringList> aboutMoreMakers;
aboutMoreMakers.append({QStringLiteral("Ahmed Charles"),
QString(),
QStringLiteral("ahmedcharles"),
QStringLiteral("acharles@outlook.com"),
tr("Contributions to the Travis integration, CMake and Visual C++ build, "
"a lot of code quality and memory management improvements.",
"about:ahmedcharles")});
aboutMoreMakers.append({QStringLiteral("Chris Mitchell"),
QString(),
QStringLiteral("Chris7"),
QStringLiteral("chrismudlet@gmail.com"),
tr("Developed a shared module system that allows script packages to be shared among profiles, a UI for viewing Lua variables, improvements in the mapper and all around.",
"about:Chris7")});
QString aboutMudletBody("<p align=\"center\"><big><b>Credits:</b></big></p>");
QVectorIterator<QStringList> iterateBig(aboutBigMakers);
while (iterateBig.hasNext()) { aboutMudletBody.append(createMakerHTML(iterateBig.next(), true)); }
QVectorIterator<QStringList> iterateMore(aboutMoreMakers);
while (iterateMore.hasNext()) { aboutMudletBody.append(createMakerHTML(iterateMore.next(), false)); }
aboutMudletBody.append(
tr("<p>Others too, have make their mark on different aspects of the Mudlet project and if they have not been mentioned here it is by no means intentional! For past contributors you may see them mentioned in the <b><a href=\"https://launchpad.net/~mudlet-makers/+members#active\">Mudlet Makers</a></b> list (on our former bug-tracking site), or for on-going contributors they may well be included in the <b><a href=\"https://github.com/Mudlet/Mudlet/graphs/contributors\">Contributors</a></b> list on GitHub.</p>\n"
"<br>\n"
"<p>Many icons are taken from the <span style=\"color:#bc8942;\"><b><u>KDE4 oxygen icon theme</u></b></span> at <a href=\"https://web.archive.org/web/20130921230632/http://www.oxygen-icons.org/\">www.oxygen-icons.org <sup>{wayback machine archive}</sup></a> or <a href=\"http://www.kde.org\">www.kde.org</a>. Most of the rest are from Thorsten Wilms, or from Stephen Lyons combining bits of Thorsten's work with the other sources.</p>\n"));
</code></pre>
<p>It is much longer, but more readable, and also only the important part is in tr() for translators to review.</p>
<p>For combination with the actual HTML tags I made another function:</p>
<pre><code>QString dlgAboutDialog::createMakerHTML(const QStringList aboutMaker, const bool big) const
{
QString makerHTML;
auto realname = aboutMaker.at(0);
auto discord = aboutMaker.at(1);
auto github = aboutMaker.at(2);
auto email = aboutMaker.at(3);
auto description = aboutMaker.at(4);
makerHTML.append(QStringLiteral("<p><span style=\"color:#bc8942;\">"));
if (big) {makerHTML.append(QStringLiteral("<big>"));}
makerHTML.append(QStringLiteral("<b>"));
makerHTML.append(realname);
makerHTML.append(QStringLiteral("</b>"));
if (big) {makerHTML.append(QStringLiteral("</big>"));}
makerHTML.append(QStringLiteral("</span> ("));
if (!discord.isEmpty()) {
makerHTML.append(QStringLiteral("<span style=\"color:#7289DA;\">"));
makerHTML.append(discord);
makerHTML.append(QStringLiteral("</span> "));
}
if (!github.isEmpty()) {
makerHTML.append(QStringLiteral("<span style=\"color:#40b040;\">"));
makerHTML.append(github);
makerHTML.append(QStringLiteral("</span> "));
}
if (!email.isEmpty()) {
makerHTML.append(QStringLiteral("<span style=\"color:#0000ff;\">"));
makerHTML.append(email);
makerHTML.append(QStringLiteral("</span> "));
}
makerHTML.append(QStringLiteral(") "));
makerHTML.append(description);
makerHTML.append(QStringLiteral("</p>\n"));
return makerHTML;
}
</code></pre>
<p>It's a bit tricky, because not all makers have all contact info filled out. Some have none at all, some have only one listed, others two or all three.</p>
<p>Maybe we need to think about rephrasing that line as well. For now, my goal was not to change the output in the software at all. (I did so for the first maker after all, just to keep the overall layout.) The goal was to reduce and sanitize the output for translators, and that goal is accomplished.</p>
<p>Looking forward to your feedback on how to improve! :)</p>
<p>edit: </p>
<p>I have got two hints:</p>
<ol>
<li>All the appending of strings could be not very smart. Use a format string instead and fill in the spaces with .arg() function.</li>
<li>Define my own data structure other than the anonymous list of strings. Maybe include the bool big in there as well.</li>
</ol>
<p>edit:</p>
<p>I got rid of most appending in the createMakerHTML helper function, which now looks like this:</p>
<pre><code>QString dlgAboutDialog::createMakerHTML(const QStringList aboutMaker, const bool big) const
{
auto realname = aboutMaker.at(0);
auto discord = aboutMaker.at(1);
auto github = aboutMaker.at(2);
auto email = aboutMaker.at(3);
auto description = aboutMaker.at(4);
QString coloredText("<span style=\"color:#%1;\">%2</span>");
QStringList contactDetails;
if (!discord.isEmpty()) {contactDetails.append(coloredText.arg("7289DA", discord));}
if (!github.isEmpty()) {contactDetails.append(coloredText.arg("40b040", github));}
if (!email.isEmpty()) {contactDetails.append(coloredText.arg("0000ff", email));}
return QStringLiteral("<p>%1%2 %3</p>\n") // name (big?), contacts (if any?), description
.arg(coloredText.arg("bc8942", QStringLiteral("<b>%1</b>")
.arg((big) ? QStringLiteral("<big>%1</big>").arg(realname) : realname)),
(contactDetails.isEmpty()) ? QString() :
QStringLiteral(" (%1)").arg(contactDetails.join(QChar::Space)),
description);
}
</code></pre>
<p>Now that .arg() cascade is much shorter but very dense, feels a bit hard to grasp.</p>
<p>edit:
Now also replaced the QStringList with a struct I defined. Let me know if you want to see the code. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T02:28:25.777",
"Id": "437868",
"Score": "0",
"body": "Have you tried using the [`CTML` Html document library](https://github.com/tinfoilboy/CTML), made for c++?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T22:31:56.593",
"Id": "437955",
"Score": "0",
"body": "No, I did not even know that library. Thanks for the hint. Will look into it."
}
] |
[
{
"body": "<h1>Avoid explicitly constructing <code>QString</code> and <code>QStringLiteral</code> objects</h1>\n\n<p>In many cases, it's totally unnecessary to explicitly write <code>QString(\"...\")</code> or <code>QStringLiteral(\"...\")</code>. Constant string literals will be implicitly converted to <code>QString</code> in many cases. Also, while <code>QStringLiteral</code> might avoid a copy <em>in some cases</em>, it looks like premature optimization to me. So for example, just write:</p>\n\n<pre><code>aboutBigMakers.append({\"Heiko Köhn\",\n \"\",\n \"\",\n \"KoehnHeiko@googlemail.com\",\n tr(\"Original author.\", \"about:Heiko\")});\n</code></pre>\n\n<h1>Use a <code>struct</code> for structured data</h1>\n\n<p>You are using a <code>QStringList</code> to hold the name, discord, github, email and description for an author. Now you have the problem that you have to remember the correct order of all the items in a <code>QStringList</code>, and it is easy to accidentily forget to add all the items to the list (especially empty ones). Instead, create a <code>struct</code> to hold these 5 items explicitly:</p>\n\n<pre><code>struct authorInformation {\n QString realname;\n QString discord;\n QString github;\n QString email;\n QString description;\n};\n</code></pre>\n\n<p>Then you can construct the vector of author information like this:</p>\n\n<pre><code>QVector<authorInformation> aboutBigMakers;\naboutBigMakers.append({\"Heiko Köhn\",\n \"\",\n \"\",\n \"KoehnHeiko@googlemail.com\",\n tr(\"Original author.\", \"about:Heiko\")});\n</code></pre>\n\n<p>Nothing much changed here, but in <code>dlgAboutDialog::createMakerHTML()</code> you no longer need to remember the order of the elements in the list, and can just write:</p>\n\n<pre><code>QString dlgAboutDialog::createMakerHTML(const authorInformation &aboutMaker, const bool big) const\n{\n QString coloredText(\"<span style=\\\"color:#%1;\\\">%2</span>\");\n QStringList contactDetails;\n if (!aboutMaker.discord.isEmpty()) {\n contactDetails.append(coloredText.arg(\"7289DA\", aboutMaker.discord));}\n }\n ...\n}\n</code></pre>\n\n<p>While you are at it, you can also add a <code>bool big</code> to <code>struct authorInformation</code>, so you don't have to pass that in as a separate function parameter, and you don't have to have one list for big and one for small authors anymore.</p>\n\n<h1>Consider using raw string literals (C++11)</h1>\n\n<p>You have a lot of strings containing HTML code that needs to escape double quote characters (<code>\\\"</code>). You can avoid this by using <a href=\"https://en.cppreference.com/w/cpp/language/string_literal\" rel=\"nofollow noreferrer\">raw string literals</a> introduced in C++11. For example, you can do this:</p>\n\n<pre><code>makerHTML.append(R\"(<p><span style=\"color:#bc8942;\">)\");\n</code></pre>\n\n<h1>Use a template library</h1>\n\n<p>You are actually implementing a template for displaying author information. It would be much nicer if you could just write the template as one big string, and have the various items like name, email address and so on filled in in the right spots. You could use string formatting like you do with <code>coloredText</code>, but a real template language is more appropriate here. I can recommend <a href=\"https://github.com/no1msd/mstch\" rel=\"nofollow noreferrer\">mstch</a>, which is a C++ implementation of the <a href=\"https://mustache.github.io/\" rel=\"nofollow noreferrer\">{{mustache}}</a> template language. Then you can write the whole HTML structure as one big string, and you avoid concattenating lots of tiny strings, as well as avoiding an <code>.arg()</code> cascade.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T14:44:06.137",
"Id": "225888",
"ParentId": "225497",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T02:02:31.590",
"Id": "225497",
"Score": "4",
"Tags": [
"c++",
"beginner",
"strings",
"html",
"qt"
],
"Title": "Create HTML structure dynamically"
}
|
225497
|
<p>I wanted to get some feedback here on my solution, because the course I am using is not allowing me to submit any answers.</p>
<blockquote>
<p>Objectives:</p>
<p>Write a Java program that:</p>
<ol>
<li>Create a grades.txt file with some grades inputted in</li>
<li>Reads these grades from the file and stores it into an <code>ArrayList</code></li>
<li>After storing all elements into the <code>ArrayList</code> return the max, min, and average grade of the list</li>
<li>Return an <code>Arraylist</code> without any duplicate grades. All duplicated grades must be removed</li>
</ol>
</blockquote>
<p></p>
<pre><code>import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
File file = new File("grades.txt");
PrintWriter output = new PrintWriter(file);
output.println("12.5");
output.println("19.75");
output.println("11.25");
output.println("10");
output.println("15");
output.println("13.25");
output.println("14");
output.println("9");
output.println("10");
output.println("19.75");
output.close();
// Reading from the file //
ArrayList<Double> gradesString = new ArrayList<Double>();
Scanner input = new Scanner(file);
while(input.hasNext())
{
String line = input.nextLine();
gradesString.add(Double.parseDouble(line));
}
double result = 0;
for(Double i : gradesString)
{
result += i;
}
double mean = result / gradesString.size();
LinkedHashSet<Double> hashSet = new LinkedHashSet<>(gradesString);
ArrayList<Double> gradesWithoutDuplicates = new ArrayList<Double>(hashSet);
System.out.println("The grades are: " + gradesString);
System.out.println("The highest grade is: " + Collections.max(gradesString));
System.out.println("The lowest grade is: " + Collections.min(gradesString));
System.out.println("The average is: " + mean);
System.out.println("The grades list without duplicates is: " + gradesWithoutDuplicates);
}
}
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>The grades are: [12.5, 19.75, 11.25, 10.0, 15.0, 13.25, 14.0, 9.0, 10.0, 19.75]
The highest grade is: 19.75
The lowest grade is: 9.0
The average is: 13.45
The grades list without duplicates is: [12.5, 19.75, 11.25, 10.0, 15.0, 13.25, 14.0, 9.0]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T08:48:44.820",
"Id": "437884",
"Score": "0",
"body": "Please don't edit the question once answers are available. This would invalidate them. After you feel sufficient reviews are available, you could always ask a follow-up question with the improved code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T16:34:15.090",
"Id": "437922",
"Score": "0",
"body": "You should have at least one method for each of your four bullet points. Reading a file, parsing a file, analyzing a data set, and deduplicating a dataset are very different responsibilities. They shouldn't all just be under one method (especially not `main`)"
}
] |
[
{
"body": "<h2>Exception handling</h2>\n\n<p>It is not customary to let the main method throw an exception. At the very least you can catch the base <code>Exception</code> class and use <code>printStackTrace()</code> to print the error message and related debug info. </p>\n\n<h2>IO handling</h2>\n\n<ol>\n<li><p>This program only deals with one file. However, it is good practice to remember to close every external resource. That includes files, database connections (and other related resources, like prepared statements and result sets), network sockets, etc. not closing resources may result in resource leaks that can escalate to JVM crash. Java 7 introduced the <a href=\"https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow noreferrer\">try-with-resources</a> construct that allows the compiler to automatically handle resource closure as well as error handling.</p></li>\n<li><p>Java 7 also introduced the \"new io\" <code>java.nio</code> package that improves IO handling in Java. the <code>Files.readAllLines()</code> is a convenient method that reads whole file into <code>List</code> of <code>String</code>s (and also internally handles the external resource). (alas, no equivalent <code>writeAllLines()</code>)</p></li>\n</ol>\n\n<h2>Naming conventions</h2>\n\n<p><code>gradesString</code> is a List of <code>Double</code> items. the name is <em>very</em> confusing.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T08:15:55.573",
"Id": "225509",
"ParentId": "225501",
"Score": "3"
}
},
{
"body": "<h2>Review</h2>\n\n<p>Java is an object-oriented language, so I suggest you take advantage of that. I understand your main concern is to provide a solution to the problem, but a next step is to make it adhere to some quality attributes such as testibility, usability and readability. This way, you'll be able to write code that others can reuse and maintain.</p>\n\n<hr>\n\n<h3>Remarks</h3>\n\n<ul>\n<li>Algorithm logic is mixed with input parsing and output to end-user</li>\n<li>Input file is fixed</li>\n<li>No error handler provided (what if can't open file or bad input detected?)</li>\n<li>Main method abused for creating the algorithm</li>\n<li>No edge case handler provided (what if file is empty, what would <em>min</em>, <em>max</em>, <em>mean</em> be?)</li>\n<li>No unit tests provided</li>\n<li>Make variables that you don't change final. For instance, <code>final double mean = result / gradesString.size();</code></li>\n<li>Fix intendations</li>\n</ul>\n\n<hr>\n\n<h3>Proposed Changes</h3>\n\n<ul>\n<li>Split the current implementation into 3 methods: one for reading and parsing an input file, one for performing the algorithm and one for outputting results to the end-user.</li>\n<li>Let main method call these 3 methods with a predefined input file and provide a simple error handler.</li>\n<li>Create a custom class holding all the statistical results and return an instance of this class in the algorithm.</li>\n<li>Provide unit tests for the algorithm for at least the happy path, but preferrably also for empty input.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T08:44:56.430",
"Id": "225510",
"ParentId": "225501",
"Score": "2"
}
},
{
"body": "<p>As the previous answers <a href=\"https://codereview.stackexchange.com/a/225509/203649\">https://codereview.stackexchange.com/a/225509/203649</a> and <a href=\"https://codereview.stackexchange.com/a/225510/203649\">https://codereview.stackexchange.com/a/225510/203649</a> have already explained, the main problem of your code is about reading and writing to the file and the exception handling.\nAbove my initialization of the filename and the creation of a double array in the main method:</p>\n\n<pre><code>String filename = \"grades.txt\";\nFile file = new File(filename);\ndouble doubles[] = {12.5, 19.75, 11.25, 10, 15, \n 13.25, 14, 9, 10, 19.75};\n</code></pre>\n\n<p>Now you can use the try-with-resources construct with PrintWriter:</p>\n\n<pre><code> try(PrintWriter pw = new PrintWriter(file)) {\n for (Double d: doubles) {\n pw.println(d);\n }\n } catch (FileNotFoundException ex) {\n ex.printStackTrace();\n }\n</code></pre>\n\n<p>In this case you will decide what to do when you handle the FileNotFoundException exception, just for simplicity in this case I will print the error message.</p>\n\n<p>After this you can start to read double values from the file;</p>\n\n<pre><code>ArrayList<Double> grades = new ArrayList<Double>();\n try {\n List<String> lines = Files.readAllLines(file.toPath());\n for (String line : lines) {\n grades.add(Double.parseDouble(line));\n }\n } catch (IOException ex) {\n ex.printStackTrace();\n }\n</code></pre>\n\n<p>Again, you have to decide what to do when you encounters a reading file error instead of just printing the error.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T11:11:36.843",
"Id": "225518",
"ParentId": "225501",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "225509",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T03:51:27.613",
"Id": "225501",
"Score": "4",
"Tags": [
"java",
"beginner",
"algorithm",
"file"
],
"Title": "Course Statistics Using Arrays and Files"
}
|
225501
|
<p>I am learning C++ and I've written a text-based classic Tetris game using OOP design. I would really appreciate it if someone could take a look at it and review the OOP design and tell me if something is particularly bad (or particularly good). I aim to make my code expressive, maintainable, with good abstraction levels.</p>
<p><a href="https://i.stack.imgur.com/3HeRI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3HeRI.png" alt="enter image description here"></a></p>
<p><strong>main.cpp</strong></p>
<pre><code>#include "Cell.h"
#include "Piece.h"
#include "Board.h"
#include "Game.h"
int main() {
Game start_game;
return 0;
}
</code></pre>
<p><strong>Game.h</strong></p>
<pre><code>#if !defined(GAME_H_)
#define GAME_H_
#include <iostream>
#include <vector>
#include <algorithm>
#include "windows.h"
#include "Cell.h"
#include "Piece.h"
#include "Board.h"
class Game {
private:
Board board;
Piece curr_piece;
std::vector<Cell> final_pionts;
int score;
int speed;
bool run;
public:
Game();
void controls();
void running();
bool hit_built_points_down();
bool checked_move(enum move_direction dir);
bool checked_rotate();
void draw();
void refresh_final_points();
void ClearScreen();
bool game_over();
bool regame();
};
#endif
</code></pre>
<p><strong>Game.cpp</strong></p>
<pre><code>#include "Game.h"
Game::Game()
:score{0}, speed{200}, run{true} {
do {
system("cls");
board = Board(20, 20);
running();
} while(regame());
}
void Game::running() {
while (!game_over()) {
curr_piece = Piece(Cell((board.get_width()-1)/2, board.get_height(), 'O'));
while (!hit_built_points_down()) {
speed = 200;
ClearScreen();
curr_piece.fall_down();
score += board.remove_row();
board.refresh();
refresh_final_points();
draw();
controls();
Sleep(speed);
}
}
}
bool Game::game_over() {
for (const auto &pnt : board.get_built_points())
if (pnt.get_y() >= board.get_height() - 2) {
return true;
}
return false;
}
bool Game::regame() {
std::cout << "======Game over======" << std::endl;
std::cout << "replay ?? (y/n) " << std::endl;
char c{};
bool isvalid{false};
do {
std::cin >> c;
if (c == 'y')
return true;
else if (c == 'n')
return false;
else {
std::cout << "invalid entry\n";
isvalid = true;
}
} while(isvalid);
}
bool Game::hit_built_points_down() {
for (const auto &next_piece_pnt : curr_piece.next_fall_down_body()) {
//hit the ground
if (next_piece_pnt.get_y() == 0) {
board.insert_to_built_points(curr_piece.get_body());
return true;
}
//hit built points
for (const auto &built_pnt : board.get_built_points())
if (next_piece_pnt == built_pnt) {
board.insert_to_built_points(curr_piece.get_body());
return true;
}
}
return false;
}
bool Game::checked_move(enum move_direction dir) {
for (const auto &next_piece_pnt : curr_piece.next_move_body(dir)) {
if (next_piece_pnt.get_x() == 0 || next_piece_pnt.get_x() == (board.get_width() - 1))
return false;
for (const auto &built_pnt : board.get_built_points())
if (built_pnt == next_piece_pnt)
return false;
}
curr_piece.move(dir);
return true;
}
bool Game::checked_rotate() {
for (const auto &next_piece_pnt : curr_piece.next_rotate_body()) {
if (next_piece_pnt.get_x() == 0 || next_piece_pnt.get_x() == (board.get_width() - 1))
return false;
for (const auto &built_pnt : board.get_built_points())
if (built_pnt == next_piece_pnt)
return false;
}
curr_piece.rotate();
return true;
}
void Game::refresh_final_points() {
final_pionts = board.get_all_points();
for (auto &final_pnt : final_pionts)
for (auto piece_pnt : curr_piece.get_body())
if (final_pnt == piece_pnt)
final_pnt = piece_pnt;
}
void Game::draw() {
for (int i{board.get_height() - 1}; i >= 0 ; i--) {
for (int j{0}; j < board.get_width(); j++) {
auto t = std::find(final_pionts.begin(), final_pionts.end(), Cell(j, i));
std::cout << t->get_type();
}
std::cout << std::endl;
}
std::cout << "\n Score = " << score << std::endl;
}
void Game::controls() {
if (GetAsyncKeyState(VK_UP))
checked_rotate();
else if (GetAsyncKeyState(VK_DOWN))
speed = 10;
else if (GetAsyncKeyState(VK_RIGHT))
checked_move(right);
else if (GetAsyncKeyState(VK_LEFT))
checked_move(left);
else if (GetAsyncKeyState('P')) {
//run = gameover();
}
}
void Game::ClearScreen() {
// Function which cleans the screen without flickering
COORD cursorPosition; cursorPosition.X = 0; cursorPosition.Y = 0; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), cursorPosition);
}
</code></pre>
<p><strong>Board.h</strong></p>
<pre><code>#if !defined(BOARD_H_)
#define BOARD_H_
#include "Piece.h"
#include <vector>
#include <algorithm>
class Board {
private:
int width;
int height;
std::vector<Cell> all_points;
std::vector<Cell> built_points;
public:
Board(int width = 30, int height = 30);
int get_width() {return width;}
int get_height() {return height;}
std::vector<Cell> get_all_points() {return all_points;}
std::vector<Cell> get_built_points() {return built_points;}
void set_built_points(std::vector<Cell> built_points) {this->built_points = built_points;}
void set_border();
void insert_to_built_points (std::vector<Cell> insert_points);
int remove_row();
void refresh();
};
#endif
</code></pre>
<p><strong>Board.cpp</strong></p>
<pre><code>#include "Board.h"
Board::Board(int width, int height)
:width{width}, height{height} {
for (int i{0}; i < width; i++)
for (int j{0}; j < height; j++)
all_points.push_back(Cell(i, j));
set_border();
}
void Board::refresh() {
set_border();
for (auto &all_pnt : all_points)
for (auto built_pnt : built_points)
if (all_pnt == built_pnt)
all_pnt = built_pnt; //seting the char of all_pnt to built pnt
}
void Board::insert_to_built_points (std::vector<Cell> insert_points) {
built_points.insert(built_points.end(), insert_points.begin(), insert_points.end());
}
void Board::set_border() {
for (auto &point : all_points) {
if (point.get_x() == 0 || point.get_y() == 0 || point.get_x() == width - 1 || point.get_y() == height - 1)
point.set_type('#');
else
point.set_type(' ');
}
}
int Board::remove_row() {
int removed_rows{0};
int i{1};
while(i < height) {
int built_points_count = std::count_if(built_points.begin(), built_points.end(), [i](const Cell &point) {
return (point.get_y() == i);
});
if (built_points_count == (width - 2)) {
removed_rows++;
// earse-remove idiom
auto it = std::remove_if(built_points.begin(), built_points.end(), [i](Cell point) {
return (point.get_y() == i);
});
built_points.erase(it, built_points.end());
std::for_each(built_points.begin(), built_points.end(), [i](Cell &point) {
if (point.get_y() > i)
point.move(0, -1);
});
} else
i++;
}
return removed_rows;
}
</code></pre>
<p><strong>Piece.h</strong></p>
<pre><code>#if !defined(PIECE_H_)
#define PIECE_H_
#include "Cell.h"
#include <vector>
#include <stdlib.h>
#include <time.h>
enum piece_type {
t_piece,
i_piece,
o_piece,
l_piece,
j_piece,
s_piece,
z_piece
};
enum move_direction {
right = 1,
left = -1
};
class Piece {
private:
enum piece_type type;
std::vector<Cell> body;
Cell pos;
public:
Piece() = default;
Piece(Cell pos);
void fall_down();
std::vector<Cell> next_fall_down_body();
void move(enum move_direction dir);
std::vector<Cell> next_move_body(enum move_direction dir);
void rotate();
std::vector<Cell> next_rotate_body();
std::vector<Cell> get_body() {return body;}
void set_body(std::vector<Cell> body) {this->body = body;}
};
#endif
</code></pre>
<p><strong>Piece.cpp</strong></p>
<pre><code>#include "Piece.h"
Piece::Piece(Cell pos)
:pos{pos} {
srand(time(0));
type = static_cast<piece_type>(rand() % 7);
if (type == t_piece)
body = {pos, pos.shift_copy(1, 0), pos.shift_copy(-1, 0), pos.shift_copy(0, 1)};
else if (type == i_piece)
body = {pos, pos.shift_copy(0, -1), pos.shift_copy(0, 1), pos.shift_copy(0, 2)};
else if (type == o_piece)
body = {pos, pos.shift_copy(0, 1), pos.shift_copy(1, 0), pos.shift_copy(1, 1)};
else if (type == l_piece)
body = {pos, pos.shift_copy(0, 1), pos.shift_copy(0, -1), pos.shift_copy(1, -1)};
else if (type == j_piece)
body = {pos, pos.shift_copy(-1, 0), pos.shift_copy(0, 1), pos.shift_copy(0, 2)};
else if (type == s_piece)
body = {pos, pos.shift_copy(-1, 0), pos.shift_copy(0, 1), pos.shift_copy(1, 1)};
else if (type == z_piece)
body = {pos, pos.shift_copy(1, 0), pos.shift_copy(0, 1), pos.shift_copy(-1, 1)};
}
void Piece::fall_down() {
pos.move(0, -1);
for (auto &point : body)
point.move(0, -1);
}
std::vector<Cell> Piece::next_fall_down_body() {
std::vector<Cell> next_body;
for (const auto &point : body)
next_body.push_back(point.shift_copy(0, -1));
return next_body;
}
void Piece::move(enum move_direction dir) {
pos.move(dir, 0);
for (auto &point : body)
point.move(dir, 0);
}
std::vector<Cell> Piece::next_move_body(enum move_direction dir) {
std::vector<Cell> next_body;
for (const auto &point : body)
next_body.push_back(point.shift_copy(dir, 0));
return next_body;
}
void Piece::rotate() {
for (auto &point : body) {
int point_x = point.get_x() - pos.get_x();
int point_y = point.get_y() - pos.get_y();
point.set_coordinate( (-1 * point_y) + pos.get_x() , point_x + pos.get_y());
}
}
std::vector<Cell> Piece::next_rotate_body() {
std::vector<Cell> next_body;
for (const auto &point : body) {
int point_x = point.get_x() - pos.get_x();
int point_y = point.get_y() - pos.get_y();
next_body.push_back(Cell((-1 * point_y) + pos.get_x() , point_x + pos.get_y()));
}
return next_body;
}
</code></pre>
<p><strong>Cell.h</strong></p>
<pre><code>#if !defined(CELL_H_)
#define CELL_H_
#include <iostream>
class Cell {
private:
int x;
int y;
char type;
public:
Cell(int x = 0, int y = 0, char type = ' ');
int get_x() const {return x;}
int get_y() const {return y;}
char get_type() const {return type;}
void set_type(char c) {type = c;}
Cell shift_copy(int x_shift, int y_shift) const;
void move(int x_move, int y_move);
void set_coordinate(int x_new, int y_new);
bool operator==(const Cell &rhs) const;
};
#endif
</code></pre>
<p><strong>Cell.cpp</strong></p>
<pre><code>#include "Cell.h"
Cell::Cell(int x, int y, char type)
:x{x}, y{y}, type{type} {}
bool Cell::operator==(const Cell &rhs) const {
return (x == rhs.get_x() && y == rhs.get_y());
}
Cell Cell::shift_copy(int x_shift, int y_shift) const {
return Cell(x + x_shift, y + y_shift, type);
}
void Cell::move(int x_move, int y_move) {
x += x_move;
y += y_move;
}
void Cell::set_coordinate(int x_new, int y_new) {
x = x_new;
y = y_new;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T07:24:34.027",
"Id": "437880",
"Score": "2",
"body": "This is a video of the game I think it will be clearer \nhttps://youtu.be/te_buNoy6SM"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T10:14:17.517",
"Id": "437894",
"Score": "0",
"body": "Why #include windows and not use #pragma once?"
}
] |
[
{
"body": "<p>Hi Mahmoud and welcome to CodeReview!</p>\n\n<p>It is great that you want to learn C++. Your project already is advanced and it is quite an achievement that you came to a working solution. As the project is large, I\nwill more focus on overall design than on small improvements. Also, I lack a windows build machine, so I cannot run the program, though I expect it to work just fine.</p>\n\n<h1>General</h1>\n\n<ul>\n<li>Only make functions public, that are really required from the outside of a class.</li>\n<li>Review your naming. There are quite some examples of functions where the intent is not really clear (<code>hit_built_points_down()</code>, <code>refresh_final_points()</code>). Why is isn't <code>isvalid</code> in <code>Game::regame()</code> called <code>invalid</code>? </li>\n<li>Separate the data storage, game logic and state display. If you want to exchange the user interface at one point in the future, why should you need to touch the Board storage? </li>\n<li>Keep constructors lightweight. You should only initialize internal variables, no logic belongs here.</li>\n<li>Reduce the number of includes in the headers. Only add headers that are required (because you reference a type defined in them).</li>\n<li>Learn about passing variables by reference (Piece::get_body()).</li>\n</ul>\n\n<h1>Game</h1>\n\n<ul>\n<li>Do not put the loop in the constructor. Move it out of game, as it's intent is \"running multiple games in a row\". Same for <code>Game::regame()</code>.</li>\n<li>Why do you configure a speed when you override it before the first use? Remove it for now, too many moving parts are harder to handle.</li>\n<li>You don't need <code>check_move</code> and <code>check_rotate</code> functions. Create a copy of the current piece, move and rotate and then check for collisions.</li>\n</ul>\n\n<h1>Board</h1>\n\n<ul>\n<li>Consider changing the design. Why not having a vector of rows where each row consists of multiple cells? If your data-structure makes a cell available via its coordinates, what does the cell need to store in extent? Also, having a row based data-structure allows for easier deletion and prepending of rows. </li>\n<li>You should store width and height as a constant, it will not change during the game.</li>\n</ul>\n\n<h1>Piece</h1>\n\n<ul>\n<li>Do not call <code>srand(time(0))</code> here, it is not related to a \"Piece\". This should be done at the main class. Also pass the type as a parameter.</li>\n<li>I would not pass the Cell to the constructor, you can easily move the piece afterwards.</li>\n<li>As said further, remove the <code>next_</code> functions and simply copy the piece and do collision checking with the copy.</li>\n<li>Remove <code>set_body</code> it is not referenced from anywhere.</li>\n</ul>\n\n<h1>Cell</h1>\n\n<ul>\n<li><code>shift_copy</code> should be split into two functions, a copy constructor and a shift (move?) function. You already have both.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T10:53:27.697",
"Id": "225516",
"ParentId": "225503",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "225516",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T05:26:04.263",
"Id": "225503",
"Score": "0",
"Tags": [
"c++",
"object-oriented",
"game",
"windows",
"tetris"
],
"Title": "Text-based Tetris game in C++"
}
|
225503
|
<p>The problem quoted:</p>
<p><a href="https://leetcode.com/problems/single-element-in-a-sorted-array/" rel="nofollow noreferrer">https://leetcode.com/problems/single-element-in-a-sorted-array/</a></p>
<p><em>Given a sorted array consisting of only integers where every element appears exactly twice except for one element which appears exactly once. Find this single element that appears only once.</em></p>
<pre><code>Example 1:
Input: [1,1,2,3,3,4,4,8,8]
Output: 2
Example 2:
Input: [3,3,7,7,10,11,11]
Output: 10
</code></pre>
<p>Note: Your solution <strong>should run in O(log n) time</strong> and O(1) space.</p>
<hr>
<p>The answer:</p>
<pre><code>var singleNonDuplicate = function(nums) {
var low = 0, high = nums.length - 2, mid;
while (low < high) {
mid = low + Math.floor((high - low) / 2);
if (mid % 2 === 1) mid--; // make sure it is even
if (nums[mid] !== nums[mid+1]) { // the single element already happened on the left
high = mid - 1;
} else {
low = mid + 2;
}
}
return nums[low];
};
</code></pre>
<p>The fourth line:</p>
<pre><code>while (low < high) {
</code></pre>
<p>if changed to</p>
<pre><code>while (low <= high) {
</code></pre>
<p>can also pass all tests on the website. But which version is correct or more robust? </p>
<p>I also had to decide whether it is better to set the initial <code>high</code> to</p>
<pre><code>high = nums.length - 2
</code></pre>
<p>or to</p>
<pre><code>high = nums.length - 1
</code></pre>
<p>The same with </p>
<pre><code>high = mid - 1;
</code></pre>
<p>I wonder if it is best to set it to <code>mid - 1</code> or <code>mid - 2</code>. </p>
<p>It seems it can be complicated near the "end game", when there are 3, 5, 7, 9 remaining array elements, when the <code>mid</code>, <code>low</code>, <code>high</code> can be calculated in the way that the loop will not terminate or find the incorrect answer. If there are many elements remaining, such as 21, 31, etc, the algorithm in general works. It seems you have to consider the small cases when the number of remaining elements is small. </p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T05:39:16.583",
"Id": "225504",
"Score": "2",
"Tags": [
"javascript",
"algorithm",
"binary-search"
],
"Title": "Find Single Element in a Sorted Array, from LeetCode"
}
|
225504
|
<p>I need to have my <a href="https://codereview.stackexchange.com/questions/225454/logger-adapter-with-a-configurable-chain-of-responsibility-of-middlewares">logger middlewares</a> (<em>nodes</em> of a linked-list) in the <em>right</em> order so that they complement each other and work as desired.</p>
<p><em>Any</em> known middleware can be inserted anytime but the first and last. They will always be there. This means I'm always starting with two of them and the other ones will have to find their place somewhere inbetween.</p>
<h3>API</h3>
<p>I came up with the following algorithm. <code>middlewhere</code> is <em>some</em> current position. From there I <em>navigate</em> to the beginning, enumerate them and <code>Zip</code> another collection shifted by one. Then by using the <code>order</code> dictionary I check whether <code>insert</code> is after or equal <code>current</code> and before or equal <code>next</code> (in case multiple instances of the same middleware are used, they are <em>equal</em>). When I find the position, I call <code>InsertNext</code> and the work is done.</p>
<pre><code>public static Middleware InsertRelative(this Middleware middleware, Middleware insert, IDictionary<Type, int> order)
{
if (middleware.Previous is null && middleware.Next is null)
{
throw new ArgumentException("There need to be at least two middlewares.");
}
var first = middleware.First();
var zip = first.Enumerate(m => m.Next).Zip(first.Enumerate(m => m.Next).Skip(1), (current, next) => (current, next));
foreach (var (current, next) in zip)
{
var canInsert =
order[insert.GetType()] >= order[current.GetType()] &&
order[insert.GetType()] <= order[next.GetType()];
if (canInsert)
{
return current.InsertNext(insert);
}
}
return default; // This should not never be reached.
}
</code></pre>
<h3>Demo</h3>
<p>Here's a working demo. I use three more helpers: <code>First</code>, <code>Last</code> and <code>Enumerate</code> to <em>navigate</em> the chain. The other classes are <em>dummies</em> that represent the types of middlewares from the other question or new ones that I've created since.</p>
<pre><code>void Main()
{
var middlewareOrder = new[]
{
typeof(PropertySetter),
typeof(Stopwatch),
typeof(Attachment),
typeof(Lambda),
typeof(Scope),
typeof(Serializer),
typeof(Filter),
typeof(Transaction),
typeof(Echo),
};
var positions = middlewareOrder.Select((m, i) => (m, i)).ToDictionary(t => t.m, t => t.i);
positions.Dump();
// Default configuration.
var middleware = new PropertySetter().InsertNext(new Echo());
// Insert some new middlewares in an arbitrary order.
middleware
.InsertRelative(new Attachment(), positions)
.InsertRelative(new Serializer(), positions)
.InsertRelative(new Scope(), positions)
.InsertRelative(new PropertySetter(), positions);
// Show their order.
middleware.First().Enumerate(m => m.Next).Select(m => m.GetType()).Dump();
}
public abstract class Middleware
{
public Middleware Previous { get; private set; }
public Middleware Next { get; private set; }
public T InsertNext<T>(T next) where T : Middleware
{
(next.Previous, next.Next, Next) = (this, Next, next);
return next;
}
}
public static class LoggerMiddlewareExtensions
{
public static Middleware InsertRelative(this Middleware middleware, Middleware insert, IDictionary<Type, int> order)
{
if (middleware.Previous is null && middleware.Next is null)
{
throw new ArgumentException("There need to be at least two middlewares.");
}
var first = middleware.First();
var zip = first.Enumerate(m => m.Next).Zip(first.Enumerate(m => m.Next).Skip(1), (current, next) => (current, next));
foreach (var (current, next) in zip)
{
var canInsert =
order[insert.GetType()] >= order[current.GetType()] &&
order[insert.GetType()] <= order[next.GetType()];
if (canInsert)
{
return current.InsertNext(insert);
}
}
return default;
}
public static Middleware First(this Middleware middleware)
{
return middleware.Enumerate(m => m.Previous).Last();
}
public static Middleware Last(this Middleware middleware)
{
return middleware.Enumerate(m => m.Next).Last();
}
public static IEnumerable<Middleware> Enumerate(this Middleware middleware, Func<Middleware, Middleware> direction)
{
do
{
yield return middleware;
} while (!((middleware = direction(middleware)) is null));
}
}
public class PropertySetter : Middleware { }
public class Stopwatch : Middleware { }
public class Attachment : Middleware { }
public class Lambda : Middleware { }
public class Scope : Middleware { }
public class Serializer : Middleware { }
public class Filter : Middleware { }
public class Transaction : Middleware { }
public class Echo : Middleware { }
</code></pre>
<hr>
<h3>Questions</h3>
<p>I don't think I'll be having hundreds of middlewares so this few helpers won't impact the performance terribly but maybe you can still think of anything more clever?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T09:09:30.113",
"Id": "437885",
"Score": "0",
"body": "Would you ever need to change the order of types?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T09:13:49.223",
"Id": "437886",
"Score": "0",
"body": "@dfhwze I highly doubt it but it is possible that a new non-built-in-type needs to be placed somewhere. Like when an application requires something specific in that domain but not general enough to be reused elsewhere."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T09:15:56.967",
"Id": "437888",
"Score": "1",
"body": "Should middleware be able to get deactivated/activated, regardless of whether they are included in the chain? Or would you just remove them and insert them again? Perhaps it's just a one-time fixed setup at bootstrap."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T09:19:56.597",
"Id": "437890",
"Score": "0",
"body": "@dfhwze this is an interesting question and a great idea... Some of them could definitely be switchable but I'll have to check whether this would work for all of them (especially with `Stopwatch` and `Scope` that currently relies on `Dispose`)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T09:21:37.767",
"Id": "437891",
"Score": "0",
"body": "The ones that don't defer entries to the next in chain, could use a flag like that. Actually, the ones that defer, could also use that flag and just pass the entries when deactivated :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T09:31:07.907",
"Id": "437892",
"Score": "1",
"body": "@dfhwze I with I could accept your comment ;-]"
}
] |
[
{
"body": "<h3>Design Review</h3>\n\n<p>This pattern of using a comparison dictionary to configure the chain seems like a convoluted work-around for just creating the chain and being able to activate/deactivate certain middleware items in the chain.</p>\n\n<p>Your input could be used as a factory instead.</p>\n\n<pre><code>var middleware = new PropertySetter(); // .. pick a root\nmiddleware = middleware.InsertNext(new Stopwatch());\n// and so on ..\nreturn middleware.First();\n</code></pre>\n\n<p>You could then implement an <code>IsActive</code> flag. For instance, in your logging middleware (see referenced question):</p>\n\n<blockquote>\n<pre><code>public abstract void Invoke(Log request);\n</code></pre>\n</blockquote>\n\n<p>You could change the pattern to:</p>\n\n<pre><code>protected abstract void InvokeCore(Log request);\n\npublic void Invoke(Log request)\n{\n if (IsActive)\n {\n InvokeCore(request);\n }\n\n Next?.Invoke(request);\n}\n</code></pre>\n\n<p>Also think about what to do when togling the <code>IsActive</code> flag. Some middleware might have local state that needs to be flushed to the next middleware in chain.</p>\n\n<pre><code>protected virtual void ActivateCore(bool active) {}\n\npublic bool IsActive\n{\n get => active; // private field\n set \n {\n if (active != value)\n {\n active = value;\n ActivateCore(value);\n }\n }\n}\n</code></pre>\n\n<hr>\n\n<h3>Conventions</h3>\n\n<ul>\n<li><code>InsertRelative</code> returns <code>default</code> when unable to insert the middleware. I would throw an exception here.</li>\n<li>There is a general lack of argument checks against <code>null</code> in your public API.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T14:55:24.353",
"Id": "437916",
"Score": "1",
"body": "Rewritten. Works like a charm! This was another silver-bullet ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T09:01:59.283",
"Id": "440848",
"Score": "1",
"body": "OT: once you hit 25k the green internet points are worthless because they don't give you any new privileges :-\\"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T09:05:42.757",
"Id": "440849",
"Score": "0",
"body": "@t3chb0t Except for a long shot at the legendary badge ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T09:08:21.507",
"Id": "440850",
"Score": "1",
"body": "badges are borig, privileges are cool ;-] and there is only one badge that gives you the single-duplicate-vote priviledge. All others are just decoration hehe"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T09:43:33.050",
"Id": "225511",
"ParentId": "225507",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "225511",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T06:28:36.293",
"Id": "225507",
"Score": "1",
"Tags": [
"c#",
"linked-list",
"extension-methods"
],
"Title": "Insert new middleware at the \"right\" location"
}
|
225507
|
<p>I have written a simple singly linked list in C++. I have previously had a data structure in an interview criticised for being too C-like (no iterators and using new/delete) instead of smart pointers. For the iterator, I'm not quite sure what I should do for operator->. Should its behaviour change depending on whether T is a primitive type or not? Also, what should be done so that this iterator would be compatible with stl algorithms such as sort etc?</p>
<p>For the question of using smart pointers or not, IMO the handling of the allocation/freeing of memory in the constructors is sufficient and is better than each ListNode having a shared pointer to the next node. Is this logic correct?</p>
<p>Thanks!</p>
<pre class="lang-cpp prettyprint-override"><code>template<typename T>
class List{
public:
struct ListNode{
T val_;
ListNode *next_;
ListNode() : val_(T()), next_(nullptr){}
ListNode(const T& val) : val_(val), next_(nullptr){}
ListNode(const T& val, ListNode *next) : val_(val), next_(next){}
ListNode(ListNode *next) : val_(T()), next_(next){}
};
class iterator{
public:
using value_type = ListNode;
using reference = ListNode&;
using pointer = ListNode*;
using difference_type = std::ptrdiff_t;
using iterator_category = std::forward_iterator_tag;
iterator(pointer ptr) : ptr_(ptr){}
bool operator==(const iterator &other){return other.ptr_ == ptr_;}
bool operator!=(const iterator &other){return other.ptr_ != ptr_;}
iterator& operator++(){
ptr_ = ptr_->next_;
return *this;
}
iterator operator++(int arg){
iterator tmp = *this;
ptr_ = ptr_->next_;
return tmp;
}
pointer operator->(){
return ptr_;
}
reference operator*(){
return *ptr_;
}
private:
pointer ptr_;
};
ListNode *tail_, *before_begin_;
List() : tail_(new ListNode), before_begin_(new ListNode(tail_)){ }
~List(){
ListNode *current = before_begin_;
while(current != tail_){
ListNode *next = current->next_;
delete current;
current = next;
}
delete tail_;
}
List& operator=(const List &other){
if(before_begin_ != nullptr){
delete before_begin_;
}
if(tail_ != nullptr){
delete tail_;
}
return *this = List(other);
}
List(List &&other) noexcept{
before_begin_ = other.before_begin_;
tail_ = other.tail_;
other.before_begin_ = nullptr;
other.tail_ = nullptr;
}
List& operator=(List &&other) noexcept{
before_begin_ = other.before_begin_;
other.before_begin_ = nullptr;
tail_ = other.tail_;
other.tail_ = nullptr;
return *this;
}
List(const List &other) {
tail_ = new ListNode(other.tail_);
before_begin_ = new ListNode(other.before_begin_->val_, tail_);
ListNode *other_current = other.before_begin_;
ListNode *other_tail = other.tail_;
ListNode *current = before_begin_;
while(other_current != other_tail){
current->next_ = new ListNode(other_current->val_);
current = current->next_;
other_current = other_current->next_;
}
current->next_ = tail_;
}
T& front(){
return before_begin_->next_->val_;
}
void pop_front(){
ListNode *tmp = before_begin_->next_;
before_begin_->next_ = tmp->next_;
delete tmp;
}
iterator push_front(const T& val){
ListNode *tmp = before_begin_->next_;
before_begin_->next_ = new ListNode(val, tmp);
return iterator(before_begin_->next_);
}
iterator insert_after(iterator position, const T& val){
ListNode *tmp = position->next_;
position->next_ = new ListNode(val, tmp);
return iterator(position->next_);
}
iterator erase_after(iterator position){
ListNode *tmp = position->next_;
position->next_ = tmp->next_;
delete tmp;
return iterator(position->next_);
}
iterator begin(){
return iterator(before_begin_->next_);
}
iterator end(){
return iterator(tail_);
}
};
</code></pre>
|
[] |
[
{
"body": "<p>I don't see why not using smart pointers in such a basic data structure is bad. You may use <code>std::unique_ptr</code> for allocation and de-allocation of your ListNodes, but in the end you'll just introduce a new header and STL dependency, so in this case I'd think it's fine doing without.\nFor primitive types, what should <code>operator-></code> return in your opinion? \nTo get compatibility with standard algorithms, see on how STL containers implement common functions.</p>\n\n<ul>\n<li>Do you need access to <code>ListNode</code> from the outside of the class? Consider making it <code>private</code>. Same goes for <code>tail_</code> and <code>before_begin_</code>.</li>\n<li>In <code>iterator operator++(int arg)</code> you can remove the <code>arg</code> it is not needed and compilers may complain about unused variables with the right warning settings.</li>\n<li>Why <code>before_begin_</code>? Isn't a <code>ListNode* first;</code> better? </li>\n<li>In your constructors you're initializing <code>before_begin_</code> and <code>tail_</code>, but in your move-constructors you're leaving the members with <code>nullptr</code>s. Consider having the move functions leaving the functions in a default constructed state (though having nullptrs is better IMO).</li>\n<li>Regarding <code>operator=</code> and copy construction, please read about the copy-and-swap idiom.</li>\n<li>using <code>erase_after</code> and <code>insert_after</code> is not very common. Check the STL documentation on how STL containers support erasing or inserting data.</li>\n<li>In <code>operator=</code> you'll leak memory if the list is filled. Maybe provide a <code>clear</code> method and use it in <code>~List()</code> and <code>operator=()</code>.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T11:29:28.193",
"Id": "225519",
"ParentId": "225512",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T10:34:41.790",
"Id": "225512",
"Score": "2",
"Tags": [
"c++",
"linked-list",
"iterator"
],
"Title": "C++ singly linked list with iterator"
}
|
225512
|
<p>I wrote a Snake Game in C++ and I have practiced some OOP approaches on windows 7. </p>
<p>What I need:</p>
<ol>
<li>advice how to improve code</li>
<li>Most important how to made what Snake on <code>CollisionCheck</code> method do different "things" for example if snake eats Fruit snake will grow by one. if Snake eats self or wall .game collapse etc/</li>
<li>Any ideas how to add functional what you can make maps in notepad and import into the game?</li>
</ol>
<h1>Source.cpp</h1>
<pre class="lang-cpp prettyprint-override"><code>// Source.cpp : Defines the entry point for the console application.
//
#include <conio.h>
#include <iostream>
#include "stdafx.h"
#include"Snake.h"
using namespace std;
int main()
{
Snake snake(20, 20);
Fruit fruit(10,10);
Wall wall(15, 15);
int i = 0;
while (i < 800) {
++i;
snake.Move();
fruit.Draw();
wall.Draw();
if (snake.CollisionCheck(&fruit))break;
Sleep(100);
}
std::cout << " END GAME! "<<std::endl;
cout << snake.SnakeLength();
return 0;
}
</code></pre>
<h1>Snake.h</h1>
<pre><code> #pragma once
#include <iostream>
#include <vector>
#include "Box.h"
#include <conio.h>
using namespace std;
#define MAX_SNAKE_SIZE 500
class Snake
{
public:
Snake(int StartX, int StartY);
~Snake();
void ShowSelf();
void TurnRigth();
void TurnLeft();
void TurnUp();
void TurnDown();
void AddBox(); //adds element at the end of the snake
void Move();
bool CollisionCheck(Obstacle*object);
int SnakeLength() { return box.size(); };
private:
int x;
int y;
char dir;//current direction of snake
vector<Box> box;//no dinamic array because sweet pain
int length;
};
</code></pre>
<h1>Snake.cpp</h1>
<pre><code>#include "stdafx.h"
#include "Snake.h"
#include <windows.h>
#include <conio.h>
//#define DEBUG
enum Object
{
BOX = 0,
FRUIT=1,
WALL=2
};
Snake::Snake(int StartX,int StartY)
{
x = StartX;
y = StartY;
length = 1;
Box obj1(x,y);
//obj1.SetSymbol('S');
box.push_back(obj1);
}
Snake::~Snake()
{
#ifdef DEBUG
for (int i = 0; i < box.size(); i++)
{
Box temp = box[i];
temp.ShowCord();
}
#endif
}
void Snake::ShowSelf()
{
for (unsigned int i = 0; i < box.size(); i++)
{
box[i].Draw();
}
}
void Snake::TurnRigth()
{
dir = 'd';
}
void Snake::TurnLeft()
{
dir = 'a';
}
void Snake::TurnUp()
{
dir = 'w';
}
void Snake::TurnDown()
{
dir = 's';
}
void Snake::AddBox()
{
int size = box.size();
Box temp(box[size-1].GetX(), box[size-1].GetY());
box.push_back(temp);
}
void Snake::Move()
{
system("cls");
//allows Snake to move
for (int i = box.size()-1; i>0; i--)
{
box[i].SetCord(box[i - 1].GetX(), box[i - 1].GetY());
}
//check what kind of button was pressed
char tempdir = dir;
if(_kbhit())dir = _getch();
if (dir == 'w') {
if (tempdir == 's') { //stops snake move backwards
box[0].MoveDown();
dir = tempdir;
}
else box[0].MoveUp();
}
else if (dir == 'd') {
if (tempdir == 'a') { //stops snake move backwards /
box[0].MoveLeft();
dir = tempdir;
}
else box[0].MoveRigth();
}
else if (dir == 's') {
if (tempdir == 'w') { //stops snake move backwards
box[0].MoveUp();
dir = tempdir;
}
else box[0].MoveDown();
}
else if (dir == 'a') {
if (tempdir == 'd') { //stops snake move backwards
box[0].MoveRigth();
dir = tempdir;
}
else box[0].MoveLeft();
}
for (unsigned int i = 0; i < box.size(); i++) //draw Snake
{
box[i].Draw();
}
}
bool Snake::CollisionCheck(Obstacle *object) //hiting magick appiers
{
int boxX = box[0].GetX(); int boxY = box[0].GetY();
//check if snake ate self or not
for (int i = 1; i < box.size(); ++i)
{
if ((box[0].GetX() == box[i].GetX()) && (box[0].GetY() == box[i].GetY())) { return true; }
}
//check if it hitten anything else is hitted
if ((object->GetX() == box[0].GetX())&&(object->GetY() == box[0].GetY()))
{
int obstacle = object->onCollision();
if (obstacle == FRUIT) { //deletes old glyph //spawns object at new coord
this->AddBox();
return false;
}
/*else if (obstacle == BOX)
{
return 0;
}*/
else if (obstacle == WALL)
{
return 0;
}
}
return false;
}
</code></pre>
<h1>Box.h where all potentional elements of game is (walls,Fruit,snake elements)</h1>
<pre><code>#pragma once
#include <iostream>
#include <conio.h>
#include <iostream>
#include <windows.h>
class Obstacle
{
public:
Obstacle(int x, int y);
void SetX(int x) { this->x = x; };
void SetY(int y) { this->y = y; };
int GetX() { return x; };
int GetY() { return y; };
void Draw();
void Erase();
void NewSpawn();//Spawns Obstacle at new coords
virtual int onCollision();//check if hited or not
void SetSymbol(char symbol) { this->symbol = symbol; };
protected:
char symbol;
int x;
int y;
};
class Box :public Obstacle
{
public:
Box(int x, int y) :Obstacle(x, y) { this->SetSymbol('o'); };
void SetCord(int x, int y);
void MoveUp();
void MoveDown();
void MoveRigth();
void MoveLeft();
int onCollision()override;
};
class Fruit :public Obstacle
{
public:
Fruit(int x, int y) :Obstacle(x, y) { this->SetSymbol('F'); };
int onCollision ()override;
};
class Wall :public Obstacle
{
public:
Wall(int x, int y) :Obstacle(x, y) { this->SetSymbol('#'); };
int onCollision()override;
};
</code></pre>
<h1>Box.cpp</h1>
<pre><code>#include "stdafx.h"
#include "Box.h"
#include <stdlib.h>
#include"time.h"
enum Object
{
BOX = 0,
FRUIT = 1,
WALL = 2
};
//place symbol at specific coords in console
void gotoxy(int x, int y)
{
COORD c = { x, y };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), c);
}
void Box::SetCord(int x, int y)
{
this->x = x;
this->y = y;
}
void Box::MoveUp()
{
y--;
}
void Box::MoveDown()
{
++y;
}
void Box::MoveRigth()
{
x++;
}
void Box::MoveLeft()
{
x--;
}
int Box::onCollision()
{
return BOX;
}
Obstacle::Obstacle(int x, int y)
{
this->x = x;
this->y = y;
}
void Obstacle::Erase()
{
gotoxy(x, y);
std::cout << " ";
}
void Obstacle::Draw()
{
gotoxy(x, y);
std::cout << symbol;
}
void Obstacle::NewSpawn()
{
srand(time(NULL));//need to fix that
x = rand() % 80;
y = rand() % 23;
}
int Obstacle::onCollision()
{
return BOX;
}
int Fruit::onCollision()
{
this->Erase();
this->NewSpawn();
return FRUIT;
}
int Wall::onCollision()
{
return WALL;
}
</code></pre>
|
[] |
[
{
"body": "<p>First on code review we prefer to see code without debug statements or commented out code because that means the code may not be ready for review.</p>\n\n<p><strong>The Good</strong><br>\nThe class <code>Obstacle</code> seems to be a well defined object, it could be an <a href=\"https://en.cppreference.com/w/cpp/language/abstract_class\" rel=\"nofollow noreferrer\">abstract</a> class if the body for the virtual function <code>onCollision()</code> was not defined by <code>Obstacle</code>. This would force every class that inherits from <code>Obstacle</code> to define the function <code>onCollision()</code>. For a reference on object oriented programming you might want to look at <a href=\"https://en.wikipedia.org/wiki/SOLID\" rel=\"nofollow noreferrer\">SOLID programming</a> which is a set of 5 programming principles that apply to objct oriented programming.</p>\n\n<p>The <code>main()</code> function is nice and concise, however, you might want to implement a <code>draw</code> function that calls the object specific <code>draw</code> functions.</p>\n\n<p><strong>Avoid Using Namespace STD</strong><br>\nIf you are coding professionally you probably should get out of the habit of using the \"using namespace std;\" statement. The code will more clearly define where cout and other functions are coming from (std::cin, std::cout). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The function cout you may override within your own classes. This <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">stack overflow question</a> discusses this in more detail.</p>\n\n<p>The <code>using namespace std;</code> really shouldn't be in header files (include files) at all. It can make tracing name collisions very difficult. Keep in mind that you may not always be the one maintaining the code.</p>\n\n<p><strong>The Usage of the this Pointer</strong><br>\nUnlike some languages such as PHP, the <code>this pointer</code> is not required when accessing methods or variables within a class. Public methods or variables from other classes need to be referenced by the variable name of the object or <code>CLASSNAME::MethodName()</code> but within a class all methods public or private are known at compile and link time. The only time the <code>this pointer</code> might be necessary is when a <a href=\"https://stackoverflow.com/questions/993352/when-should-i-make-explicit-use-of-the-this-pointer\">variable local to the function</a> has the same name as a variable declared in the class, such as in <code>Obstacle::SetSymbol(char symbol)</code>.</p>\n\n<p><strong>Defining Constants in C++</strong><br>\nThere are a lot of Magic Numbers in the <code>main()</code> function (10, 15, 20, 100, 800), it might be better to create symbolic constants for all of them to make the code more readable and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintenance easier. While you do have one symbolic constant defined in <code>snake.h</code> it might be better defined in a more modern way.</p>\n\n<p>Numeric constants in code are sometimes referred to as <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">Magic Numbers</a>, because there is no obvious meaning for them.\nThe values for the variable k are defined by the problem, but it might be better to use symbolic constants rather than raw numbers in the switch statement. That would make the code easier to read and maintain. C++ provides a couple of methods for this, there could be an <code>enum</code>, or they could be defined as constants using <code>const</code> or <code>constexpr</code>. Any of these would make the code more readable. There is a discussion of this on <a href=\"https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad\">stackoverflow</a>.</p>\n\n<p>Using <code>#define CONSTANT VALUE</code> is generally discouraged in C++, the use of <code>const</code> or <code>constexpr</code> is prefered over #define. #define is not type safe where <code>const</code> or <code>constexpr</code> is.</p>\n\n<pre><code>#define MAX_SNAKE_SIZE 500\n</code></pre>\n\n<p>versus</p>\n\n<pre><code>const int MAX_SNAKE_SIZE = 500;\n</code></pre>\n\n<p><strong>One Set of Header and Source for Each Class</strong><br>\nThe files <code>Box.h</code> and <code>Box.cpp</code> define multiple classes, it would be easier to maintain the code if each class had it's own header and source file. Header files for classes that derive (inherit) from other classes can include the necessary header file. Some tools such as Visual Studio will add the <code>#include</code> statement when you use the class wizard to define a class with a dependency on another class.</p>\n\n<p>The <code>Obstacle</code> class definition would definitely be better in it's own header file.</p>\n\n<p><strong>Use the Type std::size_t When Indexing Arrays</strong></p>\n\n<p>There are a number of for loops that uses a type <code>int or unsigned int</code> variable as the loop control variable and reference <code>box.size()</code>. When indexing into arrays or vectors, it is better to use the type <code>std::size_t</code> which is defined as unsigned int in both C and C++. All of the STD container class <code>size</code> functions return the type <code>std::size_t</code>, there is also another type which can be used <code>std::ptrdiff_t</code>. You can find a discussion of size_t versus ptrdiff_t in this <a href=\"https://stackoverflow.com/questions/3174850/what-is-the-correct-type-for-array-indexes-in-c\">stackoverflow</a> question.</p>\n\n<p>One of the benefits of using an unsigned index is that a negative number can not be used to index an array. Since arrays in C start at zero this is important and prevent bugs. A second possible benefit of using <code>size_t</code> is that it may prevent warning messages about type mismatches from some compilers when using functions such as std::container.size().</p>\n\n<p><strong>Other Type Mismatches</strong><br>\nThe function <code>bool Snake::CollisionCheck(Obstacle *object)</code> returns both Boolean values and integers, it would be better if it returned only Boolean values.</p>\n\n<p><strong>Bugs</strong><br>\nThe Snake class has a variable <code>length</code> that is initialized in the constructor but it is never referenced again in the program, it probably should be updated when the snake collides with food.</p>\n\n<p>The Snake class has a function <code>int SnakeLength()</code> that return box.size() that should probably return snake.length (also type mismatch but the variable is being promoted from std::size_t to integer).</p>\n\n<p>When in debug mode the Snake destructor performs non-destructor operations.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T18:50:46.213",
"Id": "437942",
"Score": "0",
"body": "Well about it The Snake class variable length, I have suspicions what I do not need it because I am using vector for snake and I always can get \"length\" of the snake using vector methods 2)Why Fruit.Wall and Box classes are in one file because they are using \"gotoxy\" function(allows you to place symbol at specific place) and I tried to \"split\" project in separate project files and function just dies if I I have it in multiple files. 3)Main problem except others :) is how to make what different objects are passed to onCollision() method and they do different methods."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T19:11:44.343",
"Id": "437943",
"Score": "0",
"body": "Make gotoxy() a member of Obstacle so that it gets inherited, otherwise put it in a namespace and a header file and include it where needed. I meant to mention that in my review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T09:40:28.010",
"Id": "437997",
"Score": "0",
"body": "What about ->)**\"Main problem except others :) is how to make what different objects are passed to onCollision() method and they do different methods.\" **?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T12:24:45.350",
"Id": "438022",
"Score": "0",
"body": "@Inex Can't answer that part here due to code review guidelines. You MIGHT get an answer on stackoverflow.com but clean up the code first. Code review guidelines are https://codereview.stackexchange.com/help/how-to-ask and https://codereview.stackexchange.com/help/dont-ask."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T18:36:12.973",
"Id": "225540",
"ParentId": "225514",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T10:42:57.597",
"Id": "225514",
"Score": "3",
"Tags": [
"c++",
"object-oriented",
"console",
"windows",
"snake-game"
],
"Title": "Snake Game in C++ with OOP need advice"
}
|
225514
|
<p>I've written a bunch of functions that deal with handling files on a Linux system. I'm looking for critique on the whole class, in particular:</p>
<ul>
<li>Exception handling</li>
<li>Efficiency</li>
<li>Style</li>
</ul>
<p>I'd also like to discuss the practice on marking all these methods as static and using a class merely as namespace. </p>
<p>As far as I'm aware, all methods do what they should. Backwards compatibility with Python 2.x is a nonissue.</p>
<pre><code>import os
class FileIO:
@staticmethod
def find_subdir(filename):
try:
for root, dirs, files in os.walk(os.getcwd()):
if filename in files:
return os.path.relpath(root)
except IOError as e:
print(filename + " not found: " + str(e))
@staticmethod
def find_in_subdir(filename):
try:
for root, dirs, files in os.walk(os.getcwd()):
if filename in files:
return os.path.join(root, filename)
except IOError as e:
print(filename + " not found: " + str(e))
@staticmethod
def find_file(filename, directory):
try:
for root, dirs, files in os.walk(directory):
if filename in files:
return os.path.join(root, filename)
except IOError as e:
print(filename + " not found: " + str(e))
@staticmethod
def copy_file(source, destination):
try:
copyfile(source, destination)
except Exception as e:
print("Couldn't copy file: " + str(e))
@staticmethod
def check_file(path):
try:
os.path.exists(path)
return True
except Exception as e:
print("File not found or not accessible: " + str(e))
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><strong>Docstrings</strong>: You should include a <code>docstring</code> at the beginning of every method/class/module you write. This will allow documentation to identify what your code is supposed to do. <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\">PEP-8 Docstring Conventions</a></li>\n<li><strong>String formatting</strong>: Concatenating variables and strings can become messy. Instead, use a format string <code>f\"\"</code> to directly include variables into your string, without having to type cast them or alter them in any way to allow them to be added with strings.</li>\n<li><strong>Use specific exceptions (when you can)</strong>: Catching a general <code>Exception</code> isn't always the best idea. If you're preforming a task that generates only a specific kind of exception, catch that one.</li>\n</ul>\n\n<blockquote>\n <p>I'd also like to discuss the practice on marking all these methods as static and using a class merely as namespace.</p>\n</blockquote>\n\n<p>In this context, it's perfectly fine. All of these methods have the functionality of being used and called as a static method.</p>\n\n<p><strong><em>Updated Code</em></strong></p>\n\n<pre><code>\"\"\"\nModule Docstring:\nA description of your program goes here\n\"\"\"\n\nimport os\n\nclass FileIO:\n \"\"\"\n Namespace class for handling files on a Linux system\n \"\"\"\n @staticmethod\n def find_subdir(filename):\n \"\"\"\n Finds the subdirectory from `file_name`\n\n :param filename: Name of the file (duh)\n\n \"\"\"\n try:\n for root, dirs, files in os.walk(os.getcwd()):\n if filename in files:\n return os.path.relpath(root)\n\n except IOError as e:\n print(f\"{filename} not found: {e}\")\n\n @staticmethod\n def find_in_subdir(filename):\n \"\"\"\n Finds a file in a subdirectory\n\n :param filename: Name of the file (duh)\n\n \"\"\"\n try:\n for root, dirs, files in os.walk(os.getcwd()):\n if filename in files:\n return os.path.join(root, filename)\n\n except IOError as e:\n print(f\"{filename} not found: {e}\")\n\n @staticmethod\n def find_file(filename, directory):\n \"\"\"\n Find a file in a directory\n\n :param filename: Name of the file to find\n :param directory: Directory to find the file\n\n \"\"\"\n try:\n for root, dirs, files in os.walk(directory):\n if filename in files:\n return os.path.join(root, filename)\n\n except IOError as e:\n print(f\"{filename} not found: {e}\")\n\n @staticmethod\n def copy_file(source, destination):\n \"\"\"\n Creates a copy of a file at `source`, and places it at `destination`\n\n :param source: Path to the file to be copied\n :param destination: Path where the copied file should be placed\n\n \"\"\"\n try:\n copyfile(source, destination)\n\n except Exception as e:\n print(f\"Couldn't copy file: {e}\")\n\n @staticmethod\n def check_file(path):\n \"\"\"\n Checks if the passed file exists\n\n :param path: Path to the file\n\n \"\"\"\n try:\n os.path.exists(path)\n return True\n\n except FileNotFoundError as e:\n print(f\"File not found or not accessible: {e}\")\n\n\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T10:02:46.443",
"Id": "225572",
"ParentId": "225524",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "225572",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T14:51:33.717",
"Id": "225524",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"file"
],
"Title": "Python and FileIO"
}
|
225524
|
<h3>PROBLEM</h3>
<p>I'm trying to use <strong>authboss</strong> (<a href="https://github.com/volatiletech/authboss" rel="nofollow noreferrer">https://github.com/volatiletech/authboss</a>) with quicktemplate (<a href="https://github.com/valyala/quicktemplate" rel="nofollow noreferrer">https://github.com/valyala/quicktemplate</a>).</p>
<p>The authboss rendering system is defined by one interface: <a href="https://godoc.org/github.com/volatiletech/authboss/#Renderer" rel="nofollow noreferrer">Renderer</a>.</p>
<p>I have created two different versions of the solution and would like to know which one is best <strong>or if there is a third one better</strong>.</p>
<ol>
<li><p><a href="https://github.com/frederikhors/authbossQuicktemplate_1" rel="nofollow noreferrer">https://github.com/frederikhors/authbossQuicktemplate_1</a>, with factory pattern and initializators</p></li>
<li><p><a href="https://github.com/frederikhors/authbossQuicktemplate_2" rel="nofollow noreferrer">https://github.com/frederikhors/authbossQuicktemplate_2</a>, with interface and a <code>SetData(data authboss.HTMLData) (page PageImpl)</code> method</p></li>
</ol>
<h3>QUESTIONS</h3>
<p>I don't know what to improve for performances.</p>
<ul>
<li><p>Is it possible to do the same thing differently and less in terms of hardware resources?</p></li>
<li><p>Do you think I can improve using pointers somewhere?</p></li>
</ul>
<h3>RELEVANT CODE</h3>
<ol>
<li><p>Solution with Factory pattern and initializators:</p>
<pre class="lang-golang prettyprint-override"><code>type HTML struct {
templates map[string]func(authboss.HTMLData) templates.PageImpl
}
func (h *HTML) Load(names ...string) error {
for _, n := range names {
switch n {
case "login":
h.templates[n] = InitializeLoginPage
case "recover":
h.templates[n] = InitializeRecoverPage
}
}
return nil
}
func (h *HTML) Render(ctx context.Context, page string, data authboss.HTMLData) (output []byte, contentType string, err error) {
buf := &bytes.Buffer{}
tpl, ok := h.templates[page]
if !ok {
return nil, "", errors.Errorf("template for page %s not found", page)
}
templates.WritePage(buf, tpl(data))
return buf.Bytes(), "text/html", nil
}
func InitializeLoginPage(data authboss.HTMLData) templates.PageImpl {
return &templates.LoginPage{Data: data}
}
func InitializeRecoverPage(data authboss.HTMLData) templates.PageImpl {
return &templates.RecoverPage{Data: data}
}
</code></pre></li>
<li><p>Solution with interface with a method</p>
<pre class="lang-golang prettyprint-override"><code>type HTML struct {
templates map[string]templates.AuthPageImpl
}
func (h *HTML) Load(names ...string) error {
for _, n := range names {
switch n {
case "login":
h.templates[n] = &templates.LoginPage{}
case "recover":
h.templates[n] = &templates.RecoverPage{}
}
}
return nil
}
func (h *HTML) Render(ctx context.Context, page string, data authboss.HTMLData) (output []byte, contentType string, err error) {
buf := &bytes.Buffer{}
tpl, ok := h.templates[page]
if !ok {
return nil, "", errors.Errorf("template for page %s not found", page)
}
template := tpl.SetData(data)
templates.WritePage(buf, template)
return buf.Bytes(), "text/html", nil
}
type AuthPageImpl interface {
SetData(data authboss.HTMLData) PageImpl
}
type LoginPage struct {
Data authboss.HTMLData
}
type RecoverPage struct {
Data authboss.HTMLData
}
func (p *LoginPage) SetData(data authboss.HTMLData) (page PageImpl) {
p.Data = data
return p
}
func (p *RecoverPage) SetData(data authboss.HTMLData) PageImpl {
p.Data = data
return p
}
<span class="math-container">```</span>
</code></pre></li>
</ol>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T15:26:55.733",
"Id": "225525",
"Score": "1",
"Tags": [
"go",
"authentication"
],
"Title": "Precompiled templates with initializators (factory pattern) or single interface and method or what else?"
}
|
225525
|
<p>I am implementing a BVH (Bounding volume hierarchy) in Cython and thought of using a doubly linked list to hold reference of the volumes that still need to be split and push new volumes at one end while popping others on the other side in a recursive manner.</p>
<p>But I am not sure if I got the code right, it gets confusing to me really fast.</p>
<p>Here <code>AABB</code> stands for <code>Axis Aligned Bounding Box</code>, the kind of bounding volume I want to use in my BVH.</p>
<pre><code> cdef struct AABB:
double min_x, max_x
double min_y, max_y
double min_z, max_z
AABB* next
AABB* children
int id
cdef struct AABBListItem:
AABB* box
AABBListItem* next
AABBListItem* prev
cdef AABBList* aabb_list_create(AABB* start):
cdef AABBList* lst = <AABBList *> malloc(sizeof(AABBList))
cdef AABBListItem* item = <AABBListItem *> malloc(sizeof(AABBListItem))
item.next = NULL
item.prev = NULL
item.box = start
lst.first = item
lst.last = item
lst.length = 1
return lst
cdef void aabb_list_free(AABBList* lst):
cdef AABBListItem* item = lst.first
cdef AABBListItem* next
while not item == NULL:
next = item.next
free(item)
item = next
free(lst)
cdef void aabb_list_push_last(AABBList* lst, AABB* box):
cdef AABBListItem* item = <AABBListItem *> malloc(sizeof(AABBListItem))
item.box = box
item.prev = lst.last
item.next = NULL
lst.last.next = item
lst.last = item
lst.length += 1
cdef void aabb_list_push_first(AABBList* lst, AABB* box):
cdef AABBListItem* item = <AABBListItem *> malloc(sizeof(AABBListItem))
item.box = box
item.next = lst.first
item.prev = NULL
lst.first.prev = item
lst.first = item
lst.length += 1
cdef AABB* aabb_list_pop_first(AABBList* lst):
cdef AABBListItem* item = lst.first
cdef AABB* box = item.box
lst.first = item.next
lst.first.prev = NULL
free(item)
lst.length -= 1
return box
cdef AABB* aabb_list_pop_last(AABBList* lst):
cdef AABBListItem* item = lst.last
cdef AABB* box = item.box
lst.last = item.prev
lst.last.next = NULL
free(item)
lst.length -= 1
return box
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<h3>Empty Constraint</h3>\n\n<p>You do not allow to create an empty list.</p>\n\n<blockquote>\n<pre><code>cdef AABBList* aabb_list_create(AABB* start):\n</code></pre>\n</blockquote>\n\n<p>However, the <code>pop</code> methods don't check against the empty constraint. In fact, when popping the sole node, you end up with an error.</p>\n\n<p>For instance,</p>\n\n<blockquote>\n<pre><code> cdef AABB* aabb_list_pop_first(AABBList* lst):\n cdef AABBListItem* item = lst.first\n cdef AABB* box = item.box\n lst.first = item.next // <- if item.next is NULL\n lst.first.prev = NULL // <- lst.first will be NULL, and .prev is an error\n free(item)\n lst.length -= 1\n return box\n</code></pre>\n</blockquote>\n\n<h3>Single Remaining Item after Pop</h3>\n\n<p>Furthermore, when after <code>pop</code> a single item remains, it should be set as both <code>first</code> and <code>last</code> on the list.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T18:24:28.763",
"Id": "437936",
"Score": "1",
"body": "Thanks, I would never have caught this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T18:35:21.023",
"Id": "437938",
"Score": "0",
"body": "many API's use a cyclic reference to avoid such bugs. For instance, a single node would have next and previous set to itself. Iterators know to stop - not when reaching null - but when reaching the node itself again."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T16:59:31.767",
"Id": "225534",
"ParentId": "225526",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "225534",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T16:21:20.853",
"Id": "225526",
"Score": "4",
"Tags": [
"linked-list",
"cython"
],
"Title": "Doubly linked list in Cython"
}
|
225526
|
<p><strong>Goal</strong></p>
<p>My goal is to create a TCP server/client class that can be universally reused in various private projects. It should work stable and does not need to be super fast, but rather light-weight to even work on a Raspberry Pi, for example. One TCP connection at the time would be enough for me.</p>
<p><strong>Question</strong></p>
<p>Since I am somewhat new to C# and not an expert on TCP-communications, I would like to know, if the "lock-mechanism" is correctly implemented and if there is any better way of handling errors. In addition to that, I would be glad to hear general improvements to the code or my coding style.</p>
<p><strong>Code</strong></p>
<p>In addition to the code below, I have a link to my project on GitHub as well as a link to the testing program that I created for this class/lib. NOTE: The class is targeted to .NET Standard 2.0</p>
<p><a href="https://github.com/dadul96/TcpConnection_Lib" rel="noreferrer">TCP server/client class</a></p>
<p><a href="https://github.com/dadul96/TCP_Server_Client_Tester" rel="noreferrer">Testing application</a></p>
<pre><code>using System;
using System.Net.Sockets;
using System.Threading;
using System.Text;
using System.Net;
using System.Collections;
namespace TcpConnection_Lib
{
public class TcpConnection : IDisposable
{
//fields and properties:
private TcpClient client;
private TcpListener listener;
private Thread ListenThread;
private Thread TcpReaderThread;
public string RemoteEndpointAddress { get; private set; }
private readonly Queue ReceivedStringQueue = new Queue();
public bool TcpIsConnected
{
get
{
if (client != null)
{
return client.Connected;
}
else
{
return false;
}
}
}
private readonly byte[] receiveBuffer = new byte[4096];
private readonly object syncLock = new object();
//methods:
public bool Connect(string IP, int port)
{
try
{
bool successFlag = false;
lock (syncLock)
{
try
{
client = new TcpClient();
client.Connect(IP, port);
client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
if (TcpReaderThread != null)
{
TcpReaderThread.Abort();
TcpReaderThread = null;
}
TcpReaderThread = new Thread(ReadData)
{
IsBackground = true
};
TcpReaderThread.Start();
successFlag = true;
}
catch { }
}
return successFlag;
}
catch
{
return false;
}
}
public bool Disconnect()
{
try
{
lock (syncLock)
{
try
{
if (TcpReaderThread != null)
{
TcpReaderThread.Abort();
TcpReaderThread = null;
}
if (client != null)
{
client.Client.Close();
client.Close();
client = null;
}
if (ReceivedStringQueue.Count > 0)
{
ReceivedStringQueue.Clear();
}
}
catch { }
}
return true;
}
catch
{
return false;
}
}
public bool Send(string sendString)
{
try
{
bool successFlag = false;
lock (syncLock)
{
try
{
client.Client.Send(ASCIIEncoding.ASCII.GetBytes(sendString));
successFlag = true;
}
catch { }
}
return successFlag;
}
catch
{
return false;
}
}
public string GetReceivedString()
{
try
{
string returnString = "";
lock (ReceivedStringQueue.SyncRoot)
{
try
{
if (ReceivedStringQueue.Count > 0)
{
returnString = ReceivedStringQueue.Dequeue().ToString();
}
}
catch { }
}
return returnString;
}
catch
{
return "";
}
}
public bool Listen(int port)
{
try
{
IPEndPoint ipLocalEndPoint = new IPEndPoint(IPAddress.Any, port);
listener = new TcpListener(ipLocalEndPoint);
listener.Start(port);
if (ListenThread != null)
{
ListenThread.Abort();
ListenThread = null;
}
ListenThread = new Thread(ListeningMethod)
{
IsBackground = true
};
ListenThread.Start();
return true;
}
catch
{
return false;
}
}
public void Dispose()
{
try
{
lock (syncLock)
{
try
{
Disconnect();
if (listener != null)
{
listener.Stop();
listener = null;
}
if (client != null)
{
client.Close();
client = null;
}
if (ListenThread != null)
{
ListenThread.Abort();
ListenThread = null;
}
if (TcpReaderThread != null)
{
TcpReaderThread.Abort();
TcpReaderThread = null;
}
if (ReceivedStringQueue.Count > 0)
{
ReceivedStringQueue.Clear();
}
}
catch { }
}
GC.SuppressFinalize(this);
}
catch { }
}
private void ListeningMethod()
{
try
{
while (true)
{
try
{
client = listener.AcceptTcpClient();
RemoteEndpointAddress = client.Client.RemoteEndPoint.ToString();
client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
if (TcpReaderThread != null)
{
TcpReaderThread.Abort();
TcpReaderThread = null;
}
TcpReaderThread = new Thread(ReadData)
{
IsBackground = true
};
TcpReaderThread.Start();
}
catch
{
if (listener != null)
{
listener.Stop();
listener = null;
}
break;
}
}
}
catch { }
}
private void ReadData()
{
try
{
int bytesRead = 0;
while (true)
{
if (!client.Connected)
{
break;
}
bytesRead = client.GetStream().Read(receiveBuffer, 0, receiveBuffer.Length);
if (bytesRead == 0)
{
break;
}
CopyReceived(Encoding.ASCII.GetString(receiveBuffer, 0, bytesRead));
}
}
catch { }
}
private void CopyReceived(string receivedData)
{
try
{
lock (ReceivedStringQueue.SyncRoot)
{
try
{
ReceivedStringQueue.Enqueue(receivedData);
}
catch { }
}
}
catch { }
}
}
}
</code></pre>
<p><strong>EDIT (as VisualMelon suggested):</strong></p>
<p>The API has following interfaces:</p>
<p>methods:</p>
<ul>
<li><strong>bool Connect(string IP, int port)</strong> - returns true, if the client could connect to the server</li>
<li><strong>bool Disconnect()</strong> - returns true, if all connections could be successfully closed</li>
<li><strong>bool Listen(int port)</strong> - returns true, if the listener could be successfully started</li>
<li><strong>bool Send(string sendString)</strong> - returns true, if the string could be successfully sent</li>
<li><strong>string GetReceivedString()</strong> - returns the received string or an empty string, if nothing got received</li>
<li><strong>void Dispose()</strong> - runs Disconnect() and disposes everything</li>
</ul>
<p>properties:</p>
<ul>
<li><strong>RemoteEndpointAddress</strong> - address of the client that connected to the server</li>
<li><strong>TcpIsConnected</strong> - is true, if a TCP client is connected</li>
</ul>
<p>A simple demonstration of a server implementation with my API:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TcpConnection_Lib;
namespace Tcp_Lib_Server_Tester
{
class Program
{
static TcpConnection connection = new TcpConnection();
static void Main(string[] args)
{
connection.Listen(23); //starts a TCP listener on port 23
while (!connection.TcpIsConnected) //wait until a client connects
{
System.Threading.Thread.Sleep(100);
}
Console.Write("remote endpoint address: " + connection.RemoteEndpointAddress + Environment.NewLine); //prints the remote endpoint IP to the console
bool successfulSendFlag = connection.Send("Hello world!"); //the server sends "Hello World!" to the remote peer and returns if the operation was successful
if (successfulSendFlag)
{
Console.Write("String successfully sent." + Environment.NewLine);
}
else
{
Console.Write("String NOT successfully sent." + Environment.NewLine);
}
string tempReceiveString = "";
while (tempReceiveString == "")
{
tempReceiveString = connection.GetReceivedString(); //returns the received string or an empty string, if nothing got received so far
}
Console.Write("Received: " + tempReceiveString + Environment.NewLine); //prints the received string to the console
Console.ReadLine(); //keeps the console alive
}
}
}
</code></pre>
<p><em>(The client implementation would use "Connect(ip, port)" instead of "Listen(port)" and you could not print the "RemoteEndpointAddress".)</em></p>
<p>While writing this sample code I discovered a hidden bug. If you check the <code>RemoteEndpointAddress</code> exactly after the moment where a client connects to the server, then the <code>RemoteEndpointAddress</code> would be null (therefore I implemented the <code>Sleep()</code> in the first while-loop of the API-example-code). My first proposed solution would be to lock-in the "get" of the <code>TcpIsConnected</code>-property as well as the inner part of the while-loop in the <code>ListeningMethod()</code>, but this would block the <code>TcpIsConnected</code>-property forever since <code>AcceptClient()</code> is a blocking method. This means that I have to find a better way to fix this bug...</p>
<p>About the "lock-in" mechanism: I don't have any special use case other than preventing bugs (like the one mentioned above).</p>
<p><strong>EDIT (as dfhwze suggested):</strong></p>
<p>Main goals:</p>
<ul>
<li>learn C# and OOP</li>
<li>learn about TCP</li>
<li>improve my coding style and architecture</li>
<li>create a universal library for any future projects that may come up, but nothing specific (theoretical uses: sending and receiving commands between single-board computers)</li>
<li>create a complete bugfree, well tested and good to read code</li>
</ul>
<p>Single client instance:</p>
<p>Thank you for pointing that out, because I totally overlooked this limitation!</p>
<p>Server or Client:</p>
<p>This class should either be used as a client or as a server, but not both at the same time.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T17:10:36.443",
"Id": "437929",
"Score": "3",
"body": "Welcome to code review! Your question would be improved by the inclusion of a simple piece of example code demonstrating the usage of the API. This makes it much easier to quickly understand the code, and gives us confidence that the code is working correctly. It's nice see that you have a test program on github, but it's pretty complex, and generally it's best to not depend on 3rd party sites. It would also help if you could explain the 'lock-in' mechanisms (what it achieves, how it works, why you did it that way), so that we can provide a useful review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T17:58:13.727",
"Id": "437933",
"Score": "3",
"body": "In addition to VisualMelon's comment, could you provide a description of the scope and use cases for this reusable API? I noticed you have a single _client_ instance. This limits possibilities for multiple connected connections. Is this as designed?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T18:38:41.213",
"Id": "437940",
"Score": "2",
"body": "Thank you both for your suggestions! I edited my question and marked the edits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T14:52:32.143",
"Id": "438045",
"Score": "0",
"body": "Welcome to code review. I haven't read the full question but I would like to highlight some smell. In the first sentence you mentioned about writing a *universal* TCP/IP listener. This smells like reinventing the wheel (I am not using offensive language, there is a known dedicated anti-pattern). Before implementing your own TCP/IP processing code, have you done research as whether you could use a known library/protocol under a narrower app protocol scope? If your main (and mostly only) goal is tuition, reimplementing a server is a great way and you should ignore my comment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T16:06:46.230",
"Id": "438069",
"Score": "0",
"body": "@usr-local-ΕΨΗΕΛΩΝ You are right. I somewhat reinvented the wheel, but the main goal is to improve my skills and maybe create a project that is worth putting in my programming portfolio. In addition to that, it would motivate me to build other projects that are based on this class. This allows me to learn what's important for creating an API."
}
] |
[
{
"body": "<h3>Review</h3>\n\n<p><em>This review handles readability metrics and C# conventions only and should provide insights to reach some of your goals.</em></p>\n\n<blockquote>\n <p>Goals: learn C#, improve coding style, create good to read code</p>\n</blockquote>\n\n<ul>\n<li>There are a couple of variants how to name instance variables. The most common one is to use an underscore as prefix and camel-case the name; <code>_client</code>, <code>_listener</code>, <code>_listenThread</code>, <code>_tcpReaderThread</code>, <code>_receivedStringQueue</code>, and so on.</li>\n<li>Use a generic queue when dealing with a specific type; <code>Queue ReceivedStringQueue</code> -> <code>Queue<string> ReceivedDataQueue</code>. The specifc type's name should not be part of the variable name.</li>\n<li>Use null-propagation where convenient. <code>if (TcpReaderThread != null) TcpReaderThread.Abort();</code> -> <code>TcpReaderThread?.Abort();</code></li>\n<li>Avoid empty catch blocks; <code>catch { }</code> Think about which errors to catch, how to handle them, logging, rethrowing, invalidating state, etc.</li>\n<li>Avoid redundant checks; <code>if (ReceivedStringQueue.Count > 0) ReceivedStringQueue.Clear();</code> -> <code>ReceivedStringQueue.Clear();</code> Clear does not care what the count is.</li>\n<li>It's a convention to prefix method names with <code>Try</code> when you return a boolean whether or not the method call was a sucess; <code>bool Send(string sendString)</code> -> <code>bool TrySend(string sendString)</code>.</li>\n<li>The type of member should not be part of a member name; <code>ListeningMethod</code></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T05:50:11.957",
"Id": "437983",
"Score": "1",
"body": "First of all, thank you for your review. I am going to consider these tips in my next revision of the implementation. But I have one question concerning your second point. At first, I had a type-specific Queue, but I was not able to access the `.SyncRoot` of the Queue. Is there any specific trick to still be able to use the provided `.SyncRoot` or do I have to create my own lock-in object as I did with `syncLock`? And does the newly created lock-in object make the Queue truly threadsafe?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T07:02:15.610",
"Id": "437988",
"Score": "1",
"body": "I did not focus on thread-safety when reviewing your code. But since you ask, your current implementation does not look thread-safe to me. You sometimes lock _syncRoot_ and sometimes _ReceivedStringQueue.SyncRoot_ to manipulate the queue. Perhaps it's simper to just use one lock for your class _syncRoot_."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T18:32:32.813",
"Id": "225539",
"ParentId": "225530",
"Score": "10"
}
},
{
"body": "<h2>Networking</h2>\n\n<p>You have done the classic thing that all people new to TCP do of assuming that whatever <code>NetworkStream.Read</code> gives you will be some meaningful chunk of data: this is not guaranteed, and only 'works' because you are sending tiny packages locally. Basically, if you want this to be a general-purpose and reusable system for sending discrete messages (i.e. <code>string</code>s), then you need to design a protocol to communicate this information. Instead of writing pages about it here, I'll just point you to <a href=\"https://codereview.stackexchange.com/questions/177358/send-messages-in-tcp-based-communication-system/177384#177384\">an older answer of mine</a> which discusses this in more detail. You also have a fixed-size buffer, so it's impossible at the moment to send a message longer than 4096 bytes without ending up with 2 messages: how you handle really long packets is whole other concern I won't go into.</p>\n\n<p>You've done another classic thing, which is to provide a dedicated thread for reading. There a few reasons why this isn't ideal: it doesn't scale well (having hundres of blocked threads consumes memory and messes with scheduling), it means you end up managing threads (which is not fun), and it increases complexity (what do I do when the thread fails? who is responsible for killing the thread?). If you need asyncronous communication (as you have tried to implement), then you should use the asynchronous APIs on the <code>NetworkStream</code> (e.g. <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.net.sockets.networkstream.beginread?view=netstandard-2.1\" rel=\"noreferrer\"><code>BeginRead</code></a>/<a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.net.sockets.networkstream.endread?view=netstandard-2.1\" rel=\"noreferrer\"><code>EndRead</code></a> or <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.net.sockets.networkstream.readasync?view=netstandard-2.1\" rel=\"noreferrer\"><code>ReadAsync</code></a>). Running a dedicated 'read and remember' loop can be necessary/useful in some cases, but it should still use the asynchronous APIs.</p>\n\n<p>Going asynchronous will also enable you to provide snappier reads to your queue. Currently a call to <code>GetReceivedString</code> can be blocked by pretty much anything, which means it has little use as a polling API.</p>\n\n<h2>Threading</h2>\n\n<p>Don't do this:</p>\n\n<pre><code>ListenThread.Abort();\n</code></pre>\n\n<p>Some people call exceptions hand-grenades, but they are wrong: exceptions are lovely and only make life better. <code>Thread.Abort</code>, however, is a demolition charge, and you give up a lot of confidence that anything will work if you ever do this. You have no idea what the thread was doing, and you have no idea if you are about to leave something in an invalid state. If you had some fancy lock-less concurrency going on (which currently you don't, but that may change...) you could easily lock up your entire program (which is honestly preferable to just killing a thread that was probably half way through something important).</p>\n\n<p>The simplest way to resolve this problem is to abandon the behaviour of allowing multiple calls to <code>Listen</code>: you can't guarantee what this will do, so you shouldn't even try to support it. If someone calls <code>Listen</code> twice, throw and exception telling them to not do so in future, and document the behaviour precisely. One of dfhwze's comments mentioned that it is odd to provide a class which does the job of both a client and a server, and this is related: you would be much better off separating the job of being a server out into a separate class (just like <code>TcpListener</code> is separate from <code>TcpClient</code>). At the same time, you can solve your problem with the endpoint not being set by setting it in a constructor (whereafter you can make it readonly).</p>\n\n<p>Even if you did have to terminate a reader, don't do it like this. Instead, kill the connection and detect this (somehow) within the read-loop if you need to close gracefully in that instance.</p>\n\n<h2>API and Error Handling</h2>\n\n<p>Your code can't send or receive empty strings. Implementing a proper protocol will solve this. For a polling <code>GetReceiveString</code> method, returning <code>null</code> when there is nothing available makes much more sense than returning <code>\"\"</code>: that way you <em>can</em> send an empty string (if the protocol supports it), but it also has the benefit that it will crash violently if you try to use it. You also shouldn't be returning <code>\"\"</code> in <code>GetReceivedString</code> if there is a failure. Another options is to have a <code>bool TryRead(out string message)</code> method that returns a <code>true</code> if there was something read and sets the message accordingly, and returns false and sets <code>message to</code>null` if there was not.</p>\n\n<p>If there is a failure, do <em>not</em> swallow the exception and carry on merrily: this will only make debugging harder in the future when something does actually go wrong. For instance, I would probably remove both <code>try...catch</code> statements in <code>GetReceivedString</code>: that code should never go wrong: if it does, then you have a problem with your implementation, and you <em>need</em> to address it. If I was building a larger API, I might define a new <code>Exception</code> type which I can return when something goes unexpectedly wrong pass the exception from the outer <code>try...catch</code> as an inner exception.</p>\n\n<p>In almost every method you swallow all the exceptions: sometimes this is 'ok', but that's only because I can see how it might map onto a carefully designed API, and I suspect that rather you are trying to make the code 'robust': this is a bad idea. If you are getting exceptions which you should be handling, then handling them <em>specifically</em>, and document the behaviour precisely. It's so much better for your program to crash and burn because something unexpected happened, than for it to pretend that everything is fine when it's ended up in an invalid state. Again, in much of your code you can just about get away with this, but it is not a good habit.</p>\n\n<p>I can see that you want to call <code>Listen</code> and then just start trying to read, but this gives you nothing that calling <code>Listen</code> and waiting for a client to connect (which you can package in another object) before trying to read would give you.</p>\n\n<p>Even if you did want some way to swap out the client without changing the reading object (which would be enough logic to warrant it's own class), then consider that fact that whoever is reading has <em>no idea</em> that the connection may have changed, and that it may have changed between their reading a message and writing one. This sort of thing needs a very clear set of requirements, and is not the job of a general purpose networking API.</p>\n\n<p>You should throw an <code>ArgumentNullException</code> if <code>Send</code> is called with a <code>null</code> parameter: it will throw one anyway, but this will be swallowed and look like a general failure.</p>\n\n<p><code>TcpIsConnected</code> is kind-of useless, because it doesn't tell you anything about whether you will be able to read again. It could be <code>false</code> because you are currently swapping reader, or simply not connected yet. Again, you've jammed three complex tasks (syncing reads from multiple places; listening for clients; reading from clients), and ended up with a confusing and unpredictable API. Much of the misery goes away if you separate the <code>Listen</code> and <code>Read</code> objects, because then you can make <code>TcpIsConnect</code> a one-way latch: it starts true, and if it ever goes false then you've lost it forever.</p>\n\n<p><code>TcpIsConnected</code> should probably also be taking the <code>SyncLock</code> or use <code>client?.Connected</code> (which explicitly caches the value of <code>client</code>); otherwise you are depending on dodgy runtime optimisations/luck to avoid a possible <code>NullReferenceException</code>.</p>\n\n<h2>Misc</h2>\n\n<ul>\n<li><p>Your class is hardcoded to use ASCII: consider making the encoding configurable, or at the very least use UTF-8, which will allow you to send any string without corruption.</p></li>\n<li><p>You can return from within a <code>lock</code>: you don't need all those <code>returnString</code> and <code>successFlag</code> variables, and I would consider getting rid of them: they make it harder for the compiler to help you, as the variables over-extend their meaningful scope.</p></li>\n<li><p>You should consider adding inline documentation (<code>///</code>) to all you public members: this commits you to writing a method that has a specific job, means that the maintainer knows what the code is meant to do, and allows someone consuming your API to interrogate it without leaving their API. Inline documentation is great.</p></li>\n<li><p>It's good that you are using <code>Environment.NewLine</code>, but it would be neater if you just used <code>Console.WriteLine</code>.</p></li>\n<li><p>Consider <code>Console.ReadKey(true)</code> for 'pausing': it's just a cleaner way which people come to expect. It feels wrong for the program to take your input, only to throw it away when you press return.</p></li>\n<li><p>You don't have (nor need) a finalizer, so it's not clear what <code>GC.SuppressFinalize</code> is doing for you.</p></li>\n<li><p>I have no idea why <code>ListeningMethod</code> has a <code>while</code> loop. It looks like it once either 'retried' or was meant to accept multiple clients, but now does not.</p></li>\n<li><p>It's conventional to use camel-case for all parameters, including initialisms like <code>ip</code> (which should probably have a clearer name).</p></li>\n<li><p>Avoid 'magic numbers' like <code>4096</code>: perhaps the user would like this to be configurable, and how is the maintainer supposed to know how this number was chosen? Put it in a constant somewhere with a helpful name, and explain why this hard-coded value was chosen: even if it just 'seemed like a good compromise' then write that, so that you know you didn't have some important reason for choosing it you need to bear in mind.</p></li>\n<li><p>You might consider detecting when the object is disposed and throwing an <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.objectdisposedexception?view=netstandard-2.0\" rel=\"noreferrer\"><code>ObjectDisposedException</code></a> if e.g. someone tries to send something.</p></li>\n</ul>\n\n<h2>Summary</h2>\n\n<p>I think the best think you could do is abandon any notion of having one instance of a class do the 4+ different jobs it is current doing (the 'Single Responsibility Principle' certainly applies here). Instead, provide a class to perform (basic) duplex communications (e.g. send and receive strings) over a <code>TcpClient</code>, and provide independent mechanisms (could just be a single static method each) for the following:</p>\n\n<ul>\n<li>Listen for and accept a <code>TcpClient</code> on some port, and wrap it in your class</li>\n<li>Create and connect a <code>TcpClient</code> to some endpoint, and wrap it in your class</li>\n</ul>\n\n<p>Do not even try to make your class reusable: that is just asking for misery. Instead, if you want a way to swap out clients (which is a questionable objective that needs a specification so that you know what your methods are meant to do, which is a domain problem with which we cannot help you), write another a simple class that provides this behaviour. A <code>ConcurrentQueue<string></code> would probably suffice as a backing data-structure.</p>\n\n<p>The protocol is a detail of the API of the <code>TcpClient</code> wrapper, and can be worked out independently of the overall design.</p>\n\n<p>Once you have a sensible and working API, you can then worry about making it robust (i.e. handles invalid usage and network connections properly (not just swallowing all exceptions)). You can worry about making it fast when you discover that it is too slow.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T06:34:06.403",
"Id": "437986",
"Score": "0",
"body": "Thank you for the in-depth explanation of my networking and architecture mistakes. Maybe I wasn't pointing out clear enough that an instance of my class should only be used as a server OR a client and never be reused as something different and certainly not both at the same time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T10:09:50.373",
"Id": "438000",
"Score": "0",
"body": "*Some people call exceptions hand-grenades, but they are wrong: exceptions are lovely and only make life better.* That's quite subjective."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T10:25:21.647",
"Id": "438002",
"Score": "0",
"body": "@SombreroChicken you are right, and it's also very language and usage dependent; I should probably reword that."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T20:57:24.987",
"Id": "225546",
"ParentId": "225530",
"Score": "26"
}
},
{
"body": "<blockquote>\n <p>while (true)</p>\n</blockquote>\n\n<p>Other answers cover most things although as a small point I'd consider using a Wait Handle instead of a while loop</p>\n\n<p><a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.threading.manualresetevent?view=netframework-4.8\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/dotnet/api/system.threading.manualresetevent?view=netframework-4.8</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T14:14:01.403",
"Id": "438042",
"Score": "1",
"body": "Could you elaborate in which part of the code you would introduce the wait handle, and why it would be an improvement of the current code? This way, we can all be enlightened :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T13:23:20.643",
"Id": "225583",
"ParentId": "225530",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "225546",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T16:47:08.807",
"Id": "225530",
"Score": "13",
"Tags": [
"c#",
"performance",
"beginner",
"error-handling",
"tcp"
],
"Title": "C# TCP server/client class"
}
|
225530
|
<p>I'm wondering if there's a more Pythonic way to keep paginating an API endpoint until there's no <code>next</code> key in the response. The thing that bothers me the most is the <code>for item in json_resp.get("data")</code> (I know this can be extracted as a function).</p>
<pre><code># some code is omitted, some obfuscated
# attachment of token in API calls omitted for code brevity
def get_object_list_for_user(user_service_token):
endpoint = f"{HOSTNAME}/me/library/objects/"
params = {"limit": 100}
response = _call_service_api(endpoint, params=params)
json_resp = response.json()
lists_of_objects_to_append = []
# get first batch
for item in json_resp.get("data"):
object_dict = {"library_id": item["id"], "name": item["attributes"]["name"]}
lists_of_objects_to_append.append(object_dict)
offset = 0
while json_resp.get("next"):
offset += 100
params.update({"offset": offset})
response = _call_service_api(endpoint, params=params)
json_resp = response.json()
for item in json_resp.get("data"):
object_dict = {"library_id": item["id"], "name": item["attributes"]["name"]}
lists_of_objects_to_append.append(object_dict)
return lists_of_objects_to_append
</code></pre>
|
[] |
[
{
"body": "<p>I attempted to reduce redundancy by simulating a do-while loop so that the first condition initializes the sequence and then the code can be factored out.</p>\n\n<p>Instead of having a temporary list, it returns a generator which can be appended to the list.</p>\n\n<p>I couldn't test this so I don't know if it works:</p>\n\n<pre><code>def get_object_list_for_user(user_service_token): \n endpoint = f\"{HOSTNAME}/me/library/objects/\"\n params = {\"limit\": 100}\n offset = 0\n\n lists_of_objects_to_append = []\n\n while True:\n json_resp = _call_service_api(endpoint, params=params).json()\n lists_of_objects_to_append.extend(extract_items(json_resp))\n\n offset += 100\n params.update({\"offset\": offset})\n\n if not json_resp.get(\"next\"):\n return lists_of_objects_to_append\n\ndef extract_items(json_resp):\n for item in json_resp.get(\"data\"):\n yield({\"library_id\": item[\"id\"], \"name\": item[\"attributes\"][\"name\"]})\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-01T23:37:21.683",
"Id": "233243",
"ParentId": "225532",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T16:58:00.223",
"Id": "225532",
"Score": "4",
"Tags": [
"python",
"json",
"api",
"pagination"
],
"Title": "Paginating API with \"next\" Pythonically"
}
|
225532
|
<p>I wrote a basic tic toe game. See, <a href="https://jsfiddle.net/shai1436/Lgy1u84s/4/" rel="nofollow noreferrer">https://jsfiddle.net/shai1436/Lgy1u84s/4/</a></p>
<p>I am not satisfied with the way I have designed classes and how I have implemented the undo feature. Please suggest feedback.</p>
<pre><code> //player0 is O and player1 is X
let board;
class Game {
constructor() {
this.player = 0;
this.setTurnText(this.player + 1);
this.setResultText();
}
togglePlayer() {
if (this.player === 1)
this.player = 0;
else
this.player = 1;
this.setTurnText(this.player + 1);
}
setTurnText(player) {
const ele = document.getElementById('turn-text');
ele.innerText = 'Player ' + player + ' turn';
}
setResultText() {
const ele = document.getElementById('result-text');
ele.innerText = ' ';
}
declareWinner(player) {
const ele = document.getElementById('result-text');
ele.innerText = 'Player ' + player + ' won';
console.log("player " + player + " won ");
}
declareDraw() {
const ele = document.getElementById('result-text');
ele.innerText = ' Draw ';
}
}
class Board {
constructor() {
this.gameBoard = new Array(new Array(3), new Array(3), new Array(3));
this.gameStatus = null; // 0: player0 wins, 1: player1 wins, 2: draw, null: undecided
this.cellsFilled = 0;
this.findGameStatus = this.findGameStatus.bind(this);
this.game = new Game();
this.boardCanvas = new BoardCanvas('canvas');
this.gameHistory = new Array();
}
updateBoard(indices) {
if (!this.canDraw(indices))
return;
this.gameBoard[indices.x][indices.y] = this.game.player;
this.gameHistory.push(indices);
this.cellsFilled++;
this.updateBoardCanvas();
this.findGameStatus(indices);
if (this.gameStatus === 0 || this.gameStatus === 1)
this.game.declareWinner(this.gameStatus + 1);
else if (this.gameStatus === 2)
this.game.declareDraw();
this.game.togglePlayer();
}
updateBoardCanvas() {
this.boardCanvas.drawBoard(this.gameBoard);
}
undo() {
const indices = this.gameHistory.pop();
this.gameBoard[indices.x][indices.y] = undefined;
this.updateBoardCanvas();
this.game.togglePlayer();
this.cellsFilled--;
}
canDraw(indices) {
const iscellEmpty = this.gameBoard[indices.x][indices.y] === undefined;
const isGameInProgress = this.gameStatus === null;
return iscellEmpty && isGameInProgress;
}
findGameStatus(indices) {
if (this._checkRow(indices) ||
this._checkColumn(indices) ||
this._checkDiagonal() ||
this._checkReverseDiagonal()) {
this.gameStatus = this.game.player;
}
else if (this.cellsFilled === 9) {
this.gameStatus = 2;
}
}
_checkRow(indices) {
const row = indices.x;
for (let i = 0; i < 3; i++) {
if (this.gameBoard[row][i] !== this.game.player)
return false;
}
return true;
}
_checkColumn(indices) {
const col = indices.y;
for (let i = 0; i < 3; i++) {
if (this.gameBoard[i][col] !== this.game.player)
return false;
}
return true;
}
_checkDiagonal() {
for (let i = 0; i < 3; i++) {
if (this.gameBoard[i][i] !== this.game.player)
return false;
}
return true;
}
_checkReverseDiagonal() {
for (let i = 0; i < 3; i++) {
if (this.gameBoard[i][2 - i] !== this.game.player)
return false;
}
return true;
}
}
class BoardCanvas {
constructor(id) {
this.canvas = document.getElementById(id);
this.ctx = this.canvas.getContext('2d');
this.drawBoard();
this.addClickListener();
}
mapIndicesToCanvasCells(x, y) {
var bbox = this.canvas.getBoundingClientRect();
const loc = {
x: x - bbox.left * (canvas.width / bbox.width),
y: y - bbox.top * (canvas.height / bbox.height)
};
loc.x = Math.floor(loc.x / 100) * 100;
loc.y = Math.floor(loc.y / 100) * 100;
return loc;
}
drawCross(y, x) {
this.ctx.save();
this.ctx.translate(x, y);
this.ctx.beginPath();
this.ctx.moveTo(20, 20);
this.ctx.lineTo(80, 80);
this.ctx.moveTo(80, 20);
this.ctx.lineTo(20, 80);
this.ctx.stroke();
this.ctx.restore();
}
drawCircle(y, x) {
this.ctx.save();
this.ctx.translate(x, y);
this.ctx.beginPath();
this.ctx.arc(50, 50, 30, 0, Math.PI * 2, true);
this.ctx.stroke();
this.ctx.restore();
}
drawBoard(board) {
this.clearBoard();
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
this.ctx.strokeRect(100 * i, 100 * j, 100, 100);
if (board && board[i][j] === 0)
this.drawCircle(100 * i, 100 * j);
else if (board && board[i][j] === 1)
this.drawCross(100 * i, 100 * j);
}
}
}
addClickListener() {
this.canvas.onclick = (e) => {
const loc = this.mapIndicesToCanvasCells(e.clientX, e.clientY);
const indices = {};
let temp = loc.x;
indices.x = Math.floor(loc.y / 100);
indices.y = Math.floor(temp / 100);
board.updateBoard(indices);
}
}
clearBoard() {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
const init = () => {
board = new Board();
}
init();
const undo = () => {
board.undo();
}
window.init = init;
window.undo = undo;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T16:37:29.177",
"Id": "438079",
"Score": "0",
"body": "Great answer from @radarbob, just wanted to give an example on usage of `Array` methods:\n\n`for (let i = 0; i < 3; i++) {\n if (this.gameBoard[row][i] !== this.game.player)\n return false;\n}\nreturn true`\n\nCan be rewritten like:\n\n`return this.gameBoard[row].every(foo => foo === this.game.player)`"
}
] |
[
{
"body": "<p><strong>Player is confusing</strong></p>\n\n<p>Only 1 player is defined. This spawns the need for confusing code that looks like <code>this.player</code> is 0 then 1 then 2 then 3 and so on. And player-value incrementing is spread over many methods which my spidey sense says \"uh-oh, player disconnects ahead!\".</p>\n\n<pre><code>changePlayer() { this.player = this.player === 0 ? 1 : 0; }\ncurrentPlayuer() { return this.player; }\n</code></pre>\n\n<p>Personally, when I write a second method for a given thing I start to consider making a separate class. Classes should be about exposing related functionality. Good classes expose functionality and hide state.</p>\n\n<hr>\n\n<p><strong>Array Iterator Functions</strong></p>\n\n<p>Read up on <code>Array.map</code>, <code>Array.every</code>, <code>Array.some</code>, et cetera. These will really clean up the array looping. </p>\n\n<hr>\n\n<p><strong>Class decoupling</strong></p>\n\n<p>Class purpose needs to be more precisely nailed down conceptually. Then the existing coupling will be more evident. Mixing UI functionality into many classes seems universal in my coding experiences. It just too easy to do when updating the screen is a simple one liner.</p>\n\n<p><code>Game</code> sounds like it should be the overall game manager. It should be coordinating the other objects through their own APIs, but is directly manipulating raw state that should be in other objects such as display. </p>\n\n<p><code>Board</code> is only the board and should only be aware of its own state - which squares are occupied. But it is also handling display details. <code>gameHistory</code> sounds like high level functionality that belongs in a conceptually higher level class.</p>\n\n<p><code>BoardCanvas</code> sounds like <em>the</em> place for display functions, but it is not. The DOM and <code>Canvas</code> are conceptually display components for tic-tac-toe and only <code>BoardCanvas</code> should have to use them. <code>BoardCanvas</code> needs an a tic-tac-toe game appropriate API. <code>addClickListener()</code> is a spot-on example of good decoupling.</p>\n\n<hr>\n\n<p><strong><code>Board</code> contains a <code>Game</code> or vice versa?</strong></p>\n\n<p>As a general rule have higher level classes contain lower level classes. <code>Board</code> is a low level and thus \"stupid\" class. Keep it stupid. It should not be coordinating <code>Game</code> - <code>BoardCanvas</code> interaction; which will happen if you invert the containment heirarchy.</p>\n\n<hr>\n\n<p><strong><code>undo</code></strong></p>\n\n<pre><code> const undo = () => { board.undo(); }\n</code></pre>\n\n<p>You'll end up naturally writing lots of these \"pass through\" functions with decoupled classes. This invisible hand of OO, so to speak, will make high level classes read appropriately high level and classes at all levels will be able to \"mind their own business\".</p>\n\n<hr>\n\n<p><strong>game flow logic</strong></p>\n\n<p>In the spirit of expressing high level logic, at the highest level, I imagine the game as a loop. Whether this logic is in <code>Game</code> or a new class is a design decision but the overall point is \"layers of abstraction\" in the application.</p>\n\n<pre><code>// initialze variables, create objects, etc.\nvar noWinner = true;\n...\n\nwhile (noWinner) {\n ...\n\n // testing for a winner or tie game should be somewhere in the\n // method we're calling (or method chain it might be calling).\n // An if-else in this game loop takes away part of the \"who won?\" logic \n // from its proper place. \n noWinner = this.hasWon(currentPlayer());\n}\n\nboardCanvas.displayWinner(this.winner);\n// I suppose the winner could be \"its a tie\" \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T20:03:47.570",
"Id": "225544",
"ParentId": "225536",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "225544",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T17:27:22.727",
"Id": "225536",
"Score": "3",
"Tags": [
"javascript",
"tic-tac-toe"
],
"Title": "Class diagram of Tic-Tac-Toe Game"
}
|
225536
|
<p>I am writing a lesson-based program to help teach friends and family the basics of Arabic. The program consists of different sections (letters, numbers, personnel pronouns, etc.) and each of those sections is in turn broken into different lessons. Each section has its own .py file. All of those files are then imported into the "Master" .py file which then displays the options available to the user. </p>
<p>Though I've been programming for ~2 years now, it's all been self-taught/internet help based. I've just recently started experimenting with classes (I know...). </p>
<p>What I'm mainly looking for is help refactoring my code and using it as an opportunity to improve my coding style. What I have right now works - it does what I want it to do. But, I'm sure it could be improved dramatically and my hope is that by learning how to improve this code I can become a better coder in general. </p>
<p>The code below is 350 lines long, which I know is a lot. But I would be very appreciative if folks would take some time and point out anything they think is done incorrectly or could be improved. I've done my best to keep it to PEP 8 but I'm sure I've missed a few things. </p>
<pre><code>import sys
import os
import tkinter
from tkinter import *
from tkinter import messagebox
from tkinter import ttk
from operator import itemgetter
import Letters_Listening_Test
import Numbers_1_Intro_1, Numbers_1_Intro_2
import Numbers_License_Plate_Decoder
import Lesson_1_Part_1
import Personal_Pronouns_Intro_1, Personal_Pronouns_Intro_2
import Greetings_Intro_1, Greetings_Intro_2, Greetings_Intro_3
import Greetings_Conversation_1, Greetings_Conversation_2
class Initialize_Screen:
def __init__(self, cfn, img):
self.CurrentFrameNumber = cfn
self.image = img
for i in range(0, NoF): #This is for question frames
frames[i].grid_remove()
cfn.grid(column = 0, row = 0, sticky = (tkinter.W, tkinter.E))
for i in range(0, 4):
cfn.grid_columnconfigure(i, weight=1)
cfn.grid_rowconfigure(2, weight = 1)
cfn.grid_rowconfigure(5, weight = 1)
tempimage = MenuBackgroundImages + str(img) +(".png")
backgroundImage = PhotoImage(file = (tempimage))
backgroundImage_Label = Label(cfn, image = backgroundImage)
backgroundImage_Label.place(x = 0, y = 0, relwidth = 1, relheight = 1)
backgroundImage_Label.tempimage = backgroundImage
def home_button(self):
home_button = Button(
self.CurrentFrameNumber, text = "Home",
font = ("Helvetica", 25), command = initialize_main_menue)
home_button.grid(column=0, row = 0, sticky = (tkinter.W, tkinter.E))
def profile(self):
print("Still in progress")
def profile_button(self):
profile_button = Button(
self.CurrentFrameNumber, text = " Profile ",
font = ("Helvetica", 35), command = lambda: opening_screen.profile())
profile_button.grid(column = 1, columnspan = 2, row = 3)
def main_program_button(self):
main_program_button = Button(
self.CurrentFrameNumber, text = "LibLib Arriby",
font = ("Helvetica", 35), command = initialize_lesson_menue)
main_program_button.grid(column = 1, columnspan = 2, row = 4)
def back_to_main_program(self):
back_to_main_program_button = Button(
self.CurrentFrameNumber, text = "Back",
font = ("Helvetica", 25), command = initialize_lesson_menue)
back_to_main_program_button.grid(column = 0, row = 0)
class Side_Frame:
def __init__(self, current_frame):
self.CurrentFrameNumber = current_frame
sideframe=tkinter.Frame(self.CurrentFrameNumber,
width = 100, height = 100, bg = "gray")
current_frame['borderwidth'] = 2
current_frame['relief'] = 'sunken'
current_frame.grid_propagate(True) #Turns off autoshrink of Frame widget
current_frame.grid_rowconfigure(0, weight = 1)
current_frame.grid_columnconfigure(1, weight = 1)
current_frame.grid(column= 1, row = 1)
def initialize_main_menue():
global opening_screen
opening_screen = Initialize_Screen(frames[0], 1)
opening_screen.profile_button()
opening_screen.main_program_button()
def initialize_lesson_menue():
lesson_menue = Initialize_Screen (frames[1], 2)
lesson_menue.home_button()
lessons()
def lessons():
lessonframe=tkinter.Frame(frames[1], bg = "gray",
borderwidth = 2, relief = "sunken")
lessonframe.grid(column = 1, row = 1)
lessonframe.grid_rowconfigure(0, weight = 1)
lessonframe.grid_rowconfigure(1, weight = 1)
current_frame = lessonframe
##############################################################################
## The items below list out the titles of all of the different lesson plans ##
letters_button = Button(
current_frame, text = "Letters",
font=("Helvetica", 25), command = letters)
numbers_button = Button(
current_frame, text = "Numbers",
font=("Helvetica", 25), command = Numbers)
lesson_1_button = Button(
current_frame, text = "Lesson 1",
font=("Helvetica", 25), command = lesson_1)
letters_button.grid(column = 0, columnspan = 1, row=1,
sticky = (tkinter.W, tkinter.E))
numbers_button.grid(column = 0, columnspan = 1, row=2,
sticky = (tkinter.W, tkinter.E))
lesson_1_button.grid(column = 0, columnspan = 1, row = 3,
sticky = (tkinter.W, tkinter.E))
def letters():
letter_screen = Initialize_Screen(frames[2], 3)
letter_screen.back_to_main_program()
current_frame=tkinter.Frame(frames[2], width = 100, height = 100, bg = "gray")
side_screen = Side_Frame(current_frame)
def all_buttons_forget():
letters_2_button.config(relief = RAISED, bg = "gray95")
letters_3_button.config(relief = RAISED, bg = "gray95")
letters_4_button.config(relief = RAISED, bg = "gray95")
letters_1_button.config(relief = RAISED, bg = "gray95")
class Letters:
def __init__(self, LN):
self.Lesson_Number = LN
intro_1_button = Button(
current_frame, text = "Letters "+str(LN)+": Introduction Part 1",
font = ("Helvetica", 25), command = lambda: intro_1(LN))
intro_1_button.grid(column = 1, columnspan = 2, row = 1)
intro_1_button.config(bg = "gold")
intro_2_button = Button(
current_frame, text = "Letters "+str(LN)+": Introduction Part 2",
font = ("Helvetica", 25), command = lambda: intro_2(LN))
intro_2_button.grid(column = 1, columnspan = 2, row = 2)
intro_2_button.config(bg = "gold")
quiz_button = Button(
current_frame, text = "Letters "+str(LN)+": Quiz",
font = ("Helvetica", 25), command = lambda: quiz(LN))
quiz_button.grid(column = 1, columnspan = 2, row = 3)
quiz_button.config(bg = "gold")
def intro_1(LN):
module = __import__("Letters_" + str(LN)+ "_Intro_1")
func = getattr(module, "letters_" + str(LN) + "_intro_1")
func()
def intro_2(LN):
module = __import__("Letters_" + str(LN)+ "_Intro_2")
func = getattr(module, "letters_" + str(LN) + "_intro_2")
func()
def quiz(LN):
module = __import__("Letters_" + str(LN)+ "_Quiz")
func = getattr(module, "letters_" + str(LN) + "_quiz")
func()
def letters_1():
all_buttons_forget()
letters = Letters(1)
letters_1_button.config(relief = SUNKEN, bg = "gold")
def letters_2():
all_buttons_forget()
letters = Letters(2)
letters_2_button.config(relief = SUNKEN, bg = "gold")
def letters_3():
all_buttons_forget()
letters = Letters(3)
letters_3_button.config(relief = SUNKEN, bg = "gold")
def letters_4():
all_buttons_forget()
letters = Letters(4)
letters_4_button.config(relief = SUNKEN, bg = "gold")
def about_letters():
result = messagebox.showinfo("About this Section",
"The arabic alphabet consists of 28 letters which have been divided into four sections for ease of learning. Each section introduces two sets of letters and then provides a quiz on those letters. The section on letters is then concluded with a listening comphrension and spelling test.")
def additional_resources():
imageroot = Root_File_Name + "Lessons\\Letters\\AdditionalResources\\"
image = imageroot + "Arabic_Alaphabet.png"
photo = PhotoImage(file = image)
canvas = Canvas(tkinter.Toplevel(), height = 566, width = 850)
canvas.grid(column=0, row=0)
alphabet_photo = canvas.create_image(0, 0, image = photo, anchor = NW)
alphabet_photo.image = photo
about_button = Button(
current_frame, text = "About",
font=("Helvetica", 25), command = about_letters)
about_button.grid(column = 1, columnspan = 1, row = 0,
sticky = (tkinter.W, tkinter.E))
letters_1_button = Button(
current_frame, text = "Letters 1",
font=("Helvetica", 25), command = letters_1)
letters_1_button.grid(column = 0, columnspan = 1, row = 1,
sticky = (tkinter.W, tkinter.E))
letters_2_button = Button(
current_frame, text = "Letters 2",
font=("Helvetica", 25), command = letters_2)
letters_2_button.grid(column = 0, columnspan = 1, row = 2,
sticky = (tkinter.W, tkinter.E))
letters_3_button = Button(
current_frame, text = "Letters 3",
font=("Helvetica", 25), command = letters_3)
letters_3_button.grid(column = 0, columnspan = 1, row = 3,
sticky = (tkinter.W, tkinter.E))
letters_4_button = Button(
current_frame, text = "Letters 4",
font=("Helvetica", 25), command = letters_4)
letters_4_button.grid(column = 0, columnspan = 1, row = 4,
sticky = (tkinter.W, tkinter.E))
listening_test_button = Button(
current_frame, text = "Listening Test",
font = ("Helvetica", 25), command = Letters_Listening_Test.letters_listening_test)
listening_test_button.grid(column = 0, columnspan = 1, row = 5,
sticky = (tkinter.W, tkinter.E))
additional_resources_button = Button(
current_frame, text = "Additional Resources",
font = ("Helvetica", 25), command = additional_resources)
additional_resources_button.grid(column = 1, columnspan = 2, row = 5,
sticky = (tkinter.W, tkinter.E))
def Numbers():
number_screen = Initialize_Screen(frames[3], 4)
number_screen.back_to_main_program()
current_frame=tkinter.Frame(frames[3], width = 100, height = 100, bg = "gray")
side_screen = Side_Frame(current_frame)
def all_buttons_forget():
numbers_1_button.config(relief = RAISED, bg = "gray95")
license_plate_decoder_button.config(relief = RAISED, bg = "gray95")
def numbers_1():
all_buttons_forget()
numbers_1_button.config(relief = SUNKEN, bg = "gold")
numbers_1_intro_1_button = Button(
current_frame, text = "Intro to Numbers: Part 1",
font = ("Helvetica", 25), command = Numbers_1_Intro_1.numbers_1_intro_1)
numbers_1_intro_1_button.grid(column = 1, columnspan = 1, row = 1)
numbers_1_intro_1_button.config(bg = "gold")
numbers_1_intro_2_button = Button(
current_frame, text = "Intro to Numbers: Part 2",
font = ("Helvetica", 25), command = Numbers_1_Intro_2.numbers_1_intro_2)
numbers_1_intro_2_button.grid(column = 1, columnspan = 1, row = 2)
numbers_1_intro_2_button.config(bg = "gold")
def about_numbers():
result = messagebox.showinfo("About this Section",
"Though arabic letters are written right to left, arabic numbers are still written left to right. In this numbers section, the individual arabic numbers are introduced in two sets: 0-4, and 5-9.")
about_button = Button(
current_frame, text = "About",
font=("Helvetica", 25), command = about_numbers)
about_button.grid(column = 1, columnspan = 1, row = 0,
sticky = (tkinter.W, tkinter.E))
numbers_1_button = Button(
current_frame, text = "Intro to Numbers",
font=("Helvetica", 25), command = numbers_1)
numbers_1_button.grid(column = 0, columnspan = 1, row = 1,
sticky = (tkinter.W, tkinter.E))
numbers_1_button.config(highlightcolor = "gold")
license_plate_decoder_button = Button(
current_frame, text = "License Plate Decoder",
font=("Helvetica", 25), command = Numbers_License_Plate_Decoder.license_plate_game)
license_plate_decoder_button.grid(column = 0, columnspan = 1, row = 2,
sticky = (tkinter.W, tkinter.E))
license_plate_decoder_button.config(highlightcolor = "gold")
def lesson_1():
lesson_screen = Initialize_Screen(frames[4], 5)
lesson_screen.back_to_main_program()
current_frame=tkinter.Frame(frames[4], width = 100, height = 100, bg = "gray")
side_screen = Side_Frame(current_frame)
def all_buttons_forget():
print("In progress")
def about_letters():
result = messagebox.showinfo("About this Section",
"Lesson 1 focuses on learning personel pronouns.")
about_button = Button(
current_frame, text = "About",
font=("Helvetica", 25), command = about_letters)
about_button.grid(column = 1, columnspan = 1, row = 0,
sticky = (tkinter.W, tkinter.E))
lesson_1_button = Button(
current_frame, text = "Lesson 1",
font=("Helvetica", 25), command = Lesson_1_Part_1.lesson_1_part_1)
lesson_1_button.grid(column = 0, columnspan = 1, row = 2,
sticky = (tkinter.W, tkinter.E))
lesson_1_button.config(highlightcolor = "gold")
#################################################################3
Root_File_Name = "C:\\LearningArabic\\LiblibArriby\\"
ImagePath = Root_File_Name + "Icon\\"
MenuBackgroundImages = ImagePath + "menue_screen_images\\"
icon_tiles = ImagePath + "menue_screen_images\\"
master = Tk()
master.title("LibLib Arriby") # Label the root GUI window.
##master.geometry('700x900+0+0')
##master.attributes("-fullscreen", True) #This would make it full screen
window_width = master.winfo_screenwidth()-100 # Define window size
window_heigth = (master.winfo_screenheight())-100
NoF = 6 #This is the number of frames
frames = [] # This includes frames for all questions
for i in range(0, NoF):
frame=tkinter.Frame(
master, width=window_width,
height=window_heigth, borderwidth = 2,
relief = "sunken")
frame.grid(column = 0, row = 0, sticky = (tkinter.W, tkinter.E))
# frame.grid_remove()
frame.grid_propagate(False) #Turns off autoshrinking of Frame widget
frames.append(frame)
initialize_main_menue()
master.mainloop()
</code></pre>
<p>Here are some photos of what it currently looks like. The photos are all taken here in Egypt where I live. </p>
<p><a href="https://i.stack.imgur.com/pWa1o.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pWa1o.jpg" alt="Main Screen"></a>
<a href="https://i.stack.imgur.com/Gv3G0.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Gv3G0.jpg" alt="Lesson Screen"></a>
<a href="https://i.stack.imgur.com/HxaYw.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HxaYw.jpg" alt="Letter Screen"></a></p>
|
[] |
[
{
"body": "<p>Took me a <em>long</em> time to implement all the changes I made, so I hope you find this helpful!</p>\n\n<ul>\n<li><strong>Docstrings</strong>: You should include a <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\"><code>docstring</code></a> at the beginning of every method/class/module you write. This will allow documentation to identify what your code is supposed to do.</li>\n<li><strong>Unused Imports</strong>: You had a total of four unused imports. Having these in your code and confuse you and other people reading your code, as they/you try to find where you use them. Removing them can improve the readability of your code.</li>\n<li><strong>Parameter Spacing</strong>: There should not be any spacing between the parameter name, the <code>=</code>, and the value being passed. PEP-8 has <a href=\"https://www.python.org/dev/peps/pep-0008/#whitespace-in-expressions-and-statements\" rel=\"nofollow noreferrer\">rules about whitespace in expressions and statements</a>.</li>\n<li><strong>Multiline Parameters</strong>: Should you have to have multiple lines to pass in parameters, each parameter gets its own line. The indentation should also be four spaces after the beginning of the line that the method starts on. That may have been confusing; look at the improved code.</li>\n<li><strong>Unused loop variables</strong>: When you want to loop through something, or do something a number of times without using the variable created, use an <code>_</code>. This makes it clear that the variable used in the loop should be ignored, since you don't intend on using it.</li>\n<li><strong>Variable Naming</strong>: Variables in python should be in <code>snake_case</code>, not <code>Upper_Snake_Case</code> or <code>camelCase</code>. Classes in python should be <code>PascalCase</code>.</li>\n<li><strong>String Formatting</strong>: You have strings that require you to use <code>... + str(...) + ...</code>. This is a big red flag to me. You should use <code>f\"\"</code> to directly include your variables into your strings, without having to cast them as other types (<code>str()</code>, <code>int()</code>, etc).</li>\n<li><strong>Global Variables</strong>: It is almost never a good idea to use global variables, in python or any programming language. <a href=\"http://wiki.c2.com/?GlobalVariablesAreBad\" rel=\"nofollow noreferrer\">This list</a> does a very good job of explaining the negatives of using global variables, while also providing some instances where it might be okay. In general, though, it's not recommended.</li>\n<li><strong>Unneeded lambdas</strong>: You don't need to create a lambda to call a function.</li>\n<li><strong>Indentation</strong>: PEP-8 <a href=\"https://www.python.org/dev/peps/pep-0008/#indentation\" rel=\"nofollow noreferrer\">has rules about indentation</a>. Specifically, all indentation should be four spaces. A few spots in your code you use eight. Wrongly indented code could possibly mess with the entire scope of your program.</li>\n<li><strong>Unneeded Variable Assignment</strong>: When you call <code>mesagebox.showinfo(...)</code>, you assign it to a variable. This is not needed, since you don't use that variable.</li>\n</ul>\n\n<p><strong><em>Updated Code</em></strong></p>\n\n<pre><code>\"\"\"\nModule Docstring:\nA description about this program goes here\n\"\"\"\n\nimport tkinter\nfrom tkinter import *\nfrom tkinter import messagebox\n\nimport Letters_Listening_Test\nimport Numbers_1_Intro_1, Numbers_1_Intro_2\nimport Numbers_License_Plate_Decoder\nimport Lesson_1_Part_1\nimport Personal_Pronouns_Intro_1, Personal_Pronouns_Intro_2\nimport Greetings_Intro_1, Greetings_Intro_2, Greetings_Intro_3\nimport Greetings_Conversation_1, Greetings_Conversation_2\n\nclass InitializeScreen:\n \"\"\"\n Class for setting up the screen\n \"\"\"\n def __init__(self, cfn, img):\n self.current_frame_number = cfn\n self.image = img\n self.profile = \"Still in progress\"\n\n for index in range(0, NUMBER_OF_FRAMES): #This is for question frames\n FRAMES[index].grid_remove()\n\n cfn.grid(column=0, row=0, sticky=(tkinter.W, tkinter.E))\n for num in range(0, 4):\n cfn.grid_columnconfigure(num, weight=1)\n cfn.grid_rowconfigure(2, weight=1)\n cfn.grid_rowconfigure(5, weight=1)\n\n temp_image = f\"{MENU_BACKROUND_IMAGES}{str(img)}.png\"\n background_image = PhotoImage(file=(temp_image))\n background_image_label = Label(cfn, image=background_image)\n background_image_label.place(x=0, y=0, relwidth=1, relheight=1)\n background_image_label.tempimage = background_image\n\n def home_button(self):\n \"\"\"\n Builds the home button\n \"\"\"\n home_button = Button(\n self.current_frame_number,\n text=\"Home\",\n font=(\"Helvetica\", 25),\n command=initialize_main_menue\n )\n home_button.grid(column=0, row=0, sticky=(tkinter.W, tkinter.E))\n\n def profile_button(self):\n \"\"\"\n Buids the profile button\n \"\"\"\n profile_button = Button(\n self.current_frame_number,\n text=\" Profile \",\n font=(\"Helvetica\", 35),\n command=opening_screen.profile\n )\n profile_button.grid(column=1, columnspan=2, row=3)\n\n def main_program_button(self):\n \"\"\"\n Builds the main program button\n \"\"\"\n main_program_button = Button(\n self.current_frame_number,\n text=\"LibLib Arriby\",\n font=(\"Helvetica\", 35),\n command=initialize_lesson_menue\n )\n main_program_button.grid(column=1, columnspan=2, row=4)\n\n def back_to_main_program(self):\n \"\"\"\n Builds the button that takes you back to the main program\n \"\"\"\n back_to_main_program_button = Button(\n self.current_frame_number,\n text=\"Back\",\n font=(\"Helvetica\", 25),\n command=initialize_lesson_menue)\n back_to_main_program_button.grid(column=0, row=0)\n\nclass SideFrame:\n \"\"\"\n Class that builds a side frame on creation\n \"\"\"\n def __init__(self, current_frame):\n self.current_frame_number = current_frame\n current_frame['borderwidth'] = 2\n current_frame['relief'] = 'sunken'\n current_frame.grid_propagate(True) #Turns off autoshrink of Frame widget\n current_frame.grid_rowconfigure(0, weight=1)\n current_frame.grid_columnconfigure(1, weight=1)\n current_frame.grid(column=1, row=1)\n\ndef initialize_main_menue():\n \"\"\"\n Initializes the main menu\n \"\"\"\n opening_screen = InitializeScreen(FRAMES[0], 1)\n opening_screen.profile_button()\n opening_screen.main_program_button()\n\ndef initialize_lesson_menue():\n \"\"\"\n Initializes the lesson menu\n \"\"\"\n lesson_menue = InitializeScreen(FRAMES[1], 2)\n lesson_menue.home_button()\n lessons()\n\ndef lessons():\n \"\"\"\n Creates the lesson frame, and the corresponding buttons\n \"\"\"\n lessonframe = tkinter.Frame(\n FRAMES[1],\n bg=\"gray\",\n borderwidth=2,\n relief=\"sunken\"\n )\n lessonframe.grid(column=1, row=1)\n lessonframe.grid_rowconfigure(0, weight=1)\n lessonframe.grid_rowconfigure(1, weight=1)\n\n current_frame = lessonframe\n\n##############################################################################\n## The items below list out the titles of all of the different lesson plans ##\n##############################################################################\n letters_button = Button(\n current_frame,\n text=\"Letters\",\n font=(\"Helvetica\", 25),\n command=letters\n )\n\n numbers_button = Button(\n current_frame,\n text=\"Numbers\",\n font=(\"Helvetica\", 25),\n command=Numbers\n )\n\n lesson_1_button = Button(\n current_frame,\n text=\"Lesson 1\",\n font=(\"Helvetica\", 25),\n command=lesson_1\n )\n\n letters_button.grid(\n column=0,\n columnspan=1,\n row=1,\n sticky=(tkinter.W, tkinter.E)\n )\n numbers_button.grid(\n column=0,\n columnspan=1,\n row=2,\n sticky=(tkinter.W, tkinter.E)\n )\n lesson_1_button.grid(\n column=0,\n columnspan=1,\n row=3,\n sticky=(tkinter.W, tkinter.E)\n )\n\ndef letters():\n \"\"\"\n Creates all the letters buttons\n \"\"\"\n letter_screen = InitializeScreen(FRAMES[2], 3)\n letter_screen.back_to_main_program()\n current_frame = tkinter.Frame(FRAMES[2], width=100, height=100, bg=\"gray\")\n SideFrame(current_frame)\n\n def all_buttons_forget():\n \"\"\"\n Configurates all buttons\n \"\"\"\n letters_1_button.config(relief=RAISED, bg=\"gray95\")\n letters_2_button.config(relief=RAISED, bg=\"gray95\")\n letters_3_button.config(relief=RAISED, bg=\"gray95\")\n letters_4_button.config(relief=RAISED, bg=\"gray95\")\n\n class Letters:\n \"\"\"\n Creates intro and quiz buttons uppon creation\n \"\"\"\n def __init__(self, LN):\n self.lesson_number = LN\n\n intro_1_button = Button(\n current_frame,\n text=f\"Letters {LN}: Introduction Part 1\",\n font=(\"Helvetica\", 25),\n command=intro_1(LN)\n )\n intro_1_button.grid(column=1, columnspan=2, row=1)\n intro_1_button.config(bg=\"gold\")\n\n intro_2_button = Button(\n current_frame,\n text=f\"Letters {LN}: Introduction Part 2\",\n font=(\"Helvetica\", 25),\n command=intro_2(LN)\n )\n intro_2_button.grid(column=1, columnspan=2, row=2)\n intro_2_button.config(bg=\"gold\")\n\n quiz_button = Button(\n current_frame,\n text=f\"Letters {LN}: Quiz\",\n font=(\"Helvetica\", 25),\n command=quiz(LN)\n )\n quiz_button.grid(column=1, columnspan=2, row=3)\n quiz_button.config(bg=\"gold\")\n\n def intro_1(LN):\n \"\"\"\n Intro One to Letters\n \"\"\"\n module = __import__(f\"Letters_{LN}_Intro_1\")\n func = getattr(module, f\"letters_{LN}_intro_1\")\n func()\n\n def intro_2(LN):\n \"\"\"\n Intro Two to Letters\n \"\"\"\n module = __import__(f\"Letters_{LN}_Intro_2\")\n func = getattr(module, f\"letters_{LN}_intro_2\")\n func()\n\n def quiz(LN):\n \"\"\"\n Quiz for Letters\n \"\"\"\n module = __import__(f\"Letters_{LN}_Quiz\")\n func = getattr(module, f\"letters_{LN}_quiz\")\n func()\n\n def letters_1():\n \"\"\"\n Sets `letters_1_button` as the selected button\n \"\"\"\n all_buttons_forget()\n letters_1_button.config(relief=SUNKEN, bg=\"gold\")\n\n def letters_2():\n \"\"\"\n Sets `letters_2_button` as the selected button\n \"\"\"\n all_buttons_forget()\n letters_2_button.config(relief=SUNKEN, bg=\"gold\")\n\n def letters_3():\n \"\"\"\n Sets `letters_3_button` as the selected button\n \"\"\"\n all_buttons_forget()\n letters_3_button.config(relief=SUNKEN, bg=\"gold\")\n\n def letters_4():\n \"\"\"\n Sets `letters_4_button` as the selected button\n \"\"\"\n all_buttons_forget()\n letters_4_button.config(relief=SUNKEN, bg=\"gold\")\n\n def about_letters():\n \"\"\"\n Displays information about the arabic alphabet\n \"\"\"\n messagebox.showinfo(\"About this Section\", \"The arabic alphabet consists of 28 letters which have been divided into four sections for ease of learning. Each section introduces two sets of letters and then provides a quiz on those letters. The section on letters is then concluded with a listening comphrension and spelling test.\")\n\n def additional_resources():\n \"\"\"\n Displays additional information, if needed\n \"\"\"\n imageroot = f\"{ROOT_FILE_NAME}Lessons\\\\Letters\\\\AdditionalResources\\\\\"\n image = f\"{imageroot}Arabic_Alaphabet.png\"\n photo = PhotoImage(file=image)\n\n canvas = Canvas(tkinter.Toplevel(), height=566, width=850)\n canvas.grid(column=0, row=0)\n\n alphabet_photo = canvas.create_image(0, 0, image=photo, anchor=NW)\n alphabet_photo.image = photo\n\n about_button = Button(\n current_frame,\n text=\"About\",\n font=(\"Helvetica\", 25),\n command=about_letters\n )\n about_button.grid(column=1, columnspan=1, row=0, sticky=(tkinter.W, tkinter.E))\n\n letters_1_button = Button(\n current_frame,\n text=\"Letters 1\",\n font=(\"Helvetica\", 25),\n command=letters_1\n )\n letters_1_button.grid(column=0, columnspan=1, row=1, sticky=(tkinter.W, tkinter.E))\n\n letters_2_button = Button(\n current_frame,\n text=\"Letters 2\",\n font=(\"Helvetica\", 25),\n command=letters_2\n )\n letters_2_button.grid(column=0, columnspan=1, row=2, sticky=(tkinter.W, tkinter.E))\n\n letters_3_button = Button(\n current_frame,\n text=\"Letters 3\",\n font=(\"Helvetica\", 25),\n command=letters_3\n )\n letters_3_button.grid(column=0, columnspan=1, row=3, sticky=(tkinter.W, tkinter.E))\n\n letters_4_button = Button(\n current_frame,\n text=\"Letters 4\",\n font=(\"Helvetica\", 25),\n command=letters_4\n )\n letters_4_button.grid(column=0, columnspan=1, row=4, sticky=(tkinter.W, tkinter.E))\n\n listening_test_button = Button(\n current_frame,\n text=\"Listening Test\",\n font=(\"Helvetica\", 25),\n command=Letters_Listening_Test.letters_listening_test\n )\n listening_test_button.grid(column=0, columnspan=1, row=5, sticky=(tkinter.W, tkinter.E))\n\n additional_resources_button = Button(\n current_frame,\n text=\"Additional Resources\",\n font=(\"Helvetica\", 25),\n command=additional_resources\n )\n additional_resources_button.grid(column=1, columnspan=2, row=5, sticky=(tkinter.W, tkinter.E))\n\ndef Numbers():\n \"\"\"\n Creates numbers buttons\n \"\"\"\n number_screen = InitializeScreen(FRAMES[3], 4)\n number_screen.back_to_main_program()\n\n current_frame = tkinter.Frame(FRAMES[3], width = 100, height = 100, bg = \"gray\")\n SideFrame(current_frame)\n\n def all_buttons_forget():\n \"\"\"\n Configures all buttons\n \"\"\"\n numbers_1_button.config(relief=RAISED, bg=\"gray95\")\n license_plate_decoder_button.config(relief=RAISED, bg=\"gray95\")\n\n def numbers_1():\n \"\"\"\n Creates numbers_1 button\n \"\"\"\n all_buttons_forget()\n numbers_1_button.config(relief=SUNKEN, bg=\"gold\")\n\n numbers_1_intro_1_button = Button(\n current_frame,\n text=\"Intro to Numbers: Part 1\",\n font=(\"Helvetica\", 25),\n command=Numbers_1_Intro_1.numbers_1_intro_1\n )\n numbers_1_intro_1_button.grid(column=1, columnspan=1, row=1)\n numbers_1_intro_1_button.config(bg=\"gold\")\n\n numbers_1_intro_2_button = Button(\n current_frame,\n text=\"Intro to Numbers: Part 2\",\n font=(\"Helvetica\", 25),\n command=Numbers_1_Intro_2.numbers_1_intro_2\n )\n numbers_1_intro_2_button.grid(column=1, columnspan=1, row=2)\n numbers_1_intro_2_button.config(bg=\"gold\")\n\n def about_numbers():\n \"\"\"\n Shows information about the numbers section\n \"\"\"\n messagebox.showinfo(\"About this Section\", \"Though arabic letters are written right to left, arabic numbers are still written left to right. In this numbers section, the individual arabic numbers are introduced in two sets: 0-4, and 5-9.\")\n\n about_button = Button(\n current_frame,\n text=\"About\",\n font=(\"Helvetica\", 25),\n command=about_numbers\n )\n about_button.grid(column=1, columnspan=1, row=0, sticky=(tkinter.W, tkinter.E))\n\n numbers_1_button = Button(\n current_frame,\n text=\"Intro to Numbers\",\n font=(\"Helvetica\", 25),\n command=numbers_1\n )\n numbers_1_button.grid(column=0, columnspan=1, row=1, sticky=(tkinter.W, tkinter.E))\n numbers_1_button.config(highlightcolor=\"gold\")\n\n license_plate_decoder_button = Button(\n current_frame,\n text=\"License Plate Decoder\",\n font=(\"Helvetica\", 25),\n command=Numbers_License_Plate_Decoder.license_plate_game\n )\n license_plate_decoder_button.grid(column=0, columnspan=1, row=2, sticky=(tkinter.W, tkinter.E))\n license_plate_decoder_button.config(highlightcolor=\"gold\")\n\ndef lesson_1():\n \"\"\"\n Displays the first lesson\n \"\"\"\n lesson_screen = InitializeScreen(FRAMES[4], 5)\n lesson_screen.back_to_main_program()\n\n current_frame = tkinter.Frame(FRAMES[4], width=100, height=100, bg=\"gray\")\n\n def about_letters():\n \"\"\"\n Displays information about personal pronouns\n \"\"\"\n messagebox.showinfo(\"About this Section\", \"Lesson 1 focuses on learning personel pronouns.\")\n\n about_button = Button(\n current_frame,\n text=\"About\",\n font=(\"Helvetica\", 25),\n command=about_letters\n )\n about_button.grid(column=1, columnspan=1, row=0, sticky=(tkinter.W, tkinter.E))\n\n lesson_1_button = Button(\n current_frame,\n text=\"Lesson 1\",\n font=(\"Helvetica\", 25),\n command=Lesson_1_Part_1.lesson_1_part_1\n )\n lesson_1_button.grid(column=0, columnspan=1, row=2, sticky=(tkinter.W, tkinter.E))\n lesson_1_button.config(highlightcolor=\"gold\")\n\n#################################################################3\nROOT_FILE_NAME = \"C:\\\\LearningArabic\\\\LiblibArriby\\\\\"\nIMAGE_PATH = f\"{ROOT_FILE_NAME}Icon\\\\\"\nMENU_BACKROUND_IMAGES = f\"{IMAGE_PATH}menue_screen_images\\\\\"\nICON_TITLES = f\"{IMAGE_PATH}menue_screen_images\\\\\"\n\nopening_screen = None\n\nMASTER = Tk()\nMASTER.title(\"LibLib Arriby\") # Label the root GUI window.\n##master.geometry('700x900+0+0')\n##master.attributes(\"-fullscreen\", True) #This would make it full screen\n\n#Define window size\nWINDOW_WIDTH = MASTER.winfo_screenwidth() - 100\nWINDOW_HEIGHT = MASTER.winfo_screenheight() - 100\n\nNUMBER_OF_FRAMES = 6 #This is the number of frames\nFRAMES = [] # This includes frames for all questions\nfor _ in range(0, NUMBER_OF_FRAMES):\n frame = tkinter.Frame(\n MASTER,\n width=WINDOW_WIDTH,\n height=WINDOW_HEIGHT,\n borderwidth=2,\n relief=\"sunken\"\n )\n frame.grid(column=0, row=0, sticky=(tkinter.W, tkinter.E))\n # frame.grid_remove()\n frame.grid_propagate(False) #Turns off autoshrinking of Frame widget\n FRAMES.append(frame)\n\ninitialize_main_menue()\n\nMASTER.mainloop()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T11:00:58.970",
"Id": "438004",
"Score": "0",
"body": "Linny, thank you so much for taking the time to provide the insight that you did. I know I had a lot of code to work with so I value your effort that much more. I'm going to start implementing the changes now my self and then when I think I'm done I'll compare against what you've done to see if there are things I missed. Hopefully this helps me to actually learn how to code better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T12:46:20.780",
"Id": "438026",
"Score": "0",
"body": "Linny, I have one question on your above code. Almost at the end of your updated code you have a line: \n opening_screen = None\nWhat is the purpose of this line?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T07:03:25.093",
"Id": "225564",
"ParentId": "225537",
"Score": "3"
}
},
{
"body": "<p>Let's talk about numbers.</p>\n\n<pre><code>import Numbers_1_Intro_1, Numbers_1_Intro_2\nimport Lesson_1_Part_1\nimport Personal_Pronouns_Intro_1, Personal_Pronouns_Intro_2\nimport Greetings_Intro_1, Greetings_Intro_2, Greetings_Intro_3\nimport Greetings_Conversation_1, Greetings_Conversation_2\n</code></pre>\n\n<p>Remember when I said <a href=\"https://codereview.stackexchange.com/a/203743/52915\">this</a>?</p>\n\n<blockquote>\n <p>You can't put 50 questions/answers in the code itself, it becomes a mess. A royal mess. Don't even try.</p>\n</blockquote>\n\n<p>You made a good start by extracting the data from the main code. That was a very good first step. Now we need to make a couple more steps before this turns into a royal mess anyway. Because what happens when you've reached 50 lessons? What are your imports going to look like?</p>\n\n<p>So, the golden rule about numbers is we shouldn't be using numbers. Huh? Yes. Part of this is not to use <a href=\"https://stackoverflow.com/q/47882/1014587\">magic numbers</a>. If you ever see <code>get_adjusted_data(original_data * 42 - 2)</code> in someone's code, that's bad. But there're more ways for numbers to be bad. Like in your imports.</p>\n\n<pre><code>import Lesson_1_Part_1, Lesson_1_Part_2, Lesson_2_Part_1, Lesson_2_Part_2, Lesson_3_Part_1, Lesson_3_Part_2, Lesson_4_Part_1, Lesson_4_Part_2, Lesson_5_Part_1, Lesson_5_Part_2\n</code></pre>\n\n<p>What's in those files that you need one for each lesson? Can't you reuse the code? And what would that look like?</p>\n\n<p>Hard to say without taking a look at those files, but let's use another part of your code where the same thing goes wrong as an example. For example, your lessons.</p>\n\n<p>Instead of creating <code>lesson_1</code>, <code>lesson_2</code>, etc., create <code>lessons[]</code> and append the lessons to the list (like they did <a href=\"https://codereview.stackexchange.com/a/204118/52915\">here</a> with <code>answers.append(answer))</code>, using the index of the list to access different lessons. Your <code>letter</code>, <code>lesson</code> and <code>number</code> variable names all contain numbers. That's going to cost you in maintainability eventually.</p>\n\n<pre><code>def letters_1():\n all_buttons_forget()\n letters = Letters(1)\n letters_1_button.config(relief = SUNKEN, bg = \"gold\")\n\ndef letters_2():\n all_buttons_forget()\n letters = Letters(2)\n letters_2_button.config(relief = SUNKEN, bg = \"gold\")\n\ndef letters_3():\n all_buttons_forget()\n letters = Letters(3)\n letters_3_button.config(relief = SUNKEN, bg = \"gold\")\n\ndef letters_4():\n all_buttons_forget()\n letters = Letters(4)\n letters_4_button.config(relief = SUNKEN, bg = \"gold\")\n</code></pre>\n\n<p>And your buttons do the same thing:</p>\n\n<pre><code>letters_2_button = Button(\n current_frame, text = \"Letters 2\",\n font=(\"Helvetica\", 25), command = letters_2)\nletters_2_button.grid(column = 0, columnspan = 1, row = 2,\n sticky = (tkinter.W, tkinter.E))\n</code></pre>\n\n<p>I don't have the time to fully understand what global magic is going on here, but could we possibly do something like this instead?</p>\n\n<pre><code>def all_buttons_forget(colour):\n for button in letters_buttons[num]:\n button.config(relief = RAISED, bg = colour)\n\ndef create_button(num):\n # Figure out max amount of buttons per row and column based on number\n # Beware of the magic numbers\n # Set these in a constant somewhere, or as member variable of the class it goes under\n # Assuming 6 buttons per col_span, 5 per row\n calculated_col = (num // 6)\n calculated_col_span = calculated_col + 1\n calculated_row = num % 5\n\n # Font should be in a constant as well\n Button(\n current_frame, text = \"Letters {0}\".format(num),\n font=(\"Helvetica\", 25), command = commands[num])\n letters_buttons[num].grid(column = calculated_col, columnspan = calculated_col_span, row = calculated_row,\n sticky = (tkinter.W, tkinter.E))\n\ndef create_letter(num, rel, colour):\n all_buttons_forget(\"gray95\")\n letters[num] = Letters(num)\n letters[num].button.config(relief = rel, bg = colour)\n\ncreate_button(4)\ncreate_letter(4, SUNKEN, \"gold\")\n</code></pre>\n\n<p>Functions and variables should <strong>never</strong> have indexes in their name. Sometimes a number is hard to avoid, but indexes aren't. Using indexes in a variable indicates you're using the wrong datatype.</p>\n\n<p>Instead, put them in a <a href=\"https://docs.python.org/3/library/stdtypes.html#list\" rel=\"nofollow noreferrer\">list</a>, a <a href=\"https://docs.python.org/3/library/stdtypes.html#dict\" rel=\"nofollow noreferrer\">dictionary</a>, an <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"nofollow noreferrer\">enum</a>, anything.\nSuch containers are indexable, iterable, searchable and a lot more useful than a lot of individual functions. Also a lot easier to maintain. Say you got 50 `lett</p>\n\n<p>Take an interest in modulo operators <code>%</code> and how integer division works <code>//</code> in Python 3. Pass arguments around. Set a couple as constant in the class or globally so you can remember what it means.</p>\n\n<p>Those colours for example. You could make a dictionary:</p>\n\n<pre><code>COLOURS = {\n 'active' : \"gold\",\n 'inactive': \"gray95\"\n}\n\ncreate_letter(4, SUNKEN, COLOURS['active'])\n</code></pre>\n\n<p>Perhaps you want to set <code>SUNKEN</code> as part of the <code>'active'</code> configuration as well? Use a nested dictionary:</p>\n\n<pre><code>CONFIGS = {\n 'active':\n {'rel': SUNKEN, 'colour': \"gold\"},\n 'inactive':\n {'rel': RAISED, 'colour': \"gray95\"}\n}\n\ncreate_letter(4, CONFIGS['active']['rel'], CONFIGS['active']['colour'])\n</code></pre>\n\n<p>Can we improve this even further? Absolutely. We could simplify the configuration, or put your entire configuration in a JSON. Plenty of options. But that's for another review.</p>\n\n<p>It's all a bit rough around the edges and your code hangs so together it's impractical to rewrite it all (especially since you really should be combining this advice with Linny's, so it's going to look different anyway).\nBut I hope to convey the idea here. It still isn't as good as I'd like it, but hey, we're taking steps here. Never try to run the entire race in one step.</p>\n\n<p>And remember. If you can make this piece of code more generic, you can do the same to the rest of your code. Including your imports.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T10:52:06.500",
"Id": "438482",
"Score": "1",
"body": "This is fantastic, I've already started rewriting the letters_1, letters_2, etc. but this goes a long way - even with re-writing the other modules so that I don't have to import an individual one for each lesson set. What you said about functions not having numbers makes sense, but I'd never seen that anywhere before. Good to know. \nI hope to work on re-writing this section of code but hopefully in a short while I'll have an updated version available. You and Linny have given me a lot to work with here!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T09:04:26.267",
"Id": "225755",
"ParentId": "225537",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "225564",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T17:27:55.810",
"Id": "225537",
"Score": "3",
"Tags": [
"python",
"beginner",
"python-3.x",
"game",
"tkinter"
],
"Title": "Tkinter program to teach Arabic"
}
|
225537
|
<p>I'm new to C++ and trying to learn by implementing data structures in it.</p>
<p>Is the code below the most efficient way of implementing the data structure in C++? Does it conform to C++ standards, and how readable is it?</p>
<pre><code>#include <iostream>
class Node
{
public:
int data;
Node *next;
Node(int data)
{
this->data = data;
this->next = nullptr;
}
};
class LinkedList
{
public:
Node *head;
Node *tail;
int length;
LinkedList()
{
this->head = nullptr;
this->tail = nullptr;
this->length = 0;
}
void add(int data);
void add(int data, int position);
void delete_node(int position);
int get_length();
void print();
int get_first();
};
void LinkedList::add(int data)
{
Node *node = new Node(data);
if (this->head == nullptr)
{
this->head = node;
}
else
{
this->tail->next = node;
}
this->tail = node;
this->length = this->length + 1;
}
void LinkedList::add(int data, int position)
{
Node *temp_head = this->head;
Node *node = new Node(data);
int i = 0;
while (i < this->length)
{
if (i == position - 1)
{
node->next = this->head->next;
this->head->next = node;
}
this->head = this->head->next;
i++;
}
this->head = temp_head;
this->length = this->length + 1;
}
void LinkedList::print()
{
Node *temp_head = this->head;
while (this->head != nullptr)
{
std::cout << this->head->data << '\n';
this->head = this->head->next;
}
this->head = temp_head;
}
int LinkedList::get_length()
{
return this->length;
}
int LinkedList::get_first()
{
return this->head->data;
}
int main()
{
LinkedList *llist = new LinkedList();
llist->add(0);
llist->add(1);
llist->add(3);
llist->add(4);
llist->add(2, 2);
llist->print();
std::cout << "Length: " << llist->get_length() << '\n';
std::cout << "First Element : " << llist->get_first() << '\n';
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T20:39:05.583",
"Id": "437951",
"Score": "2",
"body": "If you are new to a language, you should add the _beginner_ tag to your question. Reviewers take this tag into account."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T01:03:09.400",
"Id": "439041",
"Score": "1",
"body": "Have a look at: https://codereview.stackexchange.com/questions/125955/my-first-implementation-of-a-linked-list-in-c and my follow up. That should give you some hints."
}
] |
[
{
"body": "<ul>\n<li><p>C++ is not Java. You may safely get rid of all <code>this-></code>.</p></li>\n<li><p>The client doesn't need to know about <code>Node</code>. Make it an inner class of the <code>LinkedList</code>.</p></li>\n<li><p>The <code>~LinkedList()</code> destructor is missing. You should also consider (or prohibit) the copy constructor, <code>operator=</code>, and move constructor.</p></li>\n<li><p><code>add(int data, int position)</code> may silently leak memory. If the <code>position</code> is too large, the created node is not linked into the list, and is lost. Also, there is no way to <em>prepend</em> a node.</p></li>\n<li><p>I don't like the <code>temp_head</code> approach. Better leave the <code>head</code> alone, and iterate using a cursor variable, e.g.:</p>\n\n<pre><code>void LinkedList::print() {\n Node * cursor = head;\n while (cursor) {\n std::cout << cursor->data << '\\n';\n cursor = cursor->next;\n }\n}\n</code></pre>\n\n<p>At least, there is no need to restore <code>head</code>.</p>\n\n<p>Ditto for <code>add</code>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T18:00:04.017",
"Id": "438090",
"Score": "1",
"body": "That's a prime place for `for`: `void LinkedList::print() const { for (auto p = head; p; p = p->next) std::cout << p->data << '\\n'; }`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T21:20:48.617",
"Id": "225547",
"ParentId": "225545",
"Score": "4"
}
},
{
"body": "<p>In addition to the above, these are my comments:</p>\n\n<h2>API completeness</h2>\n\n<p>One of the attractive features of a linked list is adding elements in O(1) anywhere in the list, given a Node*. But this API only allows for adding new elements in the middle in O(n) via add(int, position). I would at least allow a method of adding after a node, given a Node*.</p>\n\n<h2>Encapsulation</h2>\n\n<p>Usually you don't want classes to have public members (one exception is static constexpr). So move head, tail and length to private.</p>\n\n<h2>Code compactness</h2>\n\n<ol>\n<li>You don't need the constructor, because you can initialize the members using {} in their declaration. <a href=\"http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#es23-prefer-the--initializer-syntax\" rel=\"nofollow noreferrer\">prefer {}</a></li>\n<li>Conceptually, add(int data) is a private case of add(int data, int position), so the code should reflect that IMO.</li>\n</ol>\n\n<h2>Readability</h2>\n\n<ol>\n<li>Since the length cannot be negative, it's better to use size_t instead of int.</li>\n<li><p>Const correctness. Add the const specifier at the end of functions that don't change the list, like: getters, print() etc: <code>int get_length() const;</code>. Note that this would prevent changing head in print() - which is good because you don't expect the list to change if you're merely printing it.</p></li>\n<li><p>Use the shorter <code>length += 1;</code> notation.</p></li>\n</ol>\n\n<h2>Reusability</h2>\n\n<p>One big thing to remember when writing a container is to templatize it. Since you're now doing your first steps in C++ I understand that you want to take one step at time, so just int as the type is fine.</p>\n\n<pre><code>template<typename T>\nclass LinkedList\n{\n...\n}\n</code></pre>\n\n<h2>Memory management</h2>\n\n<ol>\n<li>In add() use a self-managed std::shared_ptr instead of raw pointers and new. Read about smart pointers, they're one of the best features in C++11.</li>\n<li>I don't see a reason for the <code>new LinkedList();</code> in main(). Just a <code>LinkedList list;</code> would be enough.</li>\n</ol>\n\n<h2>Efficiency</h2>\n\n<p>In add(int data, int position), why continue traversing the while loop if you have already added the element?</p>\n\n<h2>Unit tests</h2>\n\n<p>Testing is really important. I would suggest using a testing framework (I work with gtests) and writing some unit tests. Going through each public method and thinking how to test it - by itself, or in conjunction with other functions - and writing unit tests to prove correctness is a sure way to increase quality.</p>\n\n<p>Note that the implementation for delete_node() is missing. Make sure that it reuses the node search code that <code>add(data, position)</code> has.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T17:52:20.153",
"Id": "225597",
"ParentId": "225545",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "225597",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-04T20:36:23.200",
"Id": "225545",
"Score": "2",
"Tags": [
"c++",
"beginner",
"linked-list"
],
"Title": "Implementation of a Singularly LinkedList"
}
|
225545
|
<p>If you don't know what is Schelling's model of segregation, you can read it <a href="http://nifty.stanford.edu/2014/mccown-schelling-model-segregation/" rel="nofollow noreferrer">here</a>. </p>
<blockquote>
<p>The Schelling model of segregation is an agent-based model that illustrates how individual tendencies regarding neighbors can lead to segregation. In the Schelling model, agents occupy cells of rectangular space. A cell can be occupied by a single agent only. Agents belong to one of two groups and are able to relocate according to the fraction of friends (i.e., agents of their own group) within a neighborhood around their location. The model's basic assumption is as follows: an agent, located in the center of a neighborhood where the fraction of friends f is less than a predefined tolerance threshold F (i.e., f < F), will try to relocate to a neighborhood for which the fraction of friends is at least f (i.e., f ≥ F) </p>
</blockquote>
<p>I have written the following code to run the Schelling's model of segregation simulation. </p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
from shapely.geometry import Point
import geopandas as gp
from matplotlib import pyplot as plt
import shapely
import random
import itertools
import copy
import matplotlib.animation
import pandas as pd
class geo_schelling(object):
def __init__(self,shapefile,spacing,empty_ratio,similarity_threshhold,n_iterations,ratio,races=2):
self.shapefile=shapefile
self.spacing=spacing
self.empty_ratio=empty_ratio
self.similarity_threshhold=similarity_threshhold
self.n_iterations=n_iterations
self.ratio=ratio
self.races=races
self.shape_cali=gp.read_file(shapefile)
def generate_grid_in_polygon(self,spacing, polygon):
''' This Function generates evenly spaced points within the given
GeoDataFrame. The parameter 'spacing' defines the distance between
the points in coordinate units. '''
# Get the bounds of the polygon
minx, miny, maxx, maxy = polygon.bounds
# Now generate the entire grid
x_coords = list(np.arange(np.floor(minx), int(np.ceil(maxx)), spacing))
y_coords = list(np.arange(np.floor(miny), int(np.ceil(maxy)), spacing))
grid = [Point(x) for x in zip(np.meshgrid(x_coords, y_coords)[0].flatten(), np.meshgrid(x_coords, y_coords)[1].flatten())]
# Finally only keep the points within the polygon
list_of_points = [point for point in grid if point.within(polygon)]
return list(zip([point.x for point in list_of_points],[point.y for point in list_of_points]))
def populate(self):
self.all_counties=self.shape_cali.geometry
self.empty_houses=[]
self.agents={}
self.all_houses=[]
for county in self.all_counties:
if type(county)==shapely.geometry.multipolygon.MultiPolygon:
for j in county:
self.all_houses.extend(self.generate_grid_in_polygon(self.spacing,j))
else:
self.all_houses.extend(self.generate_grid_in_polygon(self.spacing,county))
random.shuffle(self.all_houses)
self.n_empty=int(self.empty_ratio*len(self.all_houses))
self.empty_houses=self.all_houses[:self.n_empty]
self.remaining_houses=self.all_houses[self.n_empty:]
divider=int(round(len(self.remaining_houses)*self.ratio))
houses_majority=self.remaining_houses[:divider]
houses_minority=self.remaining_houses[divider:]
self.agents.update(dict(zip(houses_majority,[1]*divider)))
self.agents.update(dict(zip(houses_minority,[2]*int(len(self.remaining_houses)-divider))))
return self.agents,self.empty_houses,len(self.all_houses)
def plot(self):
fig, ax = plt.subplots(figsize=(15,15))
agent_colors = {1:'b', 2:'r'}
for agent,county in itertools.zip_longest(self.agents,self.all_counties):
#ax.scatter(self.agent[0], self.agent[1], color=agent_colors[agents[agent]])
if type(county)==shapely.geometry.multipolygon.MultiPolygon:
for j in county:
x,y=j.exterior.xy
ax.plot(x,y)
elif county is None:
pass
else:
x,y=county.exterior.xy
ax.plot(x,y)
ax.scatter(agent[0], agent[1], color=agent_colors[self.agents[agent]])
ax.set_title("Simulation", fontsize=10, fontweight='bold')
ax.set_xticks([])
ax.set_yticks([])
def is_unsatisfied(self, x, y):
"""
Checking if an agent is unsatisfied or satisified at its current
position.
"""
race = self.agents[(x,y)]
count_similar = 0
count_different = 0
min_width=min(np.array(self.all_houses)[:,0])
max_width=max(np.array(self.all_houses)[:,0])
min_height=min(np.array(self.all_houses)[:,1])
max_height=max(np.array(self.all_houses)[:,1])
if x > min_width and y > min_height and (x-self.spacing, y-self.spacing) not in self.empty_houses:
if (x-self.spacing, y-self.spacing) in self.agents:
if self.agents[(x-self.spacing, y-self.spacing)] == race:
count_similar += 1
else:
count_different += 1
else:
pass
if y > min_height and (x,y-self.spacing) not in self.empty_houses:
if (x,y-self.spacing) in self.agents:
if self.agents[(x,y-self.spacing)] == race:
count_similar += 1
else:
count_different += 1
else:
pass
if x < (max_width-self.spacing) and y > min_height and (x+self.spacing,y-self.spacing) not in self.empty_houses:
if (x+self.spacing,y-self.spacing) in self.agents:
if self.agents[(x+self.spacing,y-self.spacing)] == race:
count_similar += 1
else:
count_different += 1
else:
pass
if x > min_width and (x-self.spacing,y) not in self.empty_houses:
if (x-self.spacing,y) in self.agents:
if self.agents[(x-self.spacing,y)] == race:
count_similar += 1
else:
count_different += 1
else:
pass
if x < (max_width-self.spacing) and (x+self.spacing,y) not in self.empty_houses:
if (x+self.spacing,y) in self.agents:
if self.agents[(x+self.spacing,y)] == race:
count_similar += 1
else:
count_different += 1
else:
pass
if x > min_width and y < (max_height-self.spacing) and (x-self.spacing,y+self.spacing) not in self.empty_houses:
if (x-self.spacing,y+self.spacing) in self.agents:
if self.agents[(x-self.spacing,y+self.spacing)] == race:
count_similar += 1
else:
count_different += 1
else:
pass
if x > min_width and y < (max_height-self.spacing) and (x,y+self.spacing) not in self.empty_houses:
if (x,y+self.spacing) in self.agents:
if self.agents[(x,y+self.spacing)] == race:
count_similar += 1
else:
count_different += 1
else:
pass
if x < (max_width-self.spacing) and y < (max_height-self.spacing) and (x+self.spacing,y+self.spacing) not in self.empty_houses:
if (x+self.spacing,y+self.spacing) in self.agents:
if self.agents[(x+self.spacing,y+self.spacing)] == race:
count_similar += 1
else:
count_different += 1
else:
pass
if (count_similar+count_different) == 0:
return False
else:
return float(count_similar)/(count_similar+count_different) < self.similarity_threshhold
def move_to_empty(self,x,y):
race = self.agents[(x,y)]
empty_house = random.choice(self.empty_houses)
self.updated_agents[empty_house] = race
del self.updated_agents[(x, y)]
self.empty_houses.remove(empty_house)
self.empty_houses.append((x, y))
def update_animate(self):
"""
Update the square on the basis of similarity threshhold. This is the
function which actually runs the simulation.
"""
fig, ax = plt.subplots(figsize=(15,15))
agent_colors = {1:'b', 2:'r'}
ax.set_xticks([])
ax.set_yticks([])
def update(i):
self.old_agents = copy.deepcopy(self.agents)
n_changes = 0
for agent,county in itertools.zip_longest(self.old_agents,self.all_counties):
#ax.scatter(self.agent[0], self.agent[1], color=agent_colors[agents[agent]])
if type(county)==shapely.geometry.multipolygon.MultiPolygon:
for j in county:
x,y=j.exterior.xy
ax.plot(x,y)
elif county is None:
pass
else:
x,y=county.exterior.xy
ax.plot(x,y)
ax.scatter(agent[0], agent[1], color=agent_colors[self.agents[agent]])
ax.set_title('Simulation', fontsize=10, fontweight='bold')
if self.is_unsatisfied(agent[0], agent[1]):
agent_race = self.agents[agent]
empty_house = random.choice(self.empty_houses)
self.agents[empty_house] = agent_race
del self.agents[agent]
self.empty_houses.remove(empty_house)
self.empty_houses.append(agent)
n_changes += 1
if n_changes==0:
return
ani = matplotlib.animation.FuncAnimation(fig, update, frames= self.n_iterations,repeat=False)
plt.show()
def update_normal(self):
"""
This function is the normal version of the update and doesn't include
any animation whatsoever as it is in the case of the update_animate
function.
"""
for i in range(self.n_iterations):
self.old_agents = copy.deepcopy(self.agents)
n_changes = 0
for agent in self.old_agents:
if self.is_unsatisfied(agent[0], agent[1]):
agent_race = self.agents[agent]
empty_house = random.choice(self.empty_houses)
self.agents[empty_house] = agent_race
del self.agents[agent]
self.empty_houses.remove(empty_house)
self.empty_houses.append(agent)
n_changes += 1
print(n_changes)
print(i)
if n_changes == 0:
break
def calculate_similarity(self):
"""
Checking if an agent is unsatisfied or satisified at its current
position.
"""
similarity = []
min_width=min(np.array(self.all_houses)[:,0])
max_width=max(np.array(self.all_houses)[:,0])
min_height=min(np.array(self.all_houses)[:,1])
max_height=max(np.array(self.all_houses)[:,1])
for agent in self.agents:
count_similar = 0
count_different = 0
x = agent[0]
y = agent[1]
race = self.agents[(x,y)]
if x > min_width and y > min_height and (x-self.spacing, y-self.spacing) not in self.empty_houses:
if (x-self.spacing, y-self.spacing) in self.agents:
if self.agents[(x-self.spacing, y-self.spacing)] == race:
count_similar += 1
else:
count_different += 1
else:
pass
if y > min_height and (x,y-self.spacing) not in self.empty_houses:
if (x,y-self.spacing) in self.agents:
if self.agents[(x,y-self.spacing)] == race:
count_similar += 1
else:
count_different += 1
else:
pass
if x < (max_width-self.spacing) and y > min_height and (x+self.spacing,y-self.spacing) not in self.empty_houses:
if (x+self.spacing,y-self.spacing) in self.agents:
if self.agents[(x+self.spacing,y-self.spacing)] == race:
count_similar += 1
else:
count_different += 1
else:
pass
if x > min_width and (x-self.spacing,y) not in self.empty_houses:
if (x-self.spacing,y) in self.agents:
if self.agents[(x-self.spacing,y)] == race:
count_similar += 1
else:
count_different += 1
else:
pass
if x < (max_width-self.spacing) and (x+self.spacing,y) not in self.empty_houses:
if (x+self.spacing,y) in self.agents:
if self.agents[(x+self.spacing,y)] == race:
count_similar += 1
else:
count_different += 1
else:
pass
if x > min_width and y < (max_height-self.spacing) and (x-self.spacing,y+self.spacing) not in self.empty_houses:
if (x-self.spacing,y+self.spacing) in self.agents:
if self.agents[(x-self.spacing,y+self.spacing)] == race:
count_similar += 1
else:
count_different += 1
else:
pass
if x > min_width and y < (max_height-self.spacing) and (x,y+self.spacing) not in self.empty_houses:
if (x,y+self.spacing) in self.agents:
if self.agents[(x,y+self.spacing)] == race:
count_similar += 1
else:
count_different += 1
else:
pass
if x < (max_width-self.spacing) and y < (max_height-self.spacing) and (x+self.spacing,y+self.spacing) not in self.empty_houses:
if (x+self.spacing,y+self.spacing) in self.agents:
if self.agents[(x+self.spacing,y+self.spacing)] == race:
count_similar += 1
else:
count_different += 1
else:
pass
if (count_similar+count_different) == 0:
return False
else:
return float(count_similar)/(count_similar+count_different) < self.similarity_threshhold
try:
similarity.append(float(count_similar)/(count_similar+count_different))
except:
similarity.append(1)
return sum(similarity)/len(similarity)
def get_data_by_county(self):
"""
Return all the data by counties.
"""
df=pd.DataFrame(columns=['County Name','Majority Population (Number)', 'Minority Population (Number)'])
for county,name in zip(self.shape_cali.geometry,self.shape_cali.NAME):
minority_num=0
majority_num=0
for agent in self.agents:
if Point(agent).within(county):
if self.agents[agent]==1:
majority_num+=1
if self.agents[agent]==2:
minority_num+=1
dic={'County Name':[name],'Majority Population (Number)':[majority_num],'Minority Population (Number)':[minority_num]}
df=df.append(pd.DataFrame(dic),ignore_index=True)
df['Total Population']=df['Majority Population (Number)']+df['Minority Population (Number)']
df['Majority Population (%)']=df[['Total Population','Majority Population (Number)']].apply(lambda x:0 if x['Total Population']==0 else x['Majority Population (Number)']/x['Total Population'],axis=1)
df['Minority Population (%)']=df[['Total Population','Minority Population (Number)']].apply(lambda x:0 if x['Total Population']==0 else x['Minority Population (Number)']/x['Total Population'],axis=1)
return df
shapefile='CA.shp'
spacing=0.20
empty_ratio=0.30
similarity_threshhold=0.01
n_iterations=100
ratio=0.535
</code></pre>
<p>You can get the shapefile <a href="https://drive.google.com/open?id=12TpUiOTRxH2MmP6iVSH4mPRcg6aYsssK" rel="nofollow noreferrer">here</a> if you want to try it. So the above implementation is fine but the runtime is very slow. I want to optimize the following methods <code>is_unsatisfied</code>,<code>generate_grid_in_polygon</code> . Is it possible to speed up these functions with numba or parallelization? Or any other suggestions are welcome!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T04:19:07.283",
"Id": "437975",
"Score": "0",
"body": "I would suggest to add a small description of the problem statement that you linked also in the question directly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T04:25:56.897",
"Id": "437978",
"Score": "1",
"body": "@dfhwze I added a description. Thanks for the suggestion!"
}
] |
[
{
"body": "<p>welcome to code review!\nI've split my answer into three parts, each reviewing your code from a different perspective.</p>\n\n<p><strong>Structural and Stylistic</strong></p>\n\n<p>There is a coding style standard in python called PEP8. A good IDE like Pycharm will be able to tell you how to keep to it. It makes your code a lot more readable and consistent by using certain conventions which python coders will recognise. It helps with general organisation too.</p>\n\n<p>You don't need to specify <code>else: pass</code>. This will be done automatically. Note this is <em>not</em> the same as <code>else: continue</code>.</p>\n\n<p>You seem to have an indentation error in <code>check_similarity</code> with your <code>try: similarity.append(...</code> where the code is unreachable due to an early <code>return</code>. Again, using an IDE like pycharm will show these kinds of bugs straight away. </p>\n\n<p>You regularly define instance attributes outside of your <code>__init__()</code>. This can be OK, but sometimes you then try to mutate these variables which can cause issues. (How can you change that which does not exist?) Defining all of your instance variables in your <code>__init__()</code> will likely let you know if you have some extra that you no longer need, or perhaps you have two doing the same thing. It's also easier to break up classes if that becomes necessary.</p>\n\n<p>Perhaps the biggest issue with the code is the large blocks of <code>if else</code> in <code>is_unsatisfied()</code> and <code>check_similarity()</code>. This is basically unreadable with no comments as to what the conditions mean, lots of repeated checks and repeated code across the two methods. If you cleaned up these conditions I think you would find ways of exiting early to speed things up. For example, you perform the check <code>if x > min_width</code> 4 times, and <code>y < (max_height - self.spacing)</code> twice in the same method.</p>\n\n<p>It's good that you've used docstrings but they're quite sparse and don't really help. <code>check_similarity()</code> for example says <code>\"\"\"Checking if an agent is unsatisfied or satisfied at its current position.\"\"\"</code> However, you then loop over <em>all</em> agents in <code>self.agents</code> and your satisfied condition seems based on a single agent? Rewrite your docstrings and add comments!</p>\n\n<p>I would split your class up - certainly into two classes, maybe three. All of the data gathering and plotting should be done separately to the core logic.</p>\n\n<hr>\n\n<p><strong>Quick Tweaks</strong></p>\n\n<ul>\n<li>You can use tuple unpacking to define variables. e.g.</li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code># Old\nx = agent[0]\ny = agent[1]\n\n# New\nx, y = agent\n</code></pre>\n\n<p>Likewise, you can pass in unpacked tuples as arguments:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># Old\nif self.is_unsatisfied(agent[0], agent[1]):\n ...\n\n# New\nif self.is_unsatisfied(*agent):\n ...\n</code></pre>\n\n<ul>\n<li><p>In python 3, classes don't need to specify that they inherit from <code>object</code>. </p></li>\n<li><p>It's clearer and more standard to say <code>if not x:</code> than <code>if x == 0:</code></p></li>\n<li><p>If you have long lines, you can split them by going to a new line without closing a bracket. Very long lines are usually an indication of bad writing, though.</p></li>\n<li><p>Wrap your code to be executed in <code>if __name__ == '__main__':</code></p></li>\n<li><p>Don't create instance attributes if they're only going to be used by a single method and never touched again. <code>self.old_agents</code> for example.</p></li>\n<li><p>You shouldn't need to <code>round()</code> and then cast to <code>int()</code>.</p></li>\n<li><p><code>isinstance()</code> is the preferred way of checking types in python.</p></li>\n<li><p>Almost always, it's better to use <code>[]</code> and <code>{}</code> to cast to list or dict, rather than <code>list()</code> or <code>dict()</code>.</p></li>\n<li><p>Only use single letter variables when it makes sense. <code>x</code> and <code>y</code> is ok, <code>for j in county:</code> is not; what is <code>j</code>?</p></li>\n<li><p>Why are you looping over items, but using the item as an index?</p></li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>for agent in self.agents:\n if Point(agent).within(county):\n if self.agents[agent] == 1:\n ...\n</code></pre>\n\n<p>If you want to loop over an item and an index, use <code>enumerate()</code>.</p>\n\n<hr>\n\n<p><strong>Speed</strong></p>\n\n<p>You have used numpy, but only really to generate values. This isn't giving you any of its speed advantages. Where possible you want to perform vectorised operations on entire arrays, rather than looping over lists. For example, if you have some numpy array and want to check its values lie in a particular range:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>array = np.array([4, 3, 8, 9, 10, 1, 1, 5])\n\n# Normal looping over array as list\nreturn all(0 < item < 20 for item in array)\n\n# Vectorised numpy operation\nreturn (array > 0).all() and (array < 20).all()\n</code></pre>\n\n<p>If you clear up your code in <code>is_unsatisfied()</code> I think you'll be able to rewrite it to use these vectorised operations instead of what you currently have. I don't see any reason to use Numba or multithreading here.</p>\n\n<p>You may find it too difficult to convert everything to numpy, in which case I would suggest using generators instead. In places where you're constantly appending to a list, or incrementing a value, you can switch to using <code>yield</code>. This allows you to create a generator expression, which will generally be faster.</p>\n\n<p>You have two running counts for <code>count_similar</code> and <code>count_different</code>. I don't see why you can't just have a <code>count</code> which you increment and decrement. This means you don't need to get the average value at the end, and removes a lot of extra code.</p>\n\n<hr>\n\n<p>There are lots of other changes which could be made but I think it might be better for you to implement the above, then post an updated question. You can then get more specific help with your code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T12:48:41.957",
"Id": "438376",
"Score": "1",
"body": "Thanks a lot. Will make change in next couple of days and repost!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T12:13:02.493",
"Id": "445615",
"Score": "1",
"body": "Hello, I have posted a new question with cleaned up code and also implemented most of the improvements suggested!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T09:54:19.540",
"Id": "225571",
"ParentId": "225554",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "225571",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T02:37:11.710",
"Id": "225554",
"Score": "6",
"Tags": [
"python",
"numpy",
"simulation",
"clustering",
"matplotlib"
],
"Title": "Schelling's model of Segregation Python implementation with Geopandas"
}
|
225554
|
<p>This is a Haskell implementation of Conway's Game of Life.</p>
<p>It plays on a console. It should be able to play a field of any size, but we only give it a glider on a small field to run at this point.</p>
<p>Using a file named <code>GameOfLife.hs</code>:</p>
<pre><code>import Control.Concurrent
import Text.Printf
main :: IO ()
main = gameOfLife (
[ [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
, [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
, [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
] )
</code></pre>
<p>The <code>main</code> function only calls <code>gameOfLife</code> with some startup state - a list of lists of 0s and 1s:</p>
<pre><code>gameOfLife :: [[Integer]] -> IO ()
gameOfLife state = do
pretty_print state
let new_state = transition state
sleep
printf "\ESC[%dA" $ length state -- move cursor to beginning.
gameOfLife new_state
</code></pre>
<p>First we pretty print the state, define the new state as the transition of the original state, sleep (to slow it down enough to visualize the changes), move the cursor to the beginning using an escape code so we can draw the new state over the old, and then recursively call gameOfLife with the new state.</p>
<p>The pretty print function is as follows - it uses a sprite function to map the 0's and 1's to a viewable field of characters:</p>
<pre><code>pretty_print :: [[Integer]] -> IO ()
pretty_print state = do
mapM_ print_row state
where
print_row linestate = do
putStrLn $ concat $ map sprite linestate
sprite :: Integer -> String
sprite 0 = "."
sprite _ = "*"
</code></pre>
<p>"Sprite," is probably the wrong word. Maybe, "char," would be better?</p>
<p>When printed - it looks like this - here's sample output:</p>
<pre class="lang-bsh prettyprint-override"><code>$ ./GameOfLife
.*..........
..*.........
***.........
............
............
............
............
............
............
............
</code></pre>
<p>Then the new state is defined as the transition of the old state.</p>
<p>We start with the row of interest, and get the rows before it and after it. Then we go element by element. When we would get an index that would be out of bounds, I get the index from the other end of the field. This adds some time to the algorithm, I'm sure, but it has the nice effect of allowing the field to wrap around.</p>
<pre><code>-- get new state row by row.
transition :: [[Integer]] -> [[Integer]]
transition state = do
process 0
where
last_i = ((length state) - 1)
process n = process_row n : (if n == last_i then [] else process (n + 1))
process_row i = process_rows prev_row this_row next_row
where
prev_row = state !! (if i == 0 then last_i else (i - 1))
this_row = state !! i
next_row = state !! (if i == last_i then 0 else (i + 1))
process_rows prev row next = do
proc 0
where
last_j = ((length row) - 1)
proc m = proc_col m : (if m == last_j then [] else proc (m + 1))
proc_col j = live_die (row !! j) (
-- column to left
(if j == 0 then (last prev + last row + last next) else
(prev !! (j - 1) + row !! (j - 1) + next !! (j - 1)))
-- above & below
+ prev !! j + next !! j
-- column to right
+ (if j == last_j then (prev !! 0 + row !! 0 + next !! 0) else
(prev !! (j + 1) + row !! (j + 1) + next !! (j + 1)))
)
</code></pre>
<p>The logic for does the cell live or die is if the cell is currently alive, then it stays alive if 2 or 3 surrounding cells are alive, else it dies. If the current cell isn't alive, it only comes to life if there are 3 cells alive next to it. I believe I succinctly cover this logic with pattern matching:</p>
<pre><code>live_die :: Integer -> Integer -> Integer
live_die _ 3 = 1
live_die 1 2 = 1
live_die _ _ = 0
</code></pre>
<p>Finally, each transition is followed by some sleeping to avoid having a crazy-looking blur on the screen - I have no problems with the animation with a sleep of 1/10th of a second per transition:</p>
<pre><code>sleep :: IO ()
sleep = threadDelay 100000
</code></pre>
<p>I have stack installed, so I built it with:</p>
<pre class="lang-bsh prettyprint-override"><code>$ stack ghc GameOfLife.hs
</code></pre>
<p>(A friend had to build with <code>ghc -dynamic GameOfLife.hs</code> because he just installed GHC with Arch or Manjaro's package manager, <code>pacman</code>.)</p>
<p>Make the executable file actually executable (only had to do this the first time.)</p>
<pre class="lang-bsh prettyprint-override"><code>$ chmod -x GameOfLife
</code></pre>
<p>and execute it like so:</p>
<pre class="lang-bsh prettyprint-override"><code>$ ./GameOfLife
.*..........
..*.........
***.........
............
............
............
............
............
............
............
</code></pre>
<p>Ideally, the executable could take a value to seed a pseudo-random number generator (PRNG) or a filename with a user-created image. For those goals, I suppose it's obvious that <code>main</code> shouldn't unconditionally start <code>gameOfLife</code> like it does.</p>
<p>Probably the printing should be further separated from the <code>transition</code>.</p>
<p>Maybe we could use data types to represent the cells (0's and 1's) and the field (a list of lists of Integers). But we would need <code>(+)</code> implemented for Cell values.</p>
<p>I think I can see a few other ways to slightly reduce redundant function calls, but I'm not sure I'll save any lines of code that way.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T17:15:19.520",
"Id": "438530",
"Score": "0",
"body": "Why is it important to have \"no external libs\"? Using lists whenever you need O(1) indexing is just wrong. You could try using `array` package instead of lists, which is wired in with ghc, but it is still an external dependency, if you think about."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T17:27:04.077",
"Id": "438536",
"Score": "0",
"body": "You have a point, but maybe I don't need O(1) indexing - one answerer did suggest zipping with modified lists. I've been giving this some thought and I wonder if maybe the list of lists representing the field is the wrong paradigm."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T17:41:10.777",
"Id": "438538",
"Score": "0",
"body": "Even if you do not use indexing, lists are very inefficient unless you are lucky and ghc is able to fuse computation"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T17:50:48.853",
"Id": "438539",
"Score": "1",
"body": "I was quite proud of getting it to work, but I did not spend much mental energy on reducing algorithmic complexity. What I wonder is if there is a complete reworking of the model that I can factor out and abstract away from the IO handling."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T17:59:19.733",
"Id": "438540",
"Score": "0",
"body": "don't get me wrong I am not trying to criticise what you've done here. Good job on getting it to work! I am merely suggesting a way you can improve it. Not sure what you mean about abstracting away from IO handling, but good luck with it anyways ;)"
}
] |
[
{
"body": "<p>Since you haven't specified any focus points, I'll focus on readability.</p>\n\n<p>To speed things up, you may want a <code>Matrix</code> or <code>Vector</code> to represent your board.</p>\n\n<p><code>transition</code>:</p>\n\n<ul>\n<li><p>To make this function more readable, you may want to introduce a more\nabstract way to address neighbouring fields. For example, a function\nlike</p>\n\n<pre><code>liveness :: Board -> Position -> Integer\nliveness board pos = sum . filter (isAlive board) . map (addOffset pos) $\n [ (dx,dy) | dx <- (-1,0,1), dy <- (-1,0,1), (dx,dy) /= (0,0) ]\n\naddOffset :: Position -> Offset -> Position\naddOffset = ...\n\nisAlive :: Board -> Position -> Bool\nisAlive = ...\n</code></pre>\n\n<p>that counts the number of living cells surrounding <code>pos</code>.</p>\n\n<p>Whether <code>addOffset</code> should treat the edge as a border or wrap would be a detail.</p></li>\n<li><p>You would like to abstract out explicit recursion in <code>process</code>:</p>\n\n<pre><code>process n = map process_row [0..length state - 1]\n</code></pre></li>\n<li><p>If you have constant-time lookup into your cells, <code>process_row</code> will not\nneed to fetch previous and next rows.</p></li>\n<li><p>As an example of the simplicity one could achieve with this part of the code, see <a href=\"https://rhnh.net/2012/01/02/conway's-game-of-life-in-haskell/\" rel=\"noreferrer\">Xavier Shay's Game of Life</a>; some things could be improved here, also, but the general game logic is very short and succinct.</p></li>\n</ul>\n\n<p><code>main</code>:</p>\n\n<ul>\n<li>The parenthesis is redundant.</li>\n</ul>\n\n<p><code>gameOfLife</code>:</p>\n\n<ul>\n<li><p>You could abstract out the recursion part so that you have one combinator\nthat performs the meat of the IO operation, and another that iterates it\ninfinitely. That way you could reuse the meat for other versions where a\nuser must interact, or where it only runs a fixed number of iterations:</p>\n\n<pre><code>stepGame1 :: GameState -> IO GameState\nstepGame1 gameState = do\n prettyPrint gameState\n threadDelay 100000\n printf \"\\ESC[%dA\" (length state) -- move cursor to beginning\n return (transition gameState)\n\nstepGameInf :: GameState -> IO a\nstepGameInf gameState = stepGame1 gameState >>= stepGameInf\n</code></pre>\n\n<p>But you could also do it differently; for example, it's a bit weird that <code>stepGame1</code> both prints and transitions the game state.</p></li>\n</ul>\n\n<p>For further improvements on the way transitions are computed, you may want to look at:</p>\n\n<ul>\n<li><p>Chris Penner's <a href=\"https://chrispenner.ca/posts/conways-game-of-life\" rel=\"noreferrer\">Conway's Game Of Life Using Representable And Comonads</a>, which uses Vector for the game state and comonads; he uses some comonad library tricks (<code>Control.Comonad.Representable.Store</code>) to achieve memoization between transitions.</p></li>\n<li><p>The <a href=\"http://hackage.haskell.org/package/base/docs/Control-Monad-ST.html\" rel=\"noreferrer\"><code>ST</code> monad</a> for efficient, pure transitions without the comonad complexity.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T09:47:31.560",
"Id": "225570",
"ParentId": "225556",
"Score": "8"
}
},
{
"body": "<h1>Naming, the first</h1>\n\n<p>Normally haskell is written in <code>camelCase</code>, not <code>under_scores</code>. Up to now, I thought this an arbitrary convention, but I misread</p>\n\n<pre><code>process n = process_row n : (if n == last_i then [] else process (n + 1))\nprocess_row i = process_rows prev_row this_row next_row\n</code></pre>\n\n<p>as</p>\n\n<pre><code>process n = process_row n : (if n == last_i then [] else process (n + 1))\nprocess row i = process_rows prev_row this_row next_row\n</code></pre>\n\n<p>in this context. Do you spot the difference? Just a little underscore vs a space.</p>\n\n<h1>(Outer) Core loop</h1>\n\n<p>But let's get to the point:</p>\n\n<pre><code>process n = process_row n : (if n == last_i then [] else process (n + 1))\n</code></pre>\n\n<p>This uses manual recursion and transmits indices. Both are not very haskellish. I cannot eliminate them step by step, but both can be avoided with</p>\n\n<pre><code>*Main> :t zipWith3\n zipWith3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]\n</code></pre>\n\n<p>Try to rewrite the first part of your main loop, i.e. where you iterate over the rows in your <code>transition</code> function. Do it now! Game of life is a very good way to learn and improve your haskell, but the best way to learn is to do it yourself, not read up somebody else's solution. Must of the following points a make are just fillers of lesser importance between progressively added spoilers to a <code>zipWith3</code> solution.</p>\n\n<p>ZipWith example:</p>\n\n<pre><code>zipWith3 (\\a b c -> a ++ b ++ c)\n [\"Hello, \", \"Good \"]\n [\"World\" , \"night \"]\n [\"!\" , \"John boy\"]\n\n[\"Hello, World!\",\"Good night John boy\"]\n</code></pre>\n\n<p>Why are indexing and manual recursion not \"haskellish\"? This does not sound like an argument, right?</p>\n\n<ul>\n<li>both are error-prone</li>\n<li>both are too verbose</li>\n<li>indexing is slow</li>\n</ul>\n\n<h1>zipWith3 spoiler 1</h1>\n\n<p>re-use your function <code>process_row</code> like <code>zipWith3 process_row ...</code>.</p>\n\n<h1>Naming, the second</h1>\n\n<p>You are indexing with<code>this_row = state !! i</code> into a variable (or binding, as haskell programmer might prefer) named <code>state</code>. This is a list (of lists). Lists names have often plural form, I recommend</p>\n\n<ul>\n<li><code>world</code></li>\n<li><code>board</code></li>\n<li><code>lines</code> (shadows a Prelude function)</li>\n<li><code>rows</code></li>\n</ul>\n\n<p>or whatever term pops up in your specification.</p>\n\n<p>Another squabble about naming: You have <code>process</code>, <code>process_rows</code>, <code>process_row</code>, <code>proc</code> and <code>proc_col</code>. You are not seriously happy with this, are you? I expect the solution to be broken down in smaller and smaller parts, but this: <code>process_row i = process_rows</code> sounds like you are processing a row by processing (all) rows. I'd call <code>process_rows</code> instead <code>combineAdjacentRows</code> or something like it. </p>\n\n<p>Yes, this is a filler. Stop now and rewrite <code>process</code> now.</p>\n\n<h1>zipWith3 spoiler 2</h1>\n\n<p>This omits the first and last line <code>zipWith3 process_row state (tail state) (tail (tail state))</code>, and consequently shrinks the world/board of game of life vertically, but can be extended into a solution.</p>\n\n<h1>Do, do, do</h1>\n\n<p>Why didn't you write <code>sleep = threadDelay 100000</code> as</p>\n\n<pre><code>sleep = do\n threadDelay 100000\n</code></pre>\n\n<p>Just kidding! You don't need it. There are a lot of <code>do</code>s in your case that you don't need either. Especially those in <code>transition</code> are unnecessary. I do not want to dive too deep, but until you understand monads use <code>do</code> only in context of <code>IO ()</code> respectively <code>IO a</code>.</p>\n\n<h1>zipWith3 solution</h1>\n\n<p>Add the last row of <code>state</code> in front the <code>state</code>. (See how much better with would read with <code>board</code>?), then the plain <code>state</code> lines, finally all lines except this first plus the first line like this:</p>\n\n<pre><code>transition state = zipWith3 process_rows (last state:state) state (tail state ++ state)\n where\n process_rows prev row next = -- (unchanged)\n</code></pre>\n\n<p>There is more to do, but no complete rewrite by me today.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T21:52:06.157",
"Id": "438112",
"Score": "0",
"body": "I considered zip, but I wanted to avoid concatenating lists on lists - seems like a bad idea in Haskell given their immutability."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T20:54:58.943",
"Id": "225611",
"ParentId": "225556",
"Score": "3"
}
},
{
"body": "<p>If you want efficient, concise and elegant solution for Game of Life you do want to use an array library instead of resorting to lists. Here is a simple and fast implementation using <a href=\"https://github.com/lehins/massiv\" rel=\"nofollow noreferrer\"><code>massiv</code></a> that automatically parallelizes computation of each intermediate state of game of life. The core feature in this implementation is the <code>lifeStencils</code>. Documentation for massiv stencils is available in the haddock as well as in the readme on github, but I can expend explanation in here a bit as well, if necessary.</p>\n\n<p>You can run it with:</p>\n\n<pre><code>$ clear\n$ stack gameOfLife.hs 30 50\n</code></pre>\n\n<p>Initial state will be randomly generated using <code>splitmix</code> package.</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>#!/usr/bin/env stack\n{- stack --resolver lts-14.0 script --optimize --package massiv --package splitmix --package random -}\nmodule Main where\n\nimport Control.Concurrent\nimport Data.Massiv.Array as A\nimport Data.Massiv.Array.Mutable.Algorithms (iterateUntilM)\nimport Data.Word\nimport System.Environment\nimport System.Random\nimport System.Random.SplitMix (initSMGen)\n\nlifeRules :: Word8 -> Word8 -> Word8\nlifeRules 1 2 = 1\nlifeRules _ 3 = 1\nlifeRules _ _ = 0\n\nlifeStencil :: Stencil Ix2 Word8 Word8\nlifeStencil = makeStencil (Sz (3 :. 3)) (1 :. 1) $ \\ get ->\n lifeRules <$> get (0 :. 0) <*>\n (get (-1 :. -1) + get (-1 :. 0) + get (-1 :. 1) +\n get ( 0 :. -1) + get ( 0 :. 1) +\n get ( 1 :. -1) + get ( 1 :. 0) + get ( 1 :. 1))\n\nlife :: Array S Ix2 Word8 -> Array DW Ix2 Word8\nlife = mapStencil Wrap lifeStencil\n\nprintState :: Array S Ix2 Word8 -> IO ()\nprintState arr = do\n let consCell v acc\n | v == 0 = '.' : acc\n | otherwise = '*' : acc\n A.forM_ (foldrWithin Dim1 consCell \"\" arr) putStrLn\n putStrLn $ \"\\ESC[\" ++ shows (A.totalElem $ A.size arr) \"A\"\n\nmain :: IO ()\nmain = do\n [r, c] <- fmap Prelude.read <$> getArgs\n smGen <- initSMGen\n let bool2Word8 b = if b then 1 else 0\n initRandom = compute (bool2Word8 <$> randomArray smGen split random Par (Sz2 r c))\n () <$ iterateUntilM\n (\\ _ state _ -> False <$ (printState state >> threadDelay 20000))\n (const life)\n initRandom\n</code></pre>\n\n<p>Here are some important optimizations that are implemented here:</p>\n\n<ul>\n<li>Using stencils we get optimal, safe indexing of cells while avoiding bounds checking. Also border checking is handled automatically for us with <code>Wrap</code></li>\n<li>As mentioned before, computation of next state is performed in parallel</li>\n<li>Because of how <code>iterateUntilM</code> works, during the whole lifetime of the program there are only two arrays ever allocated, therefore it is extremely memory efficient.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T15:02:43.000",
"Id": "442583",
"Score": "1",
"body": "Strictly speaking, this response isn't code review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T18:02:52.943",
"Id": "442656",
"Score": "2",
"body": "@SimonShine the review portion was very concise and simple: do not use lists. But I could not just say that, it would be rude. I had to provide an example how it should be done using arrays."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T17:08:47.753",
"Id": "225779",
"ParentId": "225556",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T03:35:40.220",
"Id": "225556",
"Score": "15",
"Tags": [
"haskell",
"game-of-life"
],
"Title": "A Haskell implementation of Conway's Game of Life, viewable on the console, no external libs"
}
|
225556
|
<h3>Algorithm</h3>
<p><a href="https://en.wikipedia.org/wiki/Bubble_sort" rel="nofollow noreferrer">Bubble sort</a>, also known as sinking sort, is a sorting algorithm that repeatedly steps through a list, compares adjacent pairs and swaps them if they are not in the right order. The pass through the list is repeated, until the sorting is complete. The algorithm, which is a comparison sort, is named for the way smaller or larger elements "bubble" to the top of the list. </p>
<hr>
<h3>Solution 1</h3>
<p>This is my <code>BubbleSort</code> function:</p>
<pre><code>def BubbleSort(l):
for i in range(len(l)-1):
for j in range(len(l)-1-i):
if (l[j]>l[j+1]):
l[j],l[j+1]=l[j+1],l[j]
return l
</code></pre>
<p>which outputs:</p>
<pre><code>print(BubbleSort([1,5,-5,0,10,100]))
[-5, 0, 1, 5, 10, 100]
</code></pre>
<h3>Solution 2</h3>
<p>With some detailed advice, here is a second solution, limited to using one list comprehension:</p>
<pre><code>def BubbleSort(l):
[l.append(l.pop(0) if i == len(l) - 1 or l[0] < l[1] else l.pop(1)) for j in range(0, len(l)) for i in range(0, len(l))]
</code></pre>
<p>which somewhat outputs the same:</p>
<pre><code>l = [1,5,-5,0,10,100]
BubbleSort(l)
print(l)
[-5, 0, 1, 5, 10, 100]
</code></pre>
<hr>
<p>Would you be so kind and review it? I'd also like to know about time/space complexities, if you possibly had time.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T10:53:06.070",
"Id": "438003",
"Score": "0",
"body": "I don't understand what you are really asking, all of your answers are here and in Wikipedia, you pretty much tackle it already"
}
] |
[
{
"body": "<p>BubbleSort is not an efficient algorithm. Talking time-complexity it runs in <span class=\"math-container\">\\$O(n^2)\\$</span> which is okay given a very small array, but for a larger amount of numbers its almost unusable.</p>\n\n<p>This is a comparison between a few sorting algorithms that i wrote in C#. As you can see the only advantage of BubbleSort over the other algorithms is that it is very easy to program.\n<a href=\"https://i.stack.imgur.com/gjasY.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/gjasY.png\" alt=\"Time Complexity\"></a></p>\n\n<p>Anyway - back to your code. I would your implementation is good although i find the first one way more readable.\nAll in all if you just wanted to implement BubbleSort you did a good job, but if you really want to sort a list, you should definitely consider another algorithm that runs in <span class=\"math-container\">\\$O(log(n))\\$</span>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T09:49:51.443",
"Id": "226246",
"ParentId": "225557",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "226246",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T03:48:05.903",
"Id": "225557",
"Score": "2",
"Tags": [
"python",
"beginner",
"algorithm",
"python-3.x",
"sorting"
],
"Title": "Bubble Sort: Time and Space Complexities"
}
|
225557
|
<p>My <a href="https://codereview.stackexchange.com/questions/225454/logger-adapter-with-a-configurable-chain-of-responsibility-of-middlewares">logging adapter</a> is using a dictionary for storing data that is passed from middleware to middleware.</p>
<p>It is a one-liner:</p>
<blockquote>
<pre><code>public class Log : Dictionary<SoftString, object> {}
</code></pre>
</blockquote>
<p>Since it's using <code>SoftString</code> (like <code>string</code> but case-insensitive and trimmed) for the key and there are also two different types of data there, I was using a <em>workaround</em> by adding weird suffixes to the actual names to be able to tell them apart.</p>
<p>This <em>system</em> is very shaky so I'd like to have something <em>stronger</em> and easier to use. I thought I'll replace <a href="https://codereview.stackexchange.com/questions/220938/toggle-any-application-feature-on-or-off">strings as tokens</a> with some other type. This is how <code>ItemKey<T></code> was born.</p>
<h3>API</h3>
<p><code>ItemKey<T></code> still uses a name but it now allows me to use <code>T</code> as a <em>tag</em> that I constrained to be an <code>Enum</code>. Both properties are used for the equality check.</p>
<pre><code>public readonly struct ItemKey<T> : IEquatable<ItemKey<T>> where T : Enum
{
public ItemKey(SoftString name, T tag)
{
Name = name;
Tag = tag;
}
[AutoEqualityProperty]
public SoftString Name { get; }
[AutoEqualityProperty]
public T Tag { get; }
public override int GetHashCode() => AutoEquality<ItemKey<T>>.Comparer.GetHashCode(this);
public override bool Equals(object obj) => obj is ItemKey<T> && Equals(obj);
public bool Equals(ItemKey<T> other) => AutoEquality<ItemKey<T>>.Comparer.Equals(this, other);
public static implicit operator ItemKey<T>((string name, T tag) key) => new ItemKey<T>(key.name, key.tag);
}
public enum LogItemTag
{
Property, // These items are ready to be logged
Metadata, // These items need to be processed before they can be a 'Property'
}
</code></pre>
<h3><code>ItemKey<T></code> in action</h3>
<p>From here I created the new <code>Log</code> <em>dto</em> with all the APIs that I need. I use only a single dictionary because I copy it in certain scenarios so it's easier to do it once rather than having a separate dictionary for each item type.</p>
<pre><code>public class Log : IEnumerable<(ItemKey<LogItemTag> Key, object Value)>
{
private readonly IDictionary<ItemKey<LogItemTag>, object> _data = new Dictionary<ItemKey<LogItemTag>, object>();
public Log() { }
private Log(IDictionary<ItemKey<LogItemTag>, object> data)
{
_data = new Dictionary<ItemKey<LogItemTag>, object>(data);
}
public static Log Empty => new Log();
public Log Copy() => new Log(_data);
public Log SetItem((string Name, LogItemTag Tag) key, object value)
{
_data[key] = value;
return this;
}
public T GetItemOrDefault<T>((string Name, LogItemTag Tag) key, T defaultValue = default)
{
return _data.TryGetValue(key, out var obj) && obj is T value ? value : defaultValue;
}
public bool TryGetValue<T>((string Name, LogItemTag Tag) key, out T value)
{
if (_data.TryGetValue(key, out var obj) && obj is T result)
{
value = result;
return true;
}
else
{
value = default;
return false;
}
}
public bool RemoveItem((string Name, LogItemTag Tag) key) => _data.Remove(key);
public IEnumerator<(ItemKey<LogItemTag> Key, object Value)> GetEnumerator()
{
return _data.Select(x => (x.Key, x.Value)).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
</code></pre>
<h3>Extensions</h3>
<p>I then extended it with a few helpers so that I don't always have to use the <em>enum</em>:</p>
<pre><code>public static class LogExtensions
{
public static Log SetProperty(this Log log, string name, object value)
{
return log.SetItem((name, LogItemTag.Property), value);
}
public static Log SetMetadata(this Log log, string name, object value)
{
return log.SetItem((name, LogItemTag.Metadata), value);
}
public static bool TryGetProperty<T>(this Log log, string name, out T value)
{
return log.TryGetValue((name, LogItemTag.Property), out value);
}
public static bool TryGetMetadata<T>(this Log log, string name, out T value)
{
return log.TryGetValue((name, LogItemTag.Metadata), out value);
}
}
</code></pre>
<hr>
<h3>Questions</h3>
<p>This is pretty simple but maybe you'll still have some more ideas how to enhance it?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T06:33:24.483",
"Id": "437985",
"Score": "0",
"body": "Or should I make the _tag_ a `string`? The _enum_ cannot be extended by the user mhmmm...."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T15:28:36.347",
"Id": "438052",
"Score": "1",
"body": "Is this intended to be used from multiple threads?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T15:30:45.970",
"Id": "438053",
"Score": "0",
"body": "@VisualMelon nope, every call to `logger.Log(..)` will create a new instance of this `Log` dictionary."
}
] |
[
{
"body": "<p>I'm not sure what you gain by limiting this to using an <code>enum</code> as the Tag. I wouldn't use a string, that's for sure, but why not leave it completely free? If a user wants to use the <code>LogItemTag</code> schema, then they can. If they want to use strings, they are free to do so.</p>\n\n<hr />\n\n<p>This look like an infinite loop (though hopefully it will StackOverflow):</p>\n\n<pre><code>public override bool Equals(object obj) => obj is ItemKey<T> && Equals(obj);\n</code></pre>\n\n<p>I presume this was the intention:</p>\n\n<pre><code>public override bool Equals(object obj) => obj is ItemKey<T> key && Equals(key);\n</code></pre>\n\n<hr />\n\n<p>I would prefer this was a method:</p>\n\n<pre><code>public static Log Empty => new Log();\n</code></pre>\n\n<p>It just feels wrong to be returning an Empty thing that isn't immutable.</p>\n\n<hr />\n\n<p>Personally I would use <code>KeyValuePair</code> rather than a tuple for the key/value pairs, because I would never allow a tuple as part of a public API. Similarly, I would dispense with the tuple version of <code>ItemKey</code> in the APIs (e.g. on <code>GetItemOrDefault</code>): it's just adding inconsistency which will make the API harder to use. The implicit conversion seems like a fine way of 'overloading' the API (though again personally I wouldn't allow it).</p>\n\n<hr />\n\n<p>Your clone constructor will initialise 2 dictionaries.</p>\n\n<hr />\n\n<p>As always, the public API should carry inline documentation (<code>///</code>) so that it's purpose is clear to the maintainer and consumer. It doesn't need to be extensive or <code>cref</code> everything, but it should explain the intention clearly.</p>\n\n<hr />\n\n<p>I'd expect <code>Copy</code> to be called <code>Clone</code> (copy sounds in-place to me). <code>TryGetValue</code> should be called <code>TryGetItem</code> to be consistent with the other methods.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T16:05:50.687",
"Id": "438067",
"Score": "0",
"body": "Is there any particular reason you wouldn't allow tuples on public APIs or just a personal preference? The names of the fields are _compiled_, or rather decorated with an attribute so intellisense shows them. I find it's a convenient way of showing that these two names belong together. Oh boy, so many bugs :-\\ I was lucky the equality check was _strong_ so it didn't popup in my tests yet."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T16:07:34.073",
"Id": "438071",
"Score": "0",
"body": "Mhmm... I think the copy constructor will create only one dictionary because the default constructor isn't called and the field is initialized by it. The assignment after field definition is just a syntactic sugar. I'm pretty sure this will be _injected_ into the default ctor. ReSharper also isn't screaming but for the sake of consistency I'll better move it there myself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T16:13:50.997",
"Id": "438072",
"Score": "1",
"body": "@t3chb0t My hated of tuples is personal preference (I think most people would disagree that it's worth worrying about). The names do carry, but they can be splatted into another tuple with different names, so they are really a structural, rather than nominal, construct, and I do not like mixing structural and nominal constructs. The 'default constructor' is just a name for the parameterless constructor you get by default; it doesn't have any bearing on whether the fields are initialised or not. It has to call that twice, because the constructor could have side effects."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T16:18:13.950",
"Id": "438073",
"Score": "0",
"body": "The default ctor will be called only when you do `: this()`, otherwise it won't be called, see [example on ideone](https://ideone.com/nFsIYs) - I like the point about _soft_ tuple names. You virtually convinced me to change it, I guess ;-P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T16:20:05.133",
"Id": "438074",
"Score": "0",
"body": "@t3chb0t Aye, but the field initialisation is done before any constructor is called; it's not lumped into the 'default' ctor. ([TIO example](https://tio.run/##FcuxCsJADADQ@e4rYqcW1B/o6OKgUHDoIA7hGo5AeoHkFET67afu7yU/JDVq7elcMtzeXmkdYxJ0h8k0G67wicErVk7wUl7gilx6r/YL9wegZR/@JJy0uAodZ@NKFy7Ud2cS0T3MarLsumGMYYtba18))"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T16:22:32.340",
"Id": "438075",
"Score": "0",
"body": "Oh, indeed, a field is initialized but the constructor isn't called... what the hack. This is unexpected. What is then `: this()` for when the compiler does what it likes :-\\"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T16:23:17.663",
"Id": "438076",
"Score": "0",
"body": "@t3chb0t you're thinking of `struct`s"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T16:25:54.740",
"Id": "438077",
"Score": "0",
"body": "The IL explains what happens here. The field initialization is injected into the custom constructor unless you use `: this()` when it then remains in the default one. OK, this means that the dictionary is really initialized twice."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T15:52:23.200",
"Id": "225590",
"ParentId": "225561",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "225590",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T05:40:26.423",
"Id": "225561",
"Score": "6",
"Tags": [
"c#",
"generics",
"hash-map",
"enum",
"extension-methods"
],
"Title": "Distinguish between different types of log items in a dictionary by their key"
}
|
225561
|
<p>What I'd like to do is read data from a stream (like ifstream::read), but reserve N = 4 bytes from being returned. The last 4 bytes of the stream are not part of the data itself, but are metadata.</p>
<p>In the general case, the stream is not an ifstream so I won't be able to seek, putback, or determine the size of the stream ahead of time. Here I'm just using it as an example.</p>
<p>My approach is to keep a reserve buffer of 4 bytes to ensure I never accidentally return the last four bytes of the stream. However, the logic turned out to be pretty hard to manage... I'm hoping there's a cleaner way to accomplish what I want.</p>
<p>I'd like to ask for a code review in terms readability (is there a better approach?) and/or performance (is there anything I'm doing that is suboptimal?)</p>
<pre><code>#include <iostream>
#include <array>
#include <vector>
#include <fstream>
#include <cstring>
#define RESERVE_SIZE 4
static std::array<char, RESERVE_SIZE> reserve = {0,0,0,0}; // buffer for holding bytes at end of stream
static bool first_read = true; // true if first read and reserve buffer is empty
// helper function to print output
void data_printer(std::string msg, char * bd, size_t bytes_read) {
std::cout << msg << bytes_read << ": ";
for(size_t i=0; i < bytes_read; i++) std::cout << (int)bd[i] << " ";
std::cout << std::endl;
}
// helper function to read and return # of bytes read
size_t read_count(std::ifstream & myFile, char * dst, size_t length) {
myFile.read(dst, length);
return myFile.gcount();
}
// dst -- output buffer, has at least "length" bytes
// exact -- if true, expect "length" bytes read from myFile and copied to dst; throw error if less than that
// return value is the number of bytes read from my File and copied to dst
size_t read_reserve(std::ifstream & myFile, char * dst, size_t length, bool exact=false) {
if(first_read) {
myFile.read(reserve.data(), RESERVE_SIZE);
first_read = false;
}
if(exact) {
if(length >= RESERVE_SIZE) {
std::memcpy(dst, reserve.data(), RESERVE_SIZE);
myFile.read(dst + RESERVE_SIZE, length - RESERVE_SIZE);
myFile.read(reserve.data(), RESERVE_SIZE);
if(myFile.gcount() != RESERVE_SIZE) throw std::runtime_error("not enough data in file :(");
return length;
} else { // RESERVE_SIZE > length
std::memcpy(dst, reserve.data(), length);
// since some of the reserve buffer was consumed, shift the unconsumed bytes to beginning of array
// then read from file to fill up reserve buffer
std::memmove(reserve.data(), reserve.data() + length, RESERVE_SIZE - length);
myFile.read(reserve.data() + RESERVE_SIZE - length, length);
if(myFile.gcount() != length) throw std::runtime_error("not enough data in file :(");
return length;
}
} else { // !exact -- we can't assume that "length" bytes are left in myFile; there could even be zero bytes left
if(length >= RESERVE_SIZE) {
// use "dst" as a temporary buffer, since it's already allocated
// it is not a good idea to allocate a temp buffer of size length, as length can be large
std::memcpy(dst, reserve.data(), RESERVE_SIZE);
size_t n_read = read_count(myFile, dst + RESERVE_SIZE, length - RESERVE_SIZE);
size_t n_bufferable = n_read + RESERVE_SIZE;
if(n_bufferable < length) {
std::memcpy(reserve.data(), dst + n_bufferable - RESERVE_SIZE, RESERVE_SIZE);
return n_bufferable - RESERVE_SIZE;
} else {
std::array<char, RESERVE_SIZE> temp_buffer = {0,0,0,0};
size_t temp_size = read_count(myFile, temp_buffer.data(), RESERVE_SIZE);
std::memcpy(reserve.data(), dst + n_bufferable - (RESERVE_SIZE - temp_size), RESERVE_SIZE - temp_size);
std::memcpy(reserve.data() + RESERVE_SIZE - temp_size, temp_buffer.data(), temp_size);
return n_bufferable - (RESERVE_SIZE - temp_size);
}
} else { // length < RESERVE_SIZE
std::vector<char> temp_buffer(length, '\0');
size_t return_value = read_count(myFile, temp_buffer.data(), length);
// n_bufferable is at most RESERVE_SIZE*2 - 1 = 7
std::memcpy(dst, reserve.data(), return_value);
std::memmove(reserve.data(), reserve.data() + return_value, RESERVE_SIZE - return_value);
std::memcpy(reserve.data() + (RESERVE_SIZE - return_value), temp_buffer.data(), return_value);
return return_value;
}
}
}
// example function usage
int main() {
std::ofstream outfile("/tmp/temp.bin", std::ios::out | std::ios::binary);
std::array<char, 30> mydata = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29};
outfile.write(mydata.data(), 30);
outfile.close();
std::cout << "test1" << std::endl;
std::ifstream infile("/tmp/temp.bin", std::ios::in | std::ios::binary);
std::vector<char> buffer(100, '\0');
size_t bytes_read;
char * bd = buffer.data();
bytes_read = read_reserve(infile, bd, 3, true); data_printer("bytes read: ", bd, bytes_read); data_printer("reserve: ", reserve.data(), RESERVE_SIZE);
bytes_read = read_reserve(infile, bd, 3, false); data_printer("bytes read: ", bd, bytes_read); data_printer("reserve: ", reserve.data(), RESERVE_SIZE);
bytes_read = read_reserve(infile, bd, 5, true); data_printer("bytes read: ", bd, bytes_read); data_printer("reserve: ", reserve.data(), RESERVE_SIZE);
bytes_read = read_reserve(infile, bd, 5, false); data_printer("bytes read: ", bd, bytes_read); data_printer("reserve: ", reserve.data(), RESERVE_SIZE);
bytes_read = read_reserve(infile, bd, 100, false); data_printer("bytes read: ", bd, bytes_read); data_printer("reserve: ", reserve.data(), RESERVE_SIZE);
infile.close();
std::cout << "test2" << std::endl;
first_read = true;
std::ifstream infile2("/tmp/temp.bin", std::ios::in | std::ios::binary);
bytes_read = read_reserve(infile2, bd, 28, false); data_printer("bytes read: ", bd, bytes_read); data_printer("reserve: ", reserve.data(), RESERVE_SIZE);
bytes_read = read_reserve(infile2, bd, 3, false); data_printer("bytes read: ", bd, bytes_read); data_printer("reserve: ", reserve.data(), RESERVE_SIZE);
infile2.close();
}
// g++ -std=c++11 -O3 read_reserve.cpp -o test
</code></pre>
|
[] |
[
{
"body": "<p>In general, the code looks nice. It is structured and well-formatted.</p>\n\n<p>It is probably a bad idea to have more than 80 characters in each line, because this may happen:</p>\n\n<p><a href=\"https://i.stack.imgur.com/jqlRl.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jqlRl.png\" alt=\"line wrapping\"></a></p>\n\n<p>Also, put the body of a control statement on a separate line. For example, instead of</p>\n\n<pre><code>for(size_t i=0; i < bytes_read; i++) std::cout << (int)bd[i] << \" \";\n</code></pre>\n\n<p>do</p>\n\n<pre><code>for (size_t i=0; i < bytes_read; i++)\n std::cout << (int)bd[i] << \" \";\n</code></pre>\n\n<p>(more on this loop later.)</p>\n\n<h1>General design</h1>\n\n<p>It seems that you are using a translation unit as a \"module\" and use global <code>static</code> variables for implementation. Requiring the user to set <code>first_read</code> manually feels wrong. What you are developing is a class that wraps the functionalities.</p>\n\n<p>Also, your <code>read_reserve</code> function is way too complex. A rule of thumb is that if a function is longer than about 10 lines, it is doing too much. In your case, the <code>exact</code> parameter should be a separate function:</p>\n\n<pre><code>class Reader {\npublic:\n Reader(std::istream& i)\n :is{i}\n {\n init();\n }\n\n std::streamsize read (char* dst, std::streamsize length);\n std::streamsize read_exact(char* dst, std::streamsize length);\n\n // for the test\n void print_reserve(std::ostream& os);\n\nprivate:\n void init();\n std::streamsize read_count(char* dst, std::streamsize length);\n\n std::istream& is;\n\n static constexpr std::size_t reserve_size = 4;\n std::array<char, reserve_size> reserve{};\n};\n\nvoid Reader::init()\n{\n read_count(reserve.data(), reserve_size);\n}\n</code></pre>\n\n<p>This way, the user does not need to bother with <code>first_read</code>. They simply create a <code>Reader</code> object when they want to read something. The implementation also doesn't have to check for <code>first_read</code> each time.</p>\n\n<h1>Code</h1>\n\n<p>Now let's go through the code and figure out some possible improvements.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>#include <iostream>\n#include <array>\n#include <vector>\n#include <fstream>\n#include <cstring>\n</code></pre>\n</blockquote>\n\n<p>It is considered good practice to sort the <code>#include</code>s in alphabetical order, so that you can easily figure out whether a particular header is included. Like:</p>\n\n<pre><code>#include <array>\n#include <cstring>\n#include <fstream>\n#include <iostream>\n#include <vector>\n</code></pre>\n\n<p>In particular, you forgot <code>#include <cstddef></code> for <code>std::size_t</code>.</p>\n\n<blockquote>\n<pre><code>#define RESERVE_SIZE 4\nstatic std::array<char, RESERVE_SIZE> reserve = {0,0,0,0}; // buffer for holding bytes at end of stream\nstatic bool first_read = true; // true if first read and reserve buffer is empty\n</code></pre>\n</blockquote>\n\n<p>In C++, don't use <code>#define</code> for constants. Use <code>constexpr</code> instead.</p>\n\n<pre><code>constexpr std::size_t reserve_size = 4;\n</code></pre>\n\n<p>The initialization of <code>reserve</code> can be a simple <code>{}</code> instead of <code>= {0,0,0,0}</code>. In my opinion, that's clearer.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>// helper function to print output\nvoid data_printer(std::string msg, char * bd, size_t bytes_read) {\n std::cout << msg << bytes_read << \": \";\n for(size_t i=0; i < bytes_read; i++) std::cout << (int)bd[i] << \" \";\n std::cout << std::endl;\n}\n</code></pre>\n</blockquote>\n\n<p>Don't take <code>msg</code> by value. Take by const reference instead. Also, I don't see why <code>bd</code> is a non-const pointer. <code>size_t</code> should be <code>std::size_t</code>. Prefer <code>++i</code> over <code>i++</code>. In C++, <a href=\"https://stackoverflow.com/q/103512\">avoid C-style casts</a>. <a href=\"https://stackoverflow.com/q/213907\">Use <code>'\\n'</code> instead of <code>std::endl</code></a> when flushing is not needed. Something along the lines of:</p>\n\n<pre><code>// helper function to print output\nvoid data_printer(const std::string& msg, const char * bd, std::size_t bytes_read)\n{\n std::cout << msg << bytes_read << \": \";\n for (std::size_t i = 0; i < bytes_read; ++i)\n std::cout << static_cast<int>(bd[i]) << ' ';\n std::cout << '\\n';\n}\n</code></pre>\n\n<p>I would put a space after the <code>for</code> keyword, but that is a matter of taste, I guess.</p>\n\n<p>Also, the STL algorithms can be used here: (needs <code>#include <algorithm></code> and <code>#include <iterator></code>)</p>\n\n<pre><code>// helper function to print output\nvoid data_printer(const std::string& msg, const char* bd, std::size_t bytes_read)\n{\n std::cout << msg << bytes_read << \": \";\n std::copy_n(bd, bytes_read, std::ostream_iterator<int>{std::cout, \" \"});\n std::cout << '\\n';\n}\n</code></pre>\n\n<p>In fact, I feel that <code>msg</code> doesn't fit in here well. And it would be nice if you take a <code>std::ostream&</code> parameter instead of always outputting to <code>std::cout</code>. Also, this function may deserve an <code>inline</code>. I may write the function like this:</p>\n\n<pre><code>void print_data(std::ostream& os, const char* data, std::size_t cnt)\n{\n std::copy_n(bd, bytes_read, std::ostream_iterator<int>{std::cout, \" \"});\n}\n</code></pre>\n\n<p>and let the user handle the message and/or newline. It would be even nicer if we write an I/O manipulator so that we can use it like</p>\n\n<pre><code>std::cout << \"bytes read: \" << print_data(bd, bytes_read) << '\\n';\n</code></pre>\n\n<p>The implementation is left as an exercise to the reader. (oops)</p>\n\n<hr>\n\n<blockquote>\n<pre><code>// helper function to read and return # of bytes read\nsize_t read_count(std::ifstream & myFile, char * dst, size_t length) {\n myFile.read(dst, length);\n return myFile.gcount();\n}\n</code></pre>\n</blockquote>\n\n<p>Nice little function. Also a good candidate for <code>inline</code>. <code>myFile</code> can be any <code>std::istream</code>, not just <code>std::ifstream</code>. It may be better to use <code>std::streamsize</code> instead of <code>std::size_t</code> here:</p>\n\n<pre><code>// helper function to read and return # of bytes read\nstd::streamsize read_count(std::istream& myFile, char* dst, std::streamsize length)\n{\n myFile.read(dst, length);\n return myFile.gcount();\n}\n</code></pre>\n\n<p>Also, stream operations can be chained, but I'm not sure whether <code>return myFile.read(dst, length).gcount()</code> is more readable.</p>\n\n<hr>\n\n<p>Initialization code:</p>\n\n<blockquote>\n<pre><code>myFile.read(reserve.data(), RESERVE_SIZE);\n</code></pre>\n</blockquote>\n\n<p>As I wrote above, since you wrote <code>read_count</code>, why not use it?</p>\n\n<hr>\n\n<p>Non-exact reading code, part one:</p>\n\n<blockquote>\n<pre><code>if(length >= RESERVE_SIZE) {\n std::memcpy(dst, reserve.data(), RESERVE_SIZE);\n myFile.read(dst + RESERVE_SIZE, length - RESERVE_SIZE);\n myFile.read(reserve.data(), RESERVE_SIZE);\n if(myFile.gcount() != RESERVE_SIZE) throw std::runtime_error(\"not enough data in file :(\");\n return length;\n}\n</code></pre>\n</blockquote>\n\n<p>Here, the logic is actually simpler than it seems to be: emit the cached data, read the remaining characters and emit immediately, and then read and cache specified amount of data. It would be nice if you place a comment explaining this. Also, <code>std::copy</code> is easier to work with than <code>std::memcpy</code>, and it increments the pointer for you. (<code>std::copy</code> automatically calls <code>std::memcpy</code> for trivial types, so there is no performance quality.) And since you have written <code>read_count</code>, use it. I am starting to feel that the if statement deserves its own function:</p>\n\n<pre><code>void read_ensure(char* dest, std::streampos size)\n{\n if (read_count(dest, size) != size)\n throw std::runtime{\"not enough data in file :(\"};\n}\n</code></pre>\n\n<p>then you can use it to make the code more readable:</p>\n\n<pre><code>if (length >= reserve_size) {\n dst = std::copy(reserve.begin(), reserve.end(), dst);\n read_count(dst, length - reserve_size);\n read_ensure(reserve.data(), reserve_size);\n}\n</code></pre>\n\n<p>The return statement is common to both branches, so don't repeat it.</p>\n\n<hr>\n\n<p>Non-exact reading code, part two:</p>\n\n<blockquote>\n<pre><code>else { // RESERVE_SIZE > length\n std::memcpy(dst, reserve.data(), length);\n // since some of the reserve buffer was consumed, shift the unconsumed bytes to beginning of array\n // then read from file to fill up reserve buffer\n std::memmove(reserve.data(), reserve.data() + length, RESERVE_SIZE - length);\n myFile.read(reserve.data() + RESERVE_SIZE - length, length);\n if(myFile.gcount() != length) throw std::runtime_error(\"not enough data in file :(\");\n return length;\n}\n</code></pre>\n</blockquote>\n\n<p>We can use <code>std::copy</code> here since we know the direction: (<code>std::copy</code> is likely to call <code>std::memmove</code> internally)</p>\n\n<pre><code>else {\n std::copy(reserve.begin(), reserve.end(), dst);\n std::copy(reserve.begin() + length, reserve.end(), reserve.begin());\n read_ensure(reserve, length);\n}\n</code></pre>\n\n<hr>\n\n<p>Exact reading code, part one:</p>\n\n<blockquote>\n<pre><code>if(length >= RESERVE_SIZE) {\n // use \"dst\" as a temporary buffer, since it's already allocated\n // it is not a good idea to allocate a temp buffer of size length, as length can be large\n std::memcpy(dst, reserve.data(), RESERVE_SIZE);\n size_t n_read = read_count(myFile, dst + RESERVE_SIZE, length - RESERVE_SIZE);\n size_t n_bufferable = n_read + RESERVE_SIZE;\n if(n_bufferable < length) {\n std::memcpy(reserve.data(), dst + n_bufferable - RESERVE_SIZE, RESERVE_SIZE);\n return n_bufferable - RESERVE_SIZE;\n } else {\n std::array<char, RESERVE_SIZE> temp_buffer = {0,0,0,0};\n size_t temp_size = read_count(myFile, temp_buffer.data(), RESERVE_SIZE);\n std::memcpy(reserve.data(), dst + n_bufferable - (RESERVE_SIZE - temp_size), RESERVE_SIZE - temp_size);\n std::memcpy(reserve.data() + RESERVE_SIZE - temp_size, temp_buffer.data(), temp_size);\n return n_bufferable - (RESERVE_SIZE - temp_size);\n }\n}\n</code></pre>\n</blockquote>\n\n<p>You are actually leaking the reserved bytes. You rely on the user to not read them, but are users always careful? It may be beneficial to <code>std::fill</code> the remaining bytes to zero, but that depends on your case.</p>\n\n<hr>\n\n<p>Exact reading code, part two:</p>\n\n<blockquote>\n<pre><code>else { // length < RESERVE_SIZE\n std::vector<char> temp_buffer(length, '\\0');\n size_t return_value = read_count(myFile, temp_buffer.data(), length);\n // n_bufferable is at most RESERVE_SIZE*2 - 1 = 7\n std::memcpy(dst, reserve.data(), return_value);\n std::memmove(reserve.data(), reserve.data() + return_value, RESERVE_SIZE - return_value);\n std::memcpy(reserve.data() + (RESERVE_SIZE - return_value), temp_buffer.data(), return_value);\n return return_value;\n}\n</code></pre>\n</blockquote>\n\n<p>Well, using <code>std::vector</code> seems a little bit strange here. <code>reserve_size</code> is a small number, and since you are using it in other places, so why not use <code>std::array</code>?</p>\n\n<hr>\n\n<blockquote>\n<pre><code>// example function usage\nint main() {\n std::ofstream outfile(\"/tmp/temp.bin\", std::ios::out | std::ios::binary);\n std::array<char, 30> mydata = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29};\n outfile.write(mydata.data(), 30);\n outfile.close();\n\n std::cout << \"test1\" << std::endl;\n std::ifstream infile(\"/tmp/temp.bin\", std::ios::in | std::ios::binary);\n std::vector<char> buffer(100, '\\0');\n size_t bytes_read;\n char * bd = buffer.data();\n bytes_read = read_reserve(infile, bd, 3, true); data_printer(\"bytes read: \", bd, bytes_read); data_printer(\"reserve: \", reserve.data(), RESERVE_SIZE);\n bytes_read = read_reserve(infile, bd, 3, false); data_printer(\"bytes read: \", bd, bytes_read); data_printer(\"reserve: \", reserve.data(), RESERVE_SIZE);\n bytes_read = read_reserve(infile, bd, 5, true); data_printer(\"bytes read: \", bd, bytes_read); data_printer(\"reserve: \", reserve.data(), RESERVE_SIZE);\n bytes_read = read_reserve(infile, bd, 5, false); data_printer(\"bytes read: \", bd, bytes_read); data_printer(\"reserve: \", reserve.data(), RESERVE_SIZE);\n bytes_read = read_reserve(infile, bd, 100, false); data_printer(\"bytes read: \", bd, bytes_read); data_printer(\"reserve: \", reserve.data(), RESERVE_SIZE);\n infile.close();\n\n std::cout << \"test2\" << std::endl;\n first_read = true;\n std::ifstream infile2(\"/tmp/temp.bin\", std::ios::in | std::ios::binary);\n bytes_read = read_reserve(infile2, bd, 28, false); data_printer(\"bytes read: \", bd, bytes_read); data_printer(\"reserve: \", reserve.data(), RESERVE_SIZE);\n bytes_read = read_reserve(infile2, bd, 3, false); data_printer(\"bytes read: \", bd, bytes_read); data_printer(\"reserve: \", reserve.data(), RESERVE_SIZE);\n infile2.close();\n}\n</code></pre>\n</blockquote>\n\n<p><code>out</code> is implied for <code>std::ofstream</code>, and <code>in</code> is implied for <code>std::ifstream</code>, so omit them. Initializing <code>mydata</code> like that is no fun; <code>std::iota</code> is better. Also, it may be better to use scopes instead of manually calling <code>close</code>. The reading tests are a lot of duplicate code and may deserve a helper function. Also, the three parts can probably be extracted into their own functions. This is just a test, so it doesn't really matter too much, though.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T17:48:48.353",
"Id": "438089",
"Score": "0",
"body": "Thank you! This was more than I could have hoped for! :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T12:05:45.270",
"Id": "225580",
"ParentId": "225562",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "225580",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T06:27:25.227",
"Id": "225562",
"Score": "4",
"Tags": [
"c++",
"c++11",
"io",
"stream"
],
"Title": "Reading from a stream but reserving N bytes at the end of stream"
}
|
225562
|
<p>I created a <a href="https://github.com/Aprillion/react-auto-height" rel="nofollow noreferrer">react-auto-height</a> library:</p>
<blockquote>
<p>A React component that animates <code>height: auto</code> children when their content is changed, using CSS transitions.</p>
</blockquote>
<p>It started simple, inspired by a <a href="https://css-tricks.com/using-css-transitions-auto-dimensions/#article-header-id-5" rel="nofollow noreferrer">CSS-Tricks</a> article, but I needed to cover more edge cases, most notably to allow multiple levels of components to use <code><AutoHeight></code> without knowing about each other => handling nested elements whose <code>height</code> attribute is in transition.</p>
<p><strong>Am I using any dangerous patterns that could affect other React components unrelated to height animation?</strong> (obviously, it will affect other height animation techniques, but I want to be a "good citizen" regarting unrelated features...). If yes, please advice possible mitigation (or if you know there isn't anything I can do except document better).</p>
<p><strong>Note:</strong> I am not much concerned about security or performance - unless someone will notice I missed something important (there shouldn't be any new vulnerability that wouldn't exist otherwise + CSS transitions are already expensive, iterating over DOM children adds less than 2ms even in IE11). And I rely on manual testing of a static build of a <a href="http://peter.hozak.info/react-auto-height" rel="nofollow noreferrer">storybook</a> for now.</p>
<pre><code>import React, {memo, useEffect, useRef} from 'react'
import PropTypes from 'prop-types'
import './index.css'
const PREV_HEIGHT = 'data-react-auto-height-start-value'
const AutoHeight = ({children, className, ...props}) => {
const ref = useRef()
useEffect(() => {
const {current: el} = ref
if (!el) {
return
}
// find descendants created by nested AutoHeights and adjust future height of current element by the future heights of children
// skip for first render
let adjustBy = 0
if (el.style.height) {
el.setAttribute(PREV_HEIGHT, el.style.height)
let descendants = Array.from(el.firstChild.children)
for (let child of descendants) {
let prevHeight = child.getAttribute(PREV_HEIGHT)
if (prevHeight) {
child = child.firstChild // skip the outer wrapper
adjustBy += child.scrollHeight - parseInt(prevHeight)
}
if (child.children && child.children.length) {
Array.from(child.children).forEach(grandChild => {
if (grandChild.getAttribute) {
descendants.push(grandChild)
}
})
}
}
}
el.style.height = el.firstChild.scrollHeight + adjustBy + 'px'
})
// inner div used in el.firstChild
return (
<div ref={ref} className={`react-auto-height ${className}`} {...props}>
<div>{children}</div>
</div>
)
}
export default memo(AutoHeight)
AutoHeight.propTypes = {
children: PropTypes.node,
/** Props are propagated to the outer wrapper div - including style, className, data-test-id, ... */
'...props': PropTypes.string,
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T09:17:51.943",
"Id": "225567",
"Score": "2",
"Tags": [
"javascript",
"react.js",
"library"
],
"Title": "React-auto-height"
}
|
225567
|
<p>I have a bunch of voxel having an int value inside a 16^3 grid. I want to merge individual voxels with the same int value together in order to create the least possible amount of boxes the fastest way possible.</p>
<p>Here is my algorithm (kotlin) :</p>
<pre><code>
fun convert (grid: VoxelGrid): List<Box> {
val dim = grid.dimension
val boxes = mutableListOf<Box>()
for (width in dim - 1 downTo 1) {
for (height in dim - 1 downTo 1) {
for (depth in dim - 1 downTo 1) {
val dims = Vec3(width, height, depth)
for (x in 0 until (dim - width)) {
for (y in 0 until (dim - height)) {
for (z in 0 until (dim - depth)) {
val min = Vec3(x, y, z)
val box = Box(min, min + (dims))
if (!contains(boxes, box)) {
val voxels = box.voxels()
val first = voxels[0]
val value = grid[first.x, first.y, first.z]
if (value != 0 && voxels.all {
grid[it.x, it.y, it.z] == value
}) {
boxes.add(box)
}
}
}
}
}
}
}
}
return boxes
}
private fun contains(boxes: MutableList<Box>, other: Box): Boolean {
for (existing in boxes) {
if (existing.intersects(other)) {
return true
}
}
return false
}
</code></pre>
<p><a href="https://gist.github.com/vinz243/3b9e48f7f27f068573bbeff1326a4446" rel="nofollow noreferrer">Here is a link to the helper classes</a></p>
<p>This works, but for a 16^3 grid (the last test case) it takes around 8s to complete which is way too long. </p>
<p>In order to optimize, I think that before calling convert(), I could group every voxel by their int value, then compute the AABB for each group and only call the algorithm for each AABB. This could work pretty well but for values that are spread out around the original grid.</p>
<p>Is there any other way to optimize this?</p>
|
[] |
[
{
"body": "<p>Try to determine the complexity of the algorithms you are implementing. The code you wrote above has a complexity of O(N⁹), where N is equal to <code>grid.dimension</code>. This is because you have 6 nested for loops, and then <code>voxels.all{}</code> which itself also has to loop over all three dimensions of the box <code>voxels</code>.</p>\n\n<p>Grouping voxels by their int value is a good idea. You correctly worry about the case of voxels with the same value being spread out. The solution to that is to divide the box into <em>connected</em> voxels with the same int value. For example, if you had only one dimension, then if you have the values <code>[0, 1, 2, 2, 1, 2]</code>, then you would divide this into 5 groups: <code>[0]</code>, <code>[1]</code>, <code>[2, 2]</code>, <code>[1]</code> and <code>[2]</code>. It should be possible to do this in O(N³) time.</p>\n\n<p>Now that you have a set of smaller shapes, the function that decomposes those shapes into boxes should run a lot faster. The question is now whether you want to have that function as fast as possible, or as accurate as possible. The function as you wrote does not necessarily result in the least amount of boxes. Apart from the fact that it doesn't actually try out boxes in a strict order from largest to smallest, even trying the largest boxes first won't necessarily result in the least amount of boxes being produced. Take for example this 2D array:</p>\n\n<pre><code>1 0 0 1\n1 1 1 1\n1 0 0 1\n</code></pre>\n\n<p>The voxels with value <code>1</code> form a H-shape. If you remove the largest possible box, you end up with:</p>\n\n<pre><code>1 0 0 1\nx x x x\n1 0 0 1\n</code></pre>\n\n<p>Now you are left with 4 1x1 boxes, so in total this will result in 5 boxes for the H-shape. If instead you would start by taking out the left and right side, you are left with the middle bar, resulting in just 3 boxes. Finding the solution with the least amount of boxes is actually an NP-complete problem, and an algorithm that would produce that solution would take even longer to run that yours. Given that your algorithm already does not give acceptable performance, you should instead focus on implementing the fastest algorithm that produces acceptable results.</p>\n\n<p>The common approach is to start by finding strips of adjacent voxels in the x-direction. Then try to find adjacent strips with the same size and x-position in the y-direction, and merge them into squares. Finally do the same in the z-direction and merge adjacent squares into boxes. This should be O(N³) as well. If you know that some shapes are more common than others, you could tweak this algorithm to reduce the number of boxes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T07:22:47.720",
"Id": "438160",
"Score": "0",
"body": "Thank you for your detailed answer. I didn't do any studies, so the O(N) notation and all the complexity theory seems quite O(N^N) to me. \" Apart from the fact that it doesn't actually try out boxes in a strict order from largest to smallest\" how so ? I am iterating in the reverse order to test each boxes dimensions, am I missing something ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T07:25:31.927",
"Id": "438161",
"Score": "0",
"body": "So I should do a graph where each node represents a voxel and each vertex a connection between two voxels of the same value. Your strip algorithm seems interesting, although it really comes down to the actual shape of the voxels. Anyway, I was thinking about using several algorithm optimized for a specific shape and then try the slow generic approach (original algorithm) if the other results do not meet a threshold"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T19:18:03.653",
"Id": "438254",
"Score": "0",
"body": "About the order of largest to smallest: suppose `dim` is 10, then your outer three loops will try out a box of size (9, 9, 1) before one of size (9, 8, 9)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T18:46:43.560",
"Id": "225599",
"ParentId": "225569",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T09:43:49.447",
"Id": "225569",
"Score": "4",
"Tags": [
"kotlin"
],
"Title": "Optimizing voxel merge algorithm"
}
|
225569
|
<p>The code below simulates a given Newtonian 3 body system. Each row per slice is supposed to represent a Cartesian component for the initial trajectory vector and for the distance vectors to the other two objects. </p>
<p>What are some possible improvements to this? For instance is there any benefit to implement something to cut the redundancy with the duplicate distance vectors? How about using something like NumPy instead of vanilla?</p>
<pre><code># GRAV_MASS_CONSTANT = 1
# masses = [1, 1, 1]
def updated_trajectory_component(row):
# a = masses * GRAV_MASS_CONSTANT
a = 1
return row[0] + sum([a / i for i in row[1:]])
def updated_distance_component(row):
return [i - row[0] for i in row[1:]]
def iterate_row(row):
dist = updated_distance_component(row)
return [updated_trajectory_component(row)] + dist
def iterate_slice(slice):
return [iterate_row(i) for i in slice]
def iterate_cube(cube):
return [iterate_slice(i) for i in cube]
def num_iter(cube, iter):
print(cube)
if iter == 1: return iterate_cube(cube)
else: return num_iter(iterate_cube(cube), iter - 1)
cube = [
[
[0, 0.1, 1],
[0, 1, 0.1],
[0, 1, 1]
],
[
[0, 0.1, 1],
[0, -1, 1],
[0, -1, 0.1]
],
[
[0, -1, -1],
[0, 0.1, -1],
[0, -1, 0.1]
]
]
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><strong>Docstrings</strong>: You should include a <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\"><code>docstring</code></a> at the beginning of every method, class, and module you write. This will allow documentation to identify what your program is supposed to do.</li>\n<li><strong>Constants Naming</strong>: Any constants that you have in your program (eg. <code>cube</code>) should be in UPPERCASE, like so: <code>CUBE</code>.</li>\n<li><strong>Main Guard</strong>: Any code that isn't inside a method/class should be inside an <code>if __name__ == '__main__'</code> guard. This will prevent this code from being executed if you decide to import this module from other programs. <a href=\"https://stackoverflow.com/a/419185/8968906\">This StackOverflow answer</a> provides more insight and explanation.</li>\n<li><strong>Unnecessary if/else with returns</strong>: It is unnecessary to have an <code>else</code> after an <code>if</code>, if you return something in the <code>if</code>. Simply put the <code>else</code> return statement outside the <code>if</code> statement. This return will be run if the <code>if</code> evaluates to be <code>False</code>, which removes the necessity for the <code>else</code> statement.</li>\n<li><strong>Reserved Names</strong>: You shouldn't use reserved names for variable names, such as <code>iter</code> and <code>slice</code>, to avoid confusion.</li>\n<li><strong>Variable/Parameter Naming</strong>: You have a parameter named <code>iter</code> which you use as the number of times you iterate over the cube. It took a bit to identify this, as I see <code>iter</code> as an <em>iterator</em>, not the number of times you iterate. Renaming it <code>iterations</code> makes it clearer about what that parameter is supposed to be.</li>\n</ul>\n\n<p><strong><em>Updated Code</em></strong></p>\n\n<pre><code>\"\"\"\nModule Docstring\nA description of your program goes here\n\"\"\"\n\ndef updated_trajectory_component(row):\n \"\"\"\n Updated the trajectory component of the passed row\n\n :param row: Row to be updated\n\n \"\"\"\n num = 1\n return row[0] + sum([num / i for i in row[1:]])\n\ndef updated_distance_component(row):\n \"\"\"\n Updated the distance component of the passed row\n\n :param row: Row to be updated\n\n \"\"\"\n return [i - row[0] for i in row[1:]]\n\n\ndef iterate_row(row):\n \"\"\"\n Iterates over the passed row\n\n :param row: Row to be iterated\n\n \"\"\"\n dist = updated_distance_component(row)\n return [updated_trajectory_component(row)] + dist\n\n\ndef iterate_slice(_slice):\n \"\"\"\n Iterates over the rows in the passed slice\n\n :param _slice: Slice to be iterated over\n\n \"\"\"\n return [iterate_row(i) for i in _slice]\n\n\ndef iterate_cube(cube):\n \"\"\"\n Iterates over the slices in the passed cube\n\n :param cube: Cube to be iterated over\n\n \"\"\"\n return [iterate_slice(i) for i in cube]\n\ndef num_iterator(cube, iterations):\n \"\"\"\n Recursive iterator, iterates over the cube `iterations` times\n\n :param cube: Cube to iterate\n :param iterations: Number of times to iterate\n \"\"\"\n print(cube)\n if iterations == 1:\n return iterate_cube(cube)\n return num_iterator(iterate_cube(cube), iterations - 1)\n\n\nif __name__ == '__main__':\n CUBE = [\n [\n [0, 0.1, 1],\n [0, 1, 0.1],\n [0, 1, 1]\n ],\n [\n [0, 0.1, 1],\n [0, -1, 1],\n [0, -1, 0.1]\n ],\n [\n [0, -1, -1],\n [0, 0.1, -1],\n [0, -1, 0.1]\n ]\n ]\n\n #Sample Cases\n num_iterator(CUBE, 5)\n num_iterator(CUBE, 2)\n num_iterator(CUBE, 7)\n num_iterator(CUBE, 4)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T18:39:42.343",
"Id": "225785",
"ParentId": "225574",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T10:32:51.987",
"Id": "225574",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"simulation",
"physics"
],
"Title": "Simplified three-body simulation"
}
|
225574
|
<p>Below is an implementation of a React app printing list. Are there any areas of improvement/suggestions in below code base</p>
<pre><code> class ListElement extends React.PureComponent {
render() {
return <li onClick={() => this.props.handleClick(this.props.index)}>{this.props.item.text}</li>;
}
}
class ListComponent extends React.Component {
handleClick(index) {
this.props.onClick(index);
}
render() {
const listDetails = this.props.listDetails;
let height,width;
if (listDetails.hasOwnProperty("size")) {
height = listDetails.size.height;
width = listDetails.size.width;
}
return (
<ul style={{ height: height, width }}>
{this.props.items.map((item, i) => <ListElement item={item} key={i} index={i} handleClick={this.handleClick.bind(this)}/>)}
</ul>
);
}
}
ListComponent.propTypes = {
items: PropTypes.arrayOf(PropTypes.shape({
text: PropTypes.string.isRequired
})).isRequired,
listDetails: PropTypes.object.isRequired
};
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>Use function syntax/<a href=\"https://reactjs.org/docs/react-api.html#reactmemo\" rel=\"nofollow noreferrer\">memo</a> when possible</li>\n<li>Use destructuring</li>\n<li>Use object literal shorthand</li>\n<li>Define defaults for <code>width</code> and <code>height</code></li>\n<li><code>handleClick</code> is just <code>onClick</code> renamed</li>\n<li>Use tooling for formatting your code (eslint, prettier)</li>\n<li>Prefer ternary over if (not always true)</li>\n<li>Have a well defined API for your components (ListElement needs text, not the entire item, and doesn't really need index)</li>\n</ul>\n\n<pre class=\"lang-js prettyprint-override\"><code>const ListElement = React.Memo(({ handleClick, label }) => (\n <li onClick={handleClick()}>{label}</li>\n));\n\nconst ListComponent = React.Memo(\n ({\n items,\n listDetails: {\n size: { height, width }\n },\n onClick\n }) => (\n <ul style={{ height, width }}>\n {items.map(({ text }, i) => (\n <ListElement label={text} key={i} handleClick={() => onClick(i)} />\n ))}\n </ul>\n )\n);\n\nListComponent.propTypes = {\n items: PropTypes.arrayOf(\n PropTypes.shape({\n text: PropTypes.string.isRequired\n })\n ).isRequired,\n listDetails: PropTypes.object.isRequired\n};\n\n// Not quite sure I'm setting defaultProps correctly here, but you get the idea\nListComponent.defaultProps = {\n listDetails: { size: { height: DEFAULT_HEIGHT, width: DEFAULT_WIDTH } }\n};\n</code></pre>\n\n<p>You can also update <code>propTypes</code> with the shape of <code>listDetails</code> or change so that <code>ListComponent</code> takes <code>size</code> as an attribute instead, depending on what makes sense in your scenario.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T17:13:33.357",
"Id": "225594",
"ParentId": "225582",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "225594",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T12:52:29.127",
"Id": "225582",
"Score": "3",
"Tags": [
"react.js",
"jsx"
],
"Title": "Code for printing list in React"
}
|
225582
|
<p>I have the following code, which basically load some data files that I have in different folders, take an average of every repeat at each Temperature and then plot the results. The code works fine, and it was OK when I had only a couple of set of data. But now I have 9 different set of temperature each with 5 repeat each and the code is becoming too long in my opinion. Is there a way to consolidate it and make it more readable and efficient? </p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
steps = np.loadtxt('/home/aperego/data/HexaPaper/nvt/303K/1st/Average_MSD.txt',usecols=[0])
def load(temp,pos):
return np.loadtxt('/home/aperego/data/HexaPaper/nvt/'+temp+'K/'+pos+'/Average_MSD.txt',usecols=[1])
# T = 303 K
msd303_1 = load('303','1st')
msd303_2 = load('303','2nd')
msd303_3 = load('303','3rd')
msd303_4 = load('303','4th')
msd303_5 = load('303','5th')
msd303 = np.vstack((msd303_1,msd303_2,msd303_3,msd303_4,msd303_5)).T
msd303_mean = np.mean(msd303,axis=1)
msd303_std = np.std(msd303,axis=1)
# T = 313 K
msd313_1 = load('313','1st')
msd313_2 = load('313','2nd')
msd313_3 = load('313','3rd')
msd313_4 = load('313','4th')
msd313_5 = load('313','5th')
msd313 = np.vstack((msd313_1,msd313_2,msd313_3,msd313_4,msd313_5)).T
msd313_mean = np.mean(msd313,axis=1)
msd313_std = np.std(msd313,axis=1)
# T = 323 K
msd323_1 = load('323','1st')
msd323_2 = load('323','2nd')
msd323_3 = load('323','3rd')
msd323_4 = load('323','4th')
msd323_5 = load('323','5th')
msd323 = np.vstack((msd323_1,msd323_2,msd323_3,msd323_4,msd323_5)).T
msd323_mean = np.mean(msd323,axis=1)
msd323_std = np.std(msd323,axis=1)
plt.yscale("log")
plt.xscale("log")
plt.plot(steps,msd303_mean,label ='303K')
plt.plot(steps,msd313_mean,label ='313K')
plt.plot(steps,msd323_mean,label ='323K')
plt.legend(loc="best")
plt.show()
</code></pre>
|
[] |
[
{
"body": "<p>You are right to question your current approach. With 9 sets of data with 5 repeats of each, you would need 45 variables with your current approach. Using a list or dictionary for one dimension would reduce you to only 5 or 9 variables depending on which dimension became the list/dictionary. Use a list/dictionary of lists/dictionaries could reduce the required variables to 1.</p>\n\n<p>Using <code>'/long/path/'+var1+'suffix/'+var2+'/filename.ext'</code> is hard to read. First, the PEP8 standard requires spaces around the <code>+</code> operators (as well as other places, such as after commas). Using a <code>.format()</code> statement can make the string manipulation a bit clearer, and allow configuration to be move out of functions to a global scope, making changes easier.</p>\n\n<p>Whether you want lists or dictionaries for the data, whether you want to store the individual <code>msd[temperature][repeat]</code> for later use or whether you just need to read the data in to compute the mean & standard deviation and can then discard the data, and so on is unclear. Here (untested) is a rough reworking of your code to allow you to extend the temperatures and repeats as required; adapt as necessary. The <code>msd</code> variable is a dictionary of lists, so the variable <code>msd323_5</code> has become <code>msd[323][4]</code>.</p>\n\n<pre><code>import numpy as np \nimport matplotlib.pyplot as plt\n\n\n# Configuration\n\nFILENAME = '/home/aperego/data/HexaPaper/nvt/{}K/{}/Average_MSD.txt'\nREPEATS = ('1st', '2nd', '3rd', '4th', '5th')\nTEMPERATURES = (303, 313, 323)\n\n\n# Read data\n\ndef load(temp, pos):\n return np.loadtxt(FILENAME.format(temp, pos), usecols=[1])\n\nsteps = np.loadtxt(FILENAME.format(TEMPERATURES[0], REPEATS[0]), usecols=[0])\n\nmsd = {}\nmsd_mean = {}\nmsd_std = {}\n\nfor temperature in TEMPERATURES:\n\n repeats = []\n\n for repeat in REPEATS:\n\n sample = load(temperature, repeat)\n repeats.append(sample)\n\n data = np.vstack(repeats).T\n\n msd[temperature] = data\n msd_mean[temperature] = np.mean(data, axis=1)\n msd_std[temperature] = np.std(data, axis=1)\n\n\n# Plot the data\n\nplt.yscale(\"log\")\nplt.xscale(\"log\")\n\nfor temperature in TEMPERATURES:\n plt.plot(steps, msd_mean[temperature], label=\"{}K\".format(temperature))\n\nplt.legend(loc=\"best\")\nplt.show()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T16:48:58.570",
"Id": "438080",
"Score": "0",
"body": "Thank you, it works beautifully! Is there away using this current setup to keep the data labels so I can have a legend on the plot?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T16:54:13.743",
"Id": "438081",
"Score": "0",
"body": "I didn't see any code to generate plot labels (or even a `plt.show()` to display the resulting plot.). Without sample data, it is difficult to see/guess what \"data labels\" were that you want to keep."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T17:02:13.230",
"Id": "438084",
"Score": "0",
"body": "Perhaps `plt.plot(steps, msd_mean[temperature], label=\"{}K\".format(temperature))` maybe?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T17:02:40.410",
"Id": "438086",
"Score": "0",
"body": "I am sorry, I modified the plotting part of the code to show the labels"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T16:41:31.880",
"Id": "225591",
"ParentId": "225586",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "225591",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T14:50:00.240",
"Id": "225586",
"Score": "4",
"Tags": [
"python",
"performance"
],
"Title": "Load multiple text files with same name but in different folders"
}
|
225586
|
<p>I have below working code which works fine, but just looking way around if there is an another elegant way of doing this, because here i'm using else condition to print the last line or dataBlock to be printed.</p>
<p>Note: <code>mydudalt1</code> and <code>mydudalt2</code> are the host names</p>
<h2>My data File:</h2>
<pre><code>$ cat mydata_test.txt
-- mydudalt1 --
192.168.2.40; // udalt-sanjose
192.168.2.56; // udalt-sj1
192.168.98.71; // udalt-japan
192.168.2.146; //udalt-sj-fwd1
-- mydudalt2 --
199.43.4.70; // udalt-chelms
192.168.2.56; // udalt-sj1
192.168.98.71; // udalt-japan
</code></pre>
<h2>My Working code:</h2>
<pre><code>#!/grid/common/pkgs/python/v3.6.1/bin/python3
dataBlock = ''
with open('mydata_test.txt', 'r') as frb:
for line in frb:
line = line.strip("\n")
if line.startswith('--'):
if "japan" in dataBlock:
print(dataBlock)
dataBlock = ''
dataBlock = dataBlock + line
elif "japan" in line:
dataBlock = dataBlock + line
else:
print(dataBlock + line)
</code></pre>
<h2>Resulted Output:</h2>
<pre><code>-- mydudalt1 -- 192.168.98.71; // udalt-japan
-- mydudalt2 -- 192.168.98.71; // udalt-japan
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T17:01:07.707",
"Id": "438083",
"Score": "0",
"body": "Can `mydudalt` blocks have more than one JAPAN Ids in them?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T17:02:29.547",
"Id": "438085",
"Score": "0",
"body": "@kushj, no. `mydudalt1 ` and `mydudalt2` are the host names."
}
] |
[
{
"body": "<p>Unless there is an indentation issue, </p>\n\n<pre><code> dataBlock = ''\n dataBlock = dataBlock + line\n</code></pre>\n\n<p>can be written:</p>\n\n<pre><code> dataBlock = line\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T03:15:28.753",
"Id": "438141",
"Score": "0",
"body": "Josay, that will not do the job because if i will use `dataBlock = line` instead of `dataBlock = dataBlock + line` then it will not print host names. +1 for the throwing an idea"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T16:59:17.913",
"Id": "225593",
"ParentId": "225592",
"Score": "1"
}
},
{
"body": "<p>A quick Answer [Should not be used in PRODUCTION]</p>\n\n<p>I mainly try to answer your concern over how to avoid \"for-else\" to handle last edge case, and haven't reviewed much of rest of code.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>#!/grid/common/pkgs/python/v3.6.1/bin/python3\n\nblock_start_identifier = \"--\"\nsearch_word = \"japan\"\n\ndata_block = []\nblock_satisfied = False\n\nwith open('mydata_test.txt', 'r') as frb:\n\n for line in frb.readlines():\n\n if line.startswith(block_start_identifier):\n\n # Print previous blocks\n if block_satisfied:\n print(\"\".join(data_block))\n\n # Reset data blocks\n data_block = []\n block_satisfied = False\n\n data_block.append(line)\n\n elif search_word in line:\n data_block.append(line)\n block_satisfied = True\n\n# Flush the block again as needed to handle last case\nif block_satisfied:\n print(\"\".join(data_block))\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T03:14:00.253",
"Id": "438139",
"Score": "0",
"body": "kushj, thnx for the answer. +1 for the approach around."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T17:27:55.117",
"Id": "225595",
"ParentId": "225592",
"Score": "1"
}
},
{
"body": "<p>If <code>\"japan\"</code> only appears once in each section, you can store the <code>startswith</code> line, and simply print out the desired output immediately when the matching line is found:</p>\n\n<pre><code>for line in frb:\n line = line.strip(\"\\n\")\n\n if line.startswith(\"--\"):\n prefix = line\n if \"japan\" in line:\n print(prefix + line)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T03:14:31.960",
"Id": "438140",
"Score": "0",
"body": "AJNeufeld, this looks to be neat and promising +1, thnx"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T01:31:49.337",
"Id": "225628",
"ParentId": "225592",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "225628",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T16:55:02.317",
"Id": "225592",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"linux"
],
"Title": "Python startswith and then look a word in a conditional block"
}
|
225592
|
<p><strong>MemoryCache.cs</strong></p>
<pre><code>public class MemoryCache<TKey, TValue>
{
private static readonly object Lock = new object();
private static readonly IDictionary<TKey, TValue> Cache = new ConcurrentDictionary<TKey, TValue>();
/// <summary>
/// Function for setting the cache's value when the key isn't found.
/// </summary>
public Func<TKey, TValue> Set { get; set; }
/// <summary>
/// Retrieves the value marked by the indicated key in a thread-safe way.
/// If the item is not found, uses Set to retrieve it and store it in the cache before returning the value.
/// </summary>
public TValue Get(TKey key)
{
lock (Lock)
{
if (Cache.TryGetValue(key, out var value) == false)
{
value = Set(key);
Cache.Add(key, value);
}
return value;
}
}
/// <summary>
/// Clears all values in the cache.
/// </summary>
public void Clear()
{
lock (Lock)
{
Cache.Clear();
}
}
}
</code></pre>
<p><strong>Usage</strong></p>
<p><code>Set</code> is being used to retrieve the customer information from the database via stored procedure. <code>GetBasicCustomer</code> is a service/repository function for retrieving a customer by <code>customerId</code> or <code>sapCustomerId</code>.</p>
<pre><code>public class CustomerService : ICustomerService
{
private static readonly MemoryCache<Tuple<int?, string>, Customer> CustomerCache = new MemoryCache<Tuple<int?, string>, Customer>()
{
Set = (Tuple<int?, string> key) =>
{
var ds = Database.ExecuteStoredProcedure("EXEC usp_Experiment_BasicCustomerInformation @CustomerID, @SAPCustomerID", key.Item1, key.Item2);
if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
{
return null;
}
var dr = ds.Tables[0].Rows[0];
return new Customer(
id: dr.Field<int>("CustomerID"),
sapCustomerId: dr.Field<string>("SAPCustomerID"),
companyName: dr.Field<string>("CompanyName"),
isSbtCustomer: dr.Field<bool>("IsSBTCustomer")
);
}
};
/// <summary>
/// Retrieves the customer's basic information given CustomerID or SAPCustomerID (only one is required, make the other null).
/// </summary>
public Customer GetBasicCustomer(int? customerId, string sapCustomerId)
{
var key = new Tuple<int?, string>(customerId, sapCustomerId);
return CustomerCache.Get(key);
}
}
public CustomerController()
{
public ActionResult Index(int? customerId, string sapCustomerId)
{
var customerInfo = CustomerService.GetBasicCustomer(customerId, sapCustomerId);
return View(customerInfo);
}
}
</code></pre>
<p><strong>Concerns</strong></p>
<ul>
<li>I was thinking <code>Set</code> should maybe be named <code>FindAndSet</code> or something like that, but not really sure. I like the aesthetic of <code>Get</code>/<code>Set</code>.</li>
<li>Is <code>ConcurrentDictionary</code> necessary to be thread-safe since I'm using a <code>lock</code>? Is it doing anything for me?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T19:26:03.410",
"Id": "438092",
"Score": "1",
"body": "I'm confused. I only want the `MemoryCache` class reviewed, I added usage for context, the thing you voted I lacked. So if you could comment and let me know what I'm lacking, that'd be appreciated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T20:00:08.547",
"Id": "438098",
"Score": "1",
"body": "I didn't downvote but you know ConcurrentDictionary is already thread safe and you can just use GetOrAdd that takes a func. Having the lock seems overkill. I don't know if I would call it memorycache since MS already has a class called that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T20:24:19.893",
"Id": "438100",
"Score": "0",
"body": "You show how the cache is created from some query, but not how you would use that cache. Hence, your question seems to lack context to be on-topic for this site."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T20:30:34.333",
"Id": "438103",
"Score": "1",
"body": "@dfhwze I'm a bit thrown off by that, because it's a cache, the only context you should need is retrieving from it and setting it. Anything past that is specific to the application you're using the cache in."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T20:31:22.317",
"Id": "438104",
"Score": "0",
"body": "@CharlesNRice I was not aware of that, that does seem like overkill. I also was not aware there was a class already named MemoryCache."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T20:31:47.283",
"Id": "438105",
"Score": "0",
"body": "That's exactly what we are looking for, how you would use that cache. Part of a review might be to challenge your implementation against your use case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T20:41:12.737",
"Id": "438107",
"Score": "1",
"body": "Note that `ConcurrentDictionart'2.GetOrAdd` has different semantics to the `Get` here: the OP will call `Set` exactly once, so though it may simplify the implementation, `GetOrAdd` will still need wrapping if this behaviour is desirable."
}
] |
[
{
"body": "<p>Generally, the code is simple and easy to understand.</p>\n\n<h2>Concurrency</h2>\n\n<p>It's good that you have a dedicated <code>Lock</code> object. You might consider a more expressive name, but in this case I think you can get away with it.</p>\n\n<p>As you have noticed, using the <code>lock</code> means you gain nothing from the <code>ConcurrentDictionary'2</code>. Since this is such a simple interface, I would keep the <code>lock</code> and ditch the <code>ConcurrentDictionary</code> unless you have a serious (and measurable) performance concern.</p>\n\n<p>However, you should be aware that by locking while you call <code>Set</code>, you are blocking access while you wait for an operation to complete, the length of which you cannot know. Addressing this without changing the class' behaviour would be non-trivial, primarily because it would complicate the case where <code>Set</code> fails, but may be necessary if <code>Set</code> is slow or needs access to the cache itself. If you don't care how many times you call <code>Set</code>, you could just use <code>ConcurrentDictionary.GetOrAdd</code> as mentioned by CharlesNRice in a comment, which would simply things somewhat.</p>\n\n<h2>Other</h2>\n\n<ul>\n<li><p>It's good that you have provided some level of inline documentation. I would be inclined to add an explanation of the threading behaviour (e.g. blocks while calling <code>Set</code>, will only call <code>Set</code> once). \"a thread-safe way\" is pretty meaningless: it's much better to explain the guarantees you will make.</p></li>\n<li><p>Do you anticipate needing to change <code>Set</code>? If not, you should consider making it readonly and assign it in a constructor. There is a design concern that changing <code>Set</code> means you can't know which version was used by any call to <code>Get</code> from another thread.</p></li>\n<li><p>Using a <code>Tuple<int?, string></code> as a union doesn't seem a great idea. Either implement a sound union as a class of struct, or consider having a separate cache for each. If you do wish to keep this API, you should enforce the assumption that exactly one of them is <code>null</code> by explicitly checking and throwing if this is not the case, since it represents an error on the part of the caller, and telling them them sooner rather than later will save them lots of misery and time spent debugging.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T12:23:39.070",
"Id": "438191",
"Score": "0",
"body": "Thanks, I hadn't thought about making `Set` readonly. Definitely a good point about \"a thread-safe way\" being meaningless. The last bullet has already been fixed, noticed yesterday after posting that I wasn't even using the string portion, so I removed it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T22:38:07.793",
"Id": "225617",
"ParentId": "225600",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "225617",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T19:07:07.890",
"Id": "225600",
"Score": "2",
"Tags": [
"c#",
"reinventing-the-wheel",
"thread-safety",
"cache"
],
"Title": "Simple, flexible, and thread-safe key/value memory cache"
}
|
225600
|
<p>This is a follow-up from my previous <a href="https://codereview.stackexchange.com/questions/225526/doubly-linked-list-in-cython">question</a>.
In summary, I am trying to implement a <a href="https://en.wikipedia.org/wiki/Bounding_volume_hierarchy" rel="nofollow noreferrer">BVH</a> module with Cython and need a way to keep track of the volumes during the construction of the hierarchy.</p>
<p>I was going to use a Doubly linked list for that purpose as it allows for efficiently inserting and popping items from either side, but a user pointed that many APIs use a circular version of the list to avoid problems.</p>
<p>I decided to implement such a list, also tried to make it more general so it can be useful for further projects.</p>
<pre><code>
cdef struct CDLinkedList:
ListNode* head
int length
cdef struct ListNode:
ListNode** links #[0] = previous, [1] = next or vice versa, doesn't matter.
void* data
cdef ListNode* list_node_create(void* data) nogil:
cdef ListNode* n = <ListNode *> malloc(sizeof(ListNode))
n.links = <ListNode **> malloc(sizeof(ListNode*) * 2)
n.data = data
return n
cdef void list_node_free(ListNode* node) nogil:
free(node.links)
free(node)
cdef CDLinkedList* list_create() nogil:
cdef CDLinkedList* lst = <CDLinkedList *> malloc(sizeof(CDLinkedList))
lst.head = list_node_create(NULL)
lst.head.links[0] = lst.head
lst.head.links[1] = lst.head
lst.length = 0
return lst
cdef void list_free(CDLinkedList* lst) nogil:
while lst.length > 0:
list_pop(lst, 0)
list_node_free(lst.head)
free(lst)
cdef void list_insert(CDLinkedList* lst, void* data, int link_side) nogil:
cdef:
int next = link_side
int prev = 1 - link_side
ListNode* next_node = lst.head.links[next]
ListNode* new_node = list_node_create(data)
next_node.links[prev] = new_node
lst.head.links[next] = new_node
new_node.links[prev] = lst.head
new_node.links[next] = next_node
lst.length += 1
cdef void* list_pop(CDLinkedList* lst, int link_side) nogil:
if lst.length <= 0:
return NULL
cdef:
int next = link_side
int prev = 1 - link_side
ListNode* next_node = lst.head.links[next]
ListNode* next_next_node = next_node.links[next]
void* data = next_node.data
lst.head.links[next] = next_next_node
next_next_node.links[prev] = lst.head
list_node_free(next_node)
lst.length -= 1
return data
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T20:28:55.890",
"Id": "438102",
"Score": "1",
"body": "What an interesting coincidence: I just answered this one (circular singly linked list in Java): https://codereview.stackexchange.com/questions/133210/circular-singly-linked-list-using-java. I might have a look at your question later."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T19:43:30.747",
"Id": "225602",
"Score": "3",
"Tags": [
"python",
"linked-list",
"reinventing-the-wheel",
"cython"
],
"Title": "Circular doubly linked list implementation in Cython"
}
|
225602
|
<p>How can I improve the date format function. I have written in javascript (ES5/ES6)? This code is just a part of an exercise.</p>
<pre><code>function formatDate() {
let bookingDate = new Date();
let dayNumber = bookingDate.getDay();
let date = bookingDate.getDate();
let month = bookingDate.getMonth();
let year = bookingDate.getFullYear();
return ` ${getWeekday(dayNumber)}, ${monthName(
month
)} ${date}, ${year}`;
function getWeekday(dayNumber) {
let day = bookingDate.getDay();
let DayName = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
];
return DayName[dayNumber];
}
function monthName(month) {
let monthNames = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
];
return monthNames[month];
}
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>Why are you getting <code>day</code> in function <code>getWeekday</code> and never using it?</li>\n<li><p>Use a IIF (Immediately Invoked Function) to close over constants so they do not need to be created each time you call the function that uses them (Note optimizer will cache such constants, though not on the first pass)</p></li>\n<li><p>Don't add unneeded details to names. <code>booking</code> is unrelated to the functions role, and should not be part of the name.\nYou have added complexity where not needed. </p>\n\n<ul>\n<li>The functions <code>getWeekday</code> and <code>monthName</code> are just array look ups and can be done directly via the index you pass the functions.</li>\n<li>Almost all the variables you use are once off uses, you can side step the source and execution overhead by referencing the data directly.</li>\n</ul></li>\n<li><p>Be consistent in naming <code>getWeekday</code> and <code>monthName</code> do about the same thing yet the names are completely different. <code>dayName</code> and <code>monthName</code> would be more consistent.</p></li>\n<li><p>Use constants for variables that do not change.</p></li>\n</ul>\n\n<h2>Example 1</h2>\n\n<p>Use an IIF to define constants and returns a function that formats the date.\nAdded date as an argument that defaults to <code>new Date</code></p>\n\n<p>Rather than creating an array by hand I use a short cut to convert a delimited string to an array. I find this easier to create string arrays this way.</p>\n\n<pre><code>const formatDate = (() => {\n const DAYS = \"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday\".split(\",\");\n const MONTHS = \"January,February,March,April,May,June,July,August,September,October,November,December\".split(\",\");\n return (date = new Date()) => ` ${DAYS[date.getDay()]}, ${MONTHS[date.getMonth()]} ${date.getDate()}, ${date.getFullYear()}`;\n})();\n</code></pre>\n\n<h2>Example 2</h2>\n\n<p>Keeping to your original logic and layout, but behind an IIF. Note all the constants.</p>\n\n<pre><code>const formatNow = (() => {\n const DAYS = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"];\n const MONTHS = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"];\n const dayName = idx => DAYS[idx];\n const monthName = idx => MONTHS[idx];\n function format() {\n const now = new Date();\n const day = now.getDay();\n const date = now.getDate();\n const month = now.getMonth();\n const year = now.getFullYear();\n return ` ${dayName(day)}, ${monthName(month)} ${date}, ${year}`;\n }\n return format;\n})();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T06:58:48.293",
"Id": "438330",
"Score": "0",
"body": "Thanks for the response . Your solution is neat . There is one type at the beginning of arrow function. you have used { } instead of ( )."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T14:01:09.043",
"Id": "438387",
"Score": "1",
"body": "@RahulDhingra Oh sorry my bad will fix it now."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T10:37:44.973",
"Id": "225641",
"ParentId": "225604",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "225641",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T19:44:41.210",
"Id": "225604",
"Score": "3",
"Tags": [
"javascript",
"datetime",
"formatting"
],
"Title": "Date format function in JavaScript"
}
|
225604
|
<p><strong>Problem Statement</strong></p>
<pre class="lang-xml prettyprint-override"><code>Given the root of a binary tree, return a deepest node.
For example, in the following tree, return d.
a
/ \
b c
/
d
</code></pre>
<p><strong>My Implementation</strong></p>
<pre><code>module.exports = {
deepestNode: function deepestNode(node, level) {
if (!level)
level = 0;
node.depth = level;
if (!node.left && !node.right)
return node;
let deepestLeft, deepestRight = node;
if (node.left)
deepestLeft = deepestNode(node.left, level + 1);
if (node.right)
deepestRight = deepestNode(node.right, level + 1);
if (deepestLeft.depth > deepestRight.depth)
return deepestLeft;
else
return deepestRight;
},
TreeNode: (val) => {
return {
val: val,
left: null,
right: null
}
}
};
</code></pre>
<p><strong>Test Class</strong></p>
<pre><code>const expect = require('chai').expect;
const deepestNode = require('../../src/google/deepestNode');
let a = deepestNode.TreeNode('a');
let b = deepestNode.TreeNode('b');
let c = deepestNode.TreeNode('c');
let d = deepestNode.TreeNode('d');
a.left = b;
b.left = d;
a.right = c;
expect(deepestNode.deepestNode(a).val).eq('d');
a = deepestNode.TreeNode('a');
expect(deepestNode.deepestNode(a).val).eq('a');
</code></pre>
<p>I am a Javascript newbie so any comments regarding either the algorithm itself or the use of Javascript is welcome.</p>
|
[] |
[
{
"body": "<ul>\n<li>Use brackets for one-liner blocks (opinionated, but pretty strong consensus for this) </li>\n<li>Use shorthand object notation <code>{ val: val }</code> -> <code>{ val }</code></li>\n<li>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters\" rel=\"nofollow noreferrer\">default value syntax</a></li>\n<li>Prefer <code>const</code> to <code>let</code> (this goes for your test too)</li>\n<li>Prefer ternary to if (not true if readability suffers)</li>\n<li>Let <code>TreeNode</code> take <code>right</code> and <code>left</code> as parameters</li>\n</ul>\n\n<pre class=\"lang-js prettyprint-override\"><code>module.exports = {\n deepestNode(node) {\n const search = (node, depth = 0) => {\n const { left, right } = node;\n\n if (!left && !right) {\n return { node, depth };\n }\n\n const deepestLeft = left ? search(left, depth + 1) : { depth: -1 };\n const deepestRight = right ? search(right, depth + 1) : { depth: -1 };\n\n return deepestLeft.depth > deepestRight.depth\n ? deepestLeft\n : deepestRight;\n };\n return search(node).node;\n },\n TreeNode: (val, left = null, right = null) => ({\n val,\n left,\n right\n })\n};\n\n\n</code></pre>\n\n<p><strong>Update</strong>: fix return value. And typos...</p>\n\n<p><strong>Update 2</strong>: adjusted to @ggorlen point on not mutating the parameter</p>\n\n<p><strong>Update 3</strong>: fix return value (again)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T21:23:13.677",
"Id": "438110",
"Score": "0",
"body": "What do you mean `fix return value`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T21:34:47.440",
"Id": "438111",
"Score": "0",
"body": "@KorayTugay I changed the return value of the method, but it should return the same thing as in your original code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T21:58:44.413",
"Id": "438113",
"Score": "0",
"body": "I see, thank you."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T21:10:12.483",
"Id": "225613",
"ParentId": "225608",
"Score": "2"
}
},
{
"body": "<p>Here are my thoughts:</p>\n\n<ul>\n<li><p>Don't mutate function parameters unless there is good reason to do so.</p>\n\n<pre><code>node.depth = level;\n</code></pre>\n\n<p>The above statement basically breaks the contract of the function. The function claims to locate the <code>deepestNode</code>, but in fact it does <code>findDeepestNodeAndSetDeepestPropOnAllNodes</code> (silly, but you get the idea). This could lead to confusing, subtle bugs for the client of your module and is a serious issue.</p>\n\n<p>If you want to return the level in addition to the node itself, that's easily done by returning a <code>{node, level}</code> object pair which doesn't corrupt the reference to <code>node</code>. However, since the test suite disregards the level, I'd omit it since the function name makes no mention of this and it's not typically valuable information.</p></li>\n<li><p>Always use braces for blocks of code:</p>\n\n<pre><code>if (deepestLeft.depth > deepestRight.depth)\n return deepestLeft;\nelse\n return deepestRight;\n</code></pre>\n\n<p>is clearer and less error-prone as:</p>\n\n<pre><code>if (deepestLeft.depth > deepestRight.depth) {\n return deepestLeft;\n}\n\nreturn deepestRight;\n</code></pre></li>\n<li><p>Use default parameters:</p>\n\n<pre><code>function deepestNode(node, level) {\n if (!level)\n level = 0;\n...\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>function deepestNode(node, level=0) {\n...\n</code></pre></li>\n<li><p>Avoid excessive conditionals; it's possible to simplify 6 branches to 2, reducing the cognitive load required to understand the code. Re-write negative conditionals to be positive when possible.</p>\n\n<p>For example,</p>\n\n<pre><code>if (!node.left && !node.right)\n return node;\n</code></pre>\n\n<p>can be eliminated. As a rule of thumb, I try to operate only on the current node when writing recursive functions unless I'm forced to do otherwise.</p></li>\n<li><p>Avoid excessive references and intermediate variables. Consider:</p>\n\n<pre><code>let deepestLeft, deepestRight = node;\n/* ... various conditionals that may or may not change where\n `deepestLeft`, `deepestRight` and `node` points to ... */\n\n// later on, unclear state\n</code></pre>\n\n<p>As with conditionals, when you begin relying on aliases for objects, it becomes difficult to keep track of what's pointing where. Code like this should only be written if there's no way around it, which isn't the case here.</p>\n\n<p>In fact, this line causes crashes when <code>node.right</code> is the only child of a node. You may have meant:</p>\n\n<pre><code>let deepestLeft = deepestRight = node;\n</code></pre>\n\n<p>Adding more thorough tests to your suite would help detect bugs like this.</p>\n\n<p>As an aside, prefer <code>const</code> instead of <code>let</code> unless you have to reassign the variable. </p></li>\n<li><p>Don't crash on <code>undefined</code>/<code>null</code> parameters if it's trivial to prevent.</p>\n\n<pre><code>node.depth = level; // boom if `node` is undefined\n</code></pre></li>\n</ul>\n\n<hr>\n\n<p>Here's a re-write. I wrote this as browser code, but you can dump it into <code>module.exports</code>:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const deepestNode = (node, deepest={level: -1}, level=0) => {\n if (node) {\n if (level > deepest.level) {\n deepest.node = node;\n deepest.level = level;\n }\n\n deepestNode(node.left, deepest, level + 1);\n deepestNode(node.right, deepest, level + 1);\n }\n\n return deepest.node;\n};\n\nclass TreeNode {\n constructor(val, left=null, right=null) {\n this.val = val;\n this.left = left;\n this.right = right;\n }\n}\n\nconst root = new TreeNode(1, \n new TreeNode(2, \n new TreeNode(4)\n ), \n new TreeNode(3)\n);\n\nconsole.log(deepestNode(root));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>This function can also be written iteratively in a clean way, avoiding call stack overflow errors and function call overhead:</p>\n\n<pre><code>const deepestNode = node => {\n let deepest = {level: -1};\n const stack = [[node, 0]];\n\n while (stack.length) {\n const [curr, level] = stack.pop();\n\n if (curr) {\n if (level > deepest.level) {\n deepest = {node: curr, level: level};\n }\n\n stack.push([curr.left, level + 1], [curr.right, level + 1]);\n }\n }\n\n return deepest.node;\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T21:19:13.653",
"Id": "438109",
"Score": "0",
"body": "Great minds think alike :D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T22:00:28.543",
"Id": "438114",
"Score": "0",
"body": "When do you attach a property to an object in JavaScript? In which cases? (The way I attach property `depth` for example..)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T22:08:52.223",
"Id": "438115",
"Score": "0",
"body": "If the function tells the client that it's going to permanently modify (mutate) the objects, then it's OK. For example, [`Array#push`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) clearly modifies the object it's called on rather than returning a new copy. In your case, the function `deepestNode` is similar to [`Array#find`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) in that it performs a search. You wouldn't want `Array#find` to mess with the objects it was supposed to search through, I'd guess."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T22:09:19.847",
"Id": "438116",
"Score": "0",
"body": "I see, thank you. Makes sense."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T22:10:11.650",
"Id": "438117",
"Score": "0",
"body": "No problem--check out [side effect](https://en.wikipedia.org/wiki/Side_effect_(computer_science)) on wikipedia for more information on mutation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T22:24:34.950",
"Id": "438118",
"Score": "0",
"body": "Since we kind of moved away from a strict recursion and holding state in a variable, I think we do not need to pass the `currentLevel` to `traverse`. Something like this: https://pastebin.com/4k5N8vVw"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T22:25:23.440",
"Id": "438119",
"Score": "0",
"body": "Sorry, I mean like this: https://pastebin.com/FVWPhShT"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T22:30:29.850",
"Id": "438121",
"Score": "0",
"body": "We can do that, but what is gained? The idea is to keep the code as tight as possible, using as few variables and conditionals as we can. If we move `level` outside of `traverse`, we extend the scope of `level` (similar to a global variable). The value of `currentLevel` in a given stack frame is hard to determine from reading the code. Parameters are good in this case, I would argue, because it's clear what `level` is and how it's changing from one frame to the next because it's local to each frame. Having to `foo++` and then `foo--` later on just to keep state correct should be a red light."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T22:56:42.787",
"Id": "438124",
"Score": "0",
"body": "Why would we then not want the same for deepest found as in https://pastebin.com/vDgfgApW ? (I am trying to share ideas, not challenge you)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T23:03:54.523",
"Id": "438125",
"Score": "0",
"body": "We do, but sometimes it's just more convenient to bump something up a scope. I can get away with `deepest` being outside of the local scope because it's very intuitive when it gets modified and the alternative of passing it in as a reference parameter or using a return value doesn't really gain a whole lot of safety since we have a nested function that has tight scope already. In your code, notice that you've had to introduce more complex conditionals and variables to make it all work, counteracting the safety. I still prefer my original, but right idea! Which code is easier to understand?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T23:09:03.607",
"Id": "438126",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/97081/discussion-between-ggorlen-and-koray-tugay)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T08:36:26.290",
"Id": "438168",
"Score": "0",
"body": "+1 great answer, nice to see a non recursive alternative , however I will nit pick. You could have put more emphasise on the bug that will crash on any right sided only node you note as \"Don't crash on `undefined/null`\". Also I do not believe good JS should use `null` especially if the semantically correct `undefined` can take its place automatically. And maybe the statement \"avoiding stack overflow\" could be written more precisely as \"avoiding call stack overflow\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T15:00:41.170",
"Id": "438204",
"Score": "0",
"body": "@Blindman67 I actually like JavaScript having both undefined and null. I would prefer \"null\" in this case, since for me it carries the meaning \"we have purposely set this field to an empty value\" vs. undefined \"we don't know if someone has just forgotten to set this field, or if a field of this name actually exists at all\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T15:05:57.897",
"Id": "438205",
"Score": "0",
"body": "@Blindman67 Thanks and please nitpick! I'm not sure I follow what you mean by \"right sided only node\"--maybe I'm missing something here. For `undefined`/`null`, are you referring to my defaults in the `Node` class? I see your point but, as Falco says, I like that `null` is very explicit and it's a stringifiable JSON value. I wouldn't write my logic to check for one or the other, though, `=== undefined` or `=== null`, just `!node`, so I'm flexible on this. For \"call stack\" are you trying to disambiguate it from an explicit stack? I don't follow the distinction between \"stack\" and \"call stack\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T06:33:22.853",
"Id": "438318",
"Score": "0",
"body": "@ggorlen JS has various stacks, call stack is more concise. Right sided I mean that OPs code throws error if a node only has a link to the right. Null means a property is defined `{ a = 0} = {a: null}` will assign `null` to `a` while `{ a = 0} = {a: undefined}` or `{ a = 0} = {}` will assign `0 `to `a`. JSON does not define structure and using null means that loading JSON data requires explicit assignment of defaults rather than `{ ...defaults, ...JSON.parse(data)}`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T06:43:44.120",
"Id": "438324",
"Score": "0",
"body": "Right, I follow you. Good catches and thanks for the clarification!"
}
],
"meta_data": {
"CommentCount": "16",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T21:17:13.390",
"Id": "225614",
"ParentId": "225608",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "225614",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T20:32:16.920",
"Id": "225608",
"Score": "6",
"Tags": [
"javascript",
"beginner",
"tree",
"search"
],
"Title": "Javascript - Find a deepest node in a binary tree"
}
|
225608
|
<p>I am looking for any refactoring tips to improve code readability. Does it feel like procedural programming? If so, how can I improve it?</p>
<pre class="lang-java prettyprint-override"><code>public class StatementJob implements Job {
private static final Logger LOGGER = LoggerFactory.getLogger(StatementJob.class);
private static final String JOB_IS_DISABLED = "Uploads statement job is disabled and will not run";
private static final String UNABLE_TO_CONTINUE = "Unable to continue";
private final Configuration jobConfiguration;
private final Log log;
public StatementJob(JobConfiguration jobConfiguration) {
this.jobConfiguration = jobConfiguration;
this.log = new JobLog();
}
@Override
public Log execute() {
LOGGER.info("Stating uploading statements");
final JobProperties properties;
try {
properties = jobConfiguration.loadProperties();
} catch (BadConfigurationException e) {
return log.addError(e.getMessage());
}
if (!properties.isRunJob()) {
return log.addSuccess(JOB_IS_DISABLED);
}
final Employee statementUploader = Employee.load(properties.getStatementUploader());
final FileStatements fileStatements = new Statements(properties.getDirectories());
fileStatements
.getInboundStatements()
.forEach(inboundStatement -> {
try {
fileStatements.moveToWipLocation(inboundStatement);
fileStatements
.getWipStatements()
.forEach(wipFileStatement -> {
try {
new UploadableDocument(statementUploader, wipFileStatement).upload();
fileStatements.moveToArchiveLocation(wipFileStatement);
} catch (FailedToUploadDocumentException e) {
log.addError(e.getMessage());
try {
fileStatements.moveToErrorLocation(wipFileStatement);
} catch (UnableToMoveFileToDirectoryException ex) {
LOGGER.error(UNABLE_TO_CONTINUE, e);
throw new FatalJobException(UNABLE_TO_CONTINUE, e);
}
} catch (UnableToReadFileException | UnableToMoveFileToDirectoryException e) {
LOGGER.error(UNABLE_TO_CONTINUE, e);
throw new FatalJobException("Unable to continue", e);
}
});
} catch (UnableToMoveFileToDirectoryException e) {
LOGGER.error(UNABLE_TO_CONTINUE, e);
throw new FatalJobException("Unable to continue", e);
}
});
return log;
}
}
</code></pre>
<p>What does the code do?</p>
<ul>
<li>There is <code>FileStatements</code> which represents files, called <code>Statement</code>, stored in the file system in the inbound directory.</li>
<li>When <code>StatementJob</code> is executed it moves <code>Statement</code>s from the inbound to work in progress directory.</li>
<li>Then <code>Statement</code>s from the work in progress directory are uploded to some storage.</li>
<li>When the upload is succesfull, the <code>Statement</code>s are moved to the archive statement folder. Statements which failed to upload are moved to the error statement folder.</li>
<li><code>Log</code> is used to collect information about the job that will be emailed to whomever needs to know the status. This is very primitive at this point.</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T22:27:38.587",
"Id": "438120",
"Score": "0",
"body": "When posting here, try to specify details that are not clear from your exact code snippet. For instance, I have the following questions: 1. What logger are you using? 2. What platform is this for (make sure to add tags too)? 3. We have no idea about what almost all of those classes are. I did a quick Google for `FileStatements` for example and got no results. We can't evaluate your code without knowing what your code does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T22:44:02.827",
"Id": "438122",
"Score": "0",
"body": "I was hopping that the code is readable anough and that it is not important to reviewers which particular logger, platform (do you mean OS?) I use. You cannot see implementation details of `FileStatements` and other classes, but I was hoping that it is clear what it does by looking at the methods it has and what they return. I could upload the entire project to github with all the classes but I think no one would be interested in such extensive code review. I might be wrong, let me know."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T22:54:04.490",
"Id": "438123",
"Score": "0",
"body": "The main concern is that when posting on here, people like to be able to load it into an IDE as no one codes in a text editor anymore. Most auto-formatters tend to fail when they aren't able to compile things. I'm working on putting a Gist together that would have some dummy classes that makes it so I can load this locally. I'll add that in a comment when I'm done. When I first started posting here I didn't really understand what that entailed so my follow-up should help you understand what people want in the future :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T01:35:50.500",
"Id": "438131",
"Score": "0",
"body": "I see your point now. Thank you, I will do better next time. I very much appreciate your effort!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T01:52:20.590",
"Id": "438132",
"Score": "0",
"body": "I added a description what the code does. I know it is too late..."
}
] |
[
{
"body": "<p>Here's the best I think we can get it without actually knowing what your code is for.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class StatementJob {\n public static final Logger LOGGER = LoggerFactory.getLogger(StatementJob.class);\n\n public static final String JOB_IS_DISABLED = \"Uploads statement job is disabled and will not run\";\n public static final String UNABLE_TO_CONTINUE = \"Unable to continue\";\n\n private final Configuration jobConfiguration;\n private final Log log;\n\n public StatementJob(JobConfiguration jobConfiguration) {\n this.jobConfiguration = jobConfiguration;\n this.log = new JobLog();\n }\n\n public Log execute() {\n LOGGER.debug(\"Stating uploading statements\");\n\n final JobProperties properties;\n try {\n properties = jobConfiguration.loadProperties();\n } catch (BadConfigurationException e) {\n return log.addError(e.getMessage());\n }\n\n if (!properties.isRunJob()) {\n return log.addSuccess(JOB_IS_DISABLED);\n }\n\n Employee employee = Employee.load(properties.getStatementUploader());\n FileStatements fileStatements = new Statements(properties.getDirectories());\n\n FatalConsumer<WipStatement> wipConsumer = wip -> {\n try {\n new UploadableDocument(employee, wip).upload();\n fileStatements.moveToArchiveLocation(wip);\n } catch (FailedToUploadDocumentException e) {\n log.addError(e.getMessage());\n fileStatements.moveToErrorLocation(wip);\n }\n };\n FatalConsumer<InboundStatement> inboundConsumer = inbound -> {\n fileStatements.moveToWipLocation(inbound);\n fileStatements.getWipStatements().forEach(wipConsumer);\n };\n\n fileStatements.getInboundStatements().forEach(inboundConsumer);\n\n return log;\n }\n\n @FunctionalInterface\n public interface FatalConsumer<T> extends Consumer<T> {\n void fatalAccept(T t) throws UnableToMoveFileToDirectoryException, UnableToReadFileException;\n\n @Override\n default void accept(T t) {\n try {\n fatalAccept(t);\n } catch (UnableToMoveFileToDirectoryException | UnableToReadFileException e) {\n LOGGER.error(UNABLE_TO_CONTINUE, e);\n }\n }\n }\n}\n</code></pre>\n\n<p>Changelog:</p>\n\n<ul>\n<li>Separate constants to be grouped by category. The logger typically is flush with the class declaration while other constants are grouped below it.</li>\n<li>No need to have the extra space after the start of the <code>execute</code> method</li>\n<li>Use more accurate log levels. Specifically, you overuse \"info\". Refer to <a href=\"https://stackify.com/9-logging-sins-java/\" rel=\"nofollow noreferrer\">this</a> article about different things to avoid when logging effectively.\n\n<ul>\n<li>\"DEBUG is intended for messages that could be useful in debugging an issue (ex: method execution started)\"</li>\n</ul></li>\n<li>Use line breaks in <a href=\"https://en.wikipedia.org/wiki/Fluent_interface\" rel=\"nofollow noreferrer\">fluent</a> calls only when it becomes too long, and then only when you have created your stream/data-structure. Specifically, there's no need to have a line break after <code>fileStatements</code></li>\n<li>You have a lot of excess indentation and repeated code. Specifically, all of times you catch an exception, log it, and then immediately rethrow it. My changes above resolve that.</li>\n<li>If you are going to statically define the document uploader to be an Employee, naming the variable <code>documentUploader</code> instead of <code>employee</code> is kind of pointless.</li>\n</ul>\n\n<p>I would highly recommend moving <code>FatalConsumer</code> and each of the non-logging constants you have to their own files. Besides that, this is about as good as you're going to get imo. Hope this helps!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T23:47:06.663",
"Id": "225621",
"ParentId": "225615",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "225621",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T21:20:17.403",
"Id": "225615",
"Score": "2",
"Tags": [
"java"
],
"Title": "Java job responsible for processing file statements"
}
|
225615
|
<p>My application needs to let the user select a folder from somewhere on their local machine. Below are the interface and model pair that I have written to let the user do so.</p>
<pre class="lang-cs prettyprint-override"><code>public interface IFolderPicker
{
// Methods
// =======
string Show();
}
</code></pre>
<pre class="lang-cs prettyprint-override"><code>using Microsoft.WindowsAPICodePack.Dialogs;
using WinForms = System.Windows.Forms;
public class FolderPicker : IFolderPicker
{
// Constants
// =========
private const string SelectATargetFolder = "Select a target folder";
private const string CDrive = @"C:\";
// Variables
// =========
private readonly bool isPlatformSupported;
private readonly WinForms.FolderBrowserDialog xpFolderBrowserDialog;
private readonly CommonOpenFileDialog vistaFolderBrowserDialog;
// Constructor
// ===========
public FolderPicker()
{
isPlatformSupported = CommonFileDialog.IsPlatformSupported;
xpFolderBrowserDialog = new WinForms.FolderBrowserDialog
{
Description = SelectATargetFolder
};
vistaFolderBrowserDialog = new CommonOpenFileDialog
{
Title = SelectATargetFolder,
IsFolderPicker = true,
DefaultDirectory = CDrive,
AllowNonFileSystemItems = false,
EnsurePathExists = true,
Multiselect = false,
NavigateToShortcut = true
};
}
// Deconstructor
// =============
~FolderPicker()
{
xpFolderBrowserDialog.Dispose();
vistaFolderBrowserDialog.Dispose();
}
// Methods
// =======
public string Show()
{
if (isPlatformSupported)
{
return SelectWinVistaOrLaterFolder();
}
else
{
return SelectWinXPFolder();
}
}
private string SelectWinXPFolder()
{
WinForms.DialogResult result = xpFolderBrowserDialog.ShowDialog();
switch (result)
{
case WinForms.DialogResult.OK:
case WinForms.DialogResult.Yes:
return xpFolderBrowserDialog.SelectedPath;
default:
return null;
}
}
private string SelectWinVistaOrLaterFolder()
{
CommonFileDialogResult result = vistaFolderBrowserDialog.ShowDialog();
switch (result)
{
case CommonFileDialogResult.Ok:
return vistaFolderBrowserDialog.FileName;
default:
return null;
}
}
}
</code></pre>
<p>My reasoning for this design is that now the 3 <code>readonly</code> variables can be mocked in unit tests via reflection, while this isn't an ideal way of doing it, it's better than nothing.</p>
<p>While I am looking for all feedback, my focus here is on the <code>WinForms.FolderBrowserDialog</code> and the <code>CommonOpenFileDialog</code>. They both implement the <code>IDisposable</code> interface and my concern is that I might not be implementing that properly?<br>
I believe that I could make the <code>IFolderPicker</code> interface extend the <code>IDisposable</code> interface and then call the two <code>.Dispose()</code> methods from within the inherited <code>Dispose</code> method but I was hoping I could insulate the rest of my program from these two classes as much as possible - is disposing of them in the deconstructor like this also valid?</p>
<p>Originally I had both these classed being instantiated in their respective <code>Select...()</code> methods in a <code>using</code> block. But while also not being mock-able, it meant they were being newed up each time the method was called - is this current implementation better than that?</p>
|
[] |
[
{
"body": "<h2>Review</h2>\n\n<ul>\n<li>You always instantiate inner dialogs for both platforms, even though one will never be called. Your platform will not change at runtime. Use the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.lazy-1?view=netframework-4.8\" rel=\"noreferrer\">Lazy pattern</a> to only instantiate the required dialog at first access.</li>\n<li>Rather than returning the magic path <code>null</code>, I would opt to use a <code>TryShow</code> method returning a <em>boolean</em> whether a path got selected an an <code>out</code> parameter for the path.</li>\n</ul>\n\n<hr>\n\n<h2>Object Destruction</h2>\n\n<p>From <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/destructors\" rel=\"noreferrer\">Programming Guide: Destructors</a>:</p>\n\n<blockquote>\n <p><em>The programmer has no control over when the finalizer is called\n because this is determined by the garbage collector. The garbage\n collector checks for objects that are no longer being used by the\n application. If it considers an object eligible for finalization, it\n calls the finalizer (if any) and reclaims the memory used to store the\n object.</em></p>\n</blockquote>\n\n<p>Since your class is not sealed, derived classes can be made. These classes will not be able to control the order of finalisation code. The order of destructors is fixed as this snipped from the link shows:</p>\n\n<blockquote>\n<pre><code>protected override void Finalize() \n{ \n try \n { \n // Cleanup statements... \n } \n finally \n { \n base.Finalize(); \n } \n}\n</code></pre>\n</blockquote>\n\n<p>That's why you should implement the <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose\" rel=\"noreferrer\">dispose pattern</a> instead. It allows for more flexibility in flow and distinguishes between disposing managed vs unmanaged code. </p>\n\n<hr>\n\n<h2>Unit Tests</h2>\n\n<blockquote>\n <p><em>My reasoning for this design is that now the 3 readonly variables can be mocked in unit tests via reflection, while this isn't an ideal way\n of doing it, it's better than nothing.</em></p>\n</blockquote>\n\n<p>When writing code with testability in mind, you don't want to resort to reflection to mock private state of your classes. There are a couple of options available:</p>\n\n<ul>\n<li>Make the <em>private</em> methods <em>protected virtual</em>. Mocking frameworks and derived classes are able to override the methods. Partial mocks could be used in this case.</li>\n<li>Wrap both internal dialogs behind a custom interface, injected into the outer class. The class no longer has dependencies on native win and vista components and interfaces are easy to mock. </li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T13:57:36.500",
"Id": "438198",
"Score": "0",
"body": "Thank you for your answer. \"These classes will not be able to control the order of finalisation code.\" - Why is this an issue?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T14:32:28.897",
"Id": "438203",
"Score": "0",
"body": "This may or may not be an issue depending on your design. The point is the dispose pattern allows for more flow control."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T10:44:38.620",
"Id": "438481",
"Score": "0",
"body": "Thanks again for your answer, I didn't know about the lazy pattern. I am however going to mark the other answer as accepted because it is the implementation that I finally went with."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T12:02:56.630",
"Id": "438486",
"Score": "0",
"body": "That was also the suggestion I made _Wrap both internal dialogs behind a custom interface, injected into the outer class._ but no hard feelings :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T04:55:25.350",
"Id": "225632",
"ParentId": "225616",
"Score": "5"
}
},
{
"body": "<p>Additionally to the great answer of dfhwze, I'll provide an alternative implementation that includes some of the suggestions.</p>\n\n<p>Primary, I would implement each case separatly and create / dispose the actual dialog each time the method Show is called:</p>\n\n<pre><code>public interface IFolderPicker\n{\n string Show();\n}\n\npublic class VistaFolderPicker : IFolderPicker\n{\n private const string SelectATargetFolder = \"Select a target folder\";\n private const string CDrive = @\"C:\\\";\n\n public string Show()\n {\n var vistaFolderBrowserDialog = new CommonOpenFileDialog\n {\n Title = SelectATargetFolder,\n IsFolderPicker = true,\n DefaultDirectory = CDrive,\n AllowNonFileSystemItems = false,\n EnsurePathExists = true,\n Multiselect = false,\n NavigateToShortcut = true\n };\n\n using (vistaFolderBrowserDialog)\n {\n return vistaFolderBrowserDialog.ShowDialog() == CommonFileDialogResult.Ok\n ? vistaFolderBrowserDialog.FileName\n : null;\n }\n }\n}\n\npublic class XPFolderPicker : IFolderPicker\n{\n private const string SelectATargetFolder = \"Select a target folder\";\n\n public string Show()\n {\n xpFolderBrowserDialog = new WinForms.FolderBrowserDialog\n {\n Description = SelectATargetFolder\n };\n\n using (xpFolderBrowserDialog)\n {\n return xpFolderBrowserDialog.ShowDialog() == WinForms.DialogResult.OK\n ? xpFolderBrowserDialog.SelectedPath\n : null;\n }\n }\n}\n\nvar folderPicker = CommonFileDialog.IsPlatformSupported\n ? new VistaFolderPicker()\n : new XPFolderPicker()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T19:50:02.790",
"Id": "438260",
"Score": "0",
"body": "clean and simple (+1)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T09:25:20.870",
"Id": "438353",
"Score": "0",
"body": "Thank you for your answer. I like how this separates the two implementations (now that I say it like that it seems obvious that they should be separate). Do you have any suggestions for how I could make this approach more testable? I appreciate that at this level it's essentially a wrapper around Windows APIs but I would still like to test them if possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T16:12:00.390",
"Id": "438405",
"Score": "0",
"body": "IMHO there is nothing to test in the IFolderPicker implementations because they just open a dialog. However, dependent object can be tested by providing a mock implementation of the IFolderPicker interface."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T19:46:56.120",
"Id": "225679",
"ParentId": "225616",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "225679",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T22:32:04.093",
"Id": "225616",
"Score": "5",
"Tags": [
"c#",
"memory-management",
"wpf",
"mvvm"
],
"Title": "MVVM model letting the user select a directory in a testable manner"
}
|
225616
|
<p>I have written this function is part of a research project that involves analyzing time-series data from stochastic processes. We have a small number (from 1 to 3) of independent observations of a scalar time-series. The observations have different lengths, and each contain about <span class="math-container">\$10^4-10^5\$</span> data points. The function below <code>nKBR_moments.m</code> takes a cell array of the observations as input, along with other settings, and outputs statistical quantities known as "moments of conditional increments". These are the variables <code>M1</code> and <code>M2</code>. For more detail of the theory, <a href="https://doi.org/10.1016/j.physleta.2009.07.073" rel="nofollow noreferrer">this research paper</a> outlines a similar method.</p>
<p>For the research purposes the function will eventually be evaluated tens of thousands of times, on a desktop computer. One evaluation of this function takes about 3 seconds with the test script I have provided below. Thoughts on optimising code performance, memory usage or scalability are appreciated.</p>
<p>MATLAB function:</p>
<pre class="lang-matlab prettyprint-override"><code>function [Xcentre,M1,M2] = nKBR_moments(X,tau_in,Npoints,xLims,h)
%Kernel based moments, n-data
%
% Notes:
% Calculates kernel based moments for a given stochastic time-series.
% Uses Epanechnikov kernel with built in computational advantages. Uses
% Nadaraya-Watson estimator. Calculates moments from n sources of data.
%
%
% Inputs:
% - "X" Observed variables, cell array of data
% - "tau_in" Time-shift indexes
% - "Npoints" Number of evaluation points
% - "xLims" Limits in upper and lower evaluation points
% - "h" Bandwidth
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Processing
dX = (xLims(2)-xLims(1))/(Npoints-1); % Bins increment
Xcentre = xLims(1):dX:xLims(2); % Grid
heff = h*sqrt(5); % Effective bandwidth, for setting up bins
eta = floor(heff/dX+0.5); % Bandwidth for bins optimizing
% Epanechnikov kernel
K= @(u) 0*(u.^2>1)+3/4*(1-u.^2).*(u.^2<=1);
Ks = @(u) K(u/sqrt(5))/sqrt(5); % Silverman's definition of the kernel (Silverman, 1986)
Kh = @(u) Ks(u/h)/h; % Changing bandwidth
% Sort all data into bins
Bextend = dX*(eta+0.5); % Extend bins
edges = xLims(1)-Bextend:dX:xLims(2)+Bextend; % Edges
ndata = numel(X); % Number of data-sets
Xloc = cell(1,ndata); % Preallocate histogram location data
nXdata = cellfun(@numel,X); % Number of x data
key = 1:max(nXdata); % Data key
for nd = 1:ndata
[~,~,Xloc{nd}] = histcounts(X{nd},edges); % Sort
end
Xbinloc = eta+(1:Npoints); % Bin locations
BinBeg = Xbinloc-eta; % Bin beginnings
BinEnd = Xbinloc+eta; % Bin beginnings
% Preallocate
Ntau = numel(tau_in); % Number of time-steps
[M1,M2] = deal(zeros(Ntau,Npoints)); % Moments
[iX,iXkey,XU,Khj,yinc,Khjt] = deal(cell(1,ndata)); % Preallocate increment data
% Pre calculate increments
inc = cell(Ntau,ndata);
for nd = 1:ndata
poss_tau_ind = 1:nXdata(nd); % Possible time-shifts
for tt = 1:Ntau
tau_c = tau_in(tt); % Chosen shift
tau_ind = poss_tau_ind(1+tau_c:end); % Chosen indices
inc{tt,nd} = X{nd}(tau_ind) - X{nd}(tau_ind - tau_c);
end
end
% Loop over evaluation points
for ii = 1:Npoints
% Start and end bins
kBinBeg = BinBeg(ii);
kBinEnd = BinEnd(ii);
% Data and weights
for nd = 1:ndata
iX{nd} = and(kBinBeg<=Xloc{nd},Xloc{nd}<=kBinEnd); % Data in bins
iXkey{nd} = key(iX{nd}); % Data key
XU{nd} = X{nd}(iX{nd}); % Unshifted data
Khj{nd} = Kh(Xcentre(ii)-XU{nd}); % Weights
end
% For each shift
for tt = 1:Ntau
tau_c = tau_in(tt); % Chosen shift
% Get data
for nd = 1:ndata
XUin = iXkey{nd}; % Unshifted data indices
XUin(XUin>nXdata(nd)-tau_c) = []; % Clip overflow
yinc{nd} = inc{tt,nd}(XUin); % Increments
Khjt{nd} = Khj{nd}(1:numel(yinc{nd})); % Clipped weight vector
end
% Concatenate data
ytt = [yinc{:}];
Khjtt = [Khjt{:}];
% Increments and moments
sumKhjtt = sum(Khjtt);
M1(tt,ii) = sum(Khjtt.*ytt)/sumKhjtt;
y2 = (ytt - M1(tt,ii)).^2; % Squared (with correction)
M2(tt,ii) = sum(Khjtt.*y2)/sumKhjtt;
end
end
end
</code></pre>
<p>MATLAB test script (no feedback for this required):</p>
<pre class="lang-matlab prettyprint-override"><code>%% nKBR_testing
clearvars,close all
%% Parameters
% Simulation settings
n_sims = 10; % Number of simulations
dt = 0.001; % Time-step
tend1 = 40; % Time-end, process 1
tend2 = 36; % Time-end, process 2
x0 = 0; % Start position
eta = 0; % Mean
D = 1; % Noise amplitude
gamma = 1; % Drift slope
% Analysis settings
tau_in = 1:60; % Time-shift indexes
Npoints = 50; % Number of evaluation points
xLims = [-1,1]; % Limits of evaluation
h = 0.5; % Kernel bandwidth
%% Simulating
t1 = 0:dt:tend1;
t2 = 0:dt:tend2;
% Realize an Ornstein Uhlenbeck process
rng('default')
ex1 = exp(-gamma*t1);
ex2 = exp(-gamma*t2);
x1 = x0*ex1 + eta*(1-ex1) + sqrt(D)*ex1.*cumsum(exp(gamma*t1).*[0,sqrt(2*dt)*randn(1,numel(t1)-1)]);
x2 = x0*ex2 + eta*(1-ex2) + sqrt(D)*ex2.*cumsum(exp(gamma*t2).*[0,sqrt(2*dt)*randn(1,numel(t2)-1)]);
%% Calculating and timing moments
tic
for ns = 1:n_sims
[~,M1,M2] = nKBR_moments({x1,x2},tau_in,Npoints,xLims,h);
end
nKBR_moments_time = toc;
nKBR_average_time = nKBR_moments_time/n_sims
%% Plotting
figure
hold on,box on
plot(t1,x1)
plot(t2,x2)
xlabel('Time')
ylabel('Amplitude')
title('Two Ornstein-Uhlenbeck processes')
figure
subplot(1,2,1)
box on
plot(dt*tau_in,M1,'k')
xlabel('Time-shift, \tau')
title('M^{(1)}')
subplot(1,2,2)
box on
plot(dt*tau_in,M2,'k')
xlabel('Time-shift, \tau')
title('M^{(2)}')
</code></pre>
<p>The test script will create two figures similar to the ones below. </p>
<p><a href="https://i.stack.imgur.com/c6RKX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/c6RKX.png" alt="Time-series data of two OU processes"></a></p>
<p><a href="https://i.stack.imgur.com/g0nRe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/g0nRe.png" alt="Calculated moments of the processes"></a></p>
|
[] |
[
{
"body": "<p>The code is a bit confusing due to the large number of really short variable names, though those might match the equations in the paper you linked, I haven't looked. I would use longer, more descriptive variable names (those will also allow you to reduce the number of comments, which can only get out of synch when changing the code). Other than that, I think it's straight-forward and easy to follow.</p>\n\n<p>In regards to performance, I don't immediately see any huge gains to be had. It might be possible to vectorize some operations, but the opportunities are not immediate obvious. The number 1 thing you can do to find out how to improve your speed is to profile your code. MATLAB has a built-in profiler, see <a href=\"https://www.mathworks.com/help/matlab/ref/profile.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Here are a few things that can be simplified:</p>\n\n<hr>\n\n<pre class=\"lang-matlab prettyprint-override\"><code> for nd = 1:ndata\n iX{nd} = and(kBinBeg<=Xloc{nd},Xloc{nd}<=kBinEnd); % Data in bins\n iXkey{nd} = key(iX{nd}); % Data key\n XU{nd} = X{nd}(iX{nd}); % Unshifted data\n Khj{nd} = Kh(Xcentre(ii)-XU{nd}); % Weights\n end\n</code></pre>\n\n<p>In this piece, <code>iX{nd}</code> is never used outside the loop. Neither is <code>XU{nd}</code>. Let's get rid of these (less indexing and less data storage both lead to faster code):</p>\n\n<pre class=\"lang-matlab prettyprint-override\"><code> for nd = 1:ndata\n iX = and(kBinBeg <= Xloc{nd}, Xloc{nd} <= kBinEnd); % Data in bins\n iXkey{nd} = key(iX); % Data key\n XU = X{nd}(iX); % Unshifted data\n Khj{nd} = Kh(Xcentre(ii)-XU); % Weights\n end\n</code></pre>\n\n<p>Because <code>key = 1:max(nXdata)</code>, <code>key(iX)</code> is the same as <code>find(iX)</code>, it is likely that the latter is faster. Now you have:</p>\n\n<pre class=\"lang-matlab prettyprint-override\"><code> for nd = 1:ndata\n iXkey{nd} = find((kBinBeg <= Xloc{nd}) & (Xloc{nd} <= kBinEnd));\n Khj{nd} = Kh(Xcentre(ii) - X{nd}(iXkey{nd}));\n end\n</code></pre>\n\n<hr>\n\n<p>This phrase:</p>\n\n<pre class=\"lang-matlab prettyprint-override\"><code>XUin(XUin>nXdata(nd)-tau_c) = [];\n</code></pre>\n\n<p>can also be written as:</p>\n\n<pre class=\"lang-matlab prettyprint-override\"><code>XUin = XUin(XUin <= nXdata(nd)-tau_c);\n</code></pre>\n\n<p>This happens inside the innermost loop, and is thus one of the lines most often executed. It is worthwhile trying both options to see which one is faster.</p>\n\n<hr>\n\n<p>This bit is quite expensive, because it copies the data:</p>\n\n<pre class=\"lang-matlab prettyprint-override\"><code> ytt = [yinc{:}];\n Khjtt = [Khjt{:}];\n\n % Increments and moments\n sumKhjtt = sum(Khjtt);\n M1(tt,ii) = sum(Khjtt.*ytt)/sumKhjtt;\n</code></pre>\n\n<p>It is worth while here also to see if a loop is faster than the concatenation:</p>\n\n<pre class=\"lang-matlab prettyprint-override\"><code> sumKhjtt = 0;\n sumKhjtt_ytt = 0;\n for nd = 1:ndata\n sumKhjtt = sumKhjtt + sum(Khjt{nd});\n sumKhjtt_ytt = sumKhjtt_ytt + sum(Khjt{nd}.*yinc{nd});\n end\n M1(tt,ii) = sumKhjtt_ytt / sumKhjtt;\n</code></pre>\n\n<p>(and the same for M2). This loop can be included into the previous one to avoid two more cell arrays: <code>yinc</code> and <code>Khjt</code>:</p>\n\n<pre class=\"lang-matlab prettyprint-override\"><code> sumKhjtt = 0;\n sumKhjtt_ytt = 0;\n for nd = 1:ndata\n XUin = iXkey{nd};\n XUin(XUin > nXdata(nd)-tau_c) = [];\n yinc = inc{tt,nd}(XUin);\n Khjt = Khj{nd}(1:numel(yinc{nd}));\n sumKhjtt = sumKhjtt + sum(Khjt{nd});\n sumKhjtt_ytt = sumKhjtt_ytt + sum(Khjt{nd}.*yinc{nd});\n end\n M1(tt,ii) = sumKhjtt_ytt / sumKhjtt;\n</code></pre>\n\n<p>You'll have to rewrite the equation for <code>M2</code> to be able to merge the summation it into that loop. This is fairly simple, it's analogous to <a href=\"https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Na%C3%AFve_algorithm\" rel=\"nofollow noreferrer\">the naive algorithm for computing the variance</a>. That algorithm is not stable, it depends on your data whether the results are good or not. If it is not, use <a href=\"https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford's_online_algorithm\" rel=\"nofollow noreferrer\">Welford's online algorithm</a> instead. There you can compute the second order central moment of the first batch, then add to the accumulators for subsequent batches.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-26T21:41:24.870",
"Id": "229724",
"ParentId": "225618",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "229724",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T22:38:52.857",
"Id": "225618",
"Score": "4",
"Tags": [
"performance",
"statistics",
"matlab"
],
"Title": "Kernel based conditional increments of many stochastic processes"
}
|
225618
|
<p>Recently I've been developing a chess game in Python - using pygame - just as a project for myself. I have a class for each piece type, and in each class, I have a method called <code>find_available_moves</code> which returns an array representing the board showing where the piece is legally allowed to move. I've accomplished this, but I feel like there is a lot of repetition and I'm unsure how to make my code more concise.</p>
<p>Here is the method from the Rook class for instance:</p>
<pre class="lang-py prettyprint-override"><code>def find_available_moves(self, grid):
"""
:param grid: Grid class
:return list: The spaces where the rook can move to
"""
available_spaces = [[False] * grid.columns for i in range(grid.rows)]
# Check spaces to the right
for x in range(self.grid_position[0] + 1, grid.columns):
# Position to check
position = (x, self.grid_position[1])
# If there is nothing in the space it is available
if grid.board_layout[position[1]][position[0]] is None:
available_spaces[position[1]][position[0]] = True
# If there is a piece of the opposite colour in the space it is available, but further spaces are not
elif grid.board_layout[position[1]][position[0]]['colour'] != self.colour:
available_spaces[position[1]][position[0]] = True
break
# If there is a piece of the same colour in the space it is not available, neither are further spaces
else:
break
# Check spaces to the left
for x in range(self.grid_position[0] - 1, -1, -1):
# Position to check
position = (x, self.grid_position[1])
# If there is nothing in the space it is available
if grid.board_layout[position[1]][position[0]] is None:
available_spaces[position[1]][position[0]] = True
# If there is a piece of the opposite colour in the space it is available, but further spaces are not
elif grid.board_layout[position[1]][position[0]]['colour'] != self.colour:
available_spaces[position[1]][position[0]] = True
break
# If there is a piece of the same colour in the space it is not available, neither are further spaces
else:
break
# Check spaces below
for y in range(self.grid_position[1] + 1, grid.rows):
# Position to check
position = (self.grid_position[0], y)
# If there is nothing in the space it is available
if grid.board_layout[position[1]][position[0]] is None:
available_spaces[position[1]][position[0]] = True
# If there is a piece of the opposite colour in the space it is available, but further spaces are not
elif grid.board_layout[position[1]][position[0]]['colour'] != self.colour:
available_spaces[position[1]][position[0]] = True
break
# If there is a piece of the same colour in the space it is not available, neither are further spaces
else:
break
# Check spaces above
for y in range(self.grid_position[1] - 1, -1, -1):
# Position to check
position = (self.grid_position[0], y)
# If there is nothing in the space it is available
if grid.board_layout[position[1]][position[0]] is None:
available_spaces[position[1]][position[0]] = True
# If there is a piece of the opposite colour in the space it is available, but further spaces are not
elif grid.board_layout[position[1]][position[0]]['colour'] != self.colour:
available_spaces[position[1]][position[0]] = True
break
# If there is a piece of the same colour in the space it is not available, neither are further spaces
else:
break
return available_spaces
</code></pre>
<p>So is there any way that I can make this more simple, by perhaps using another method to test what is in each grid space? I'm just not sure how to go about implementing something like that.</p>
<p>Thank you for your help.</p>
<p><strong>Variable definitions:</strong></p>
<ul>
<li><p>The <code>grid</code> variable is just a class which contains information on the
current layout of the board and is responsible for drawing the pieces
in the correct locations.</p></li>
<li><p><code>grid.rows</code> and <code>grid.columns</code> are integers containing the dimensions
of the board.</p></li>
<li><p><code>grid.board_layout</code> is an array containing a dictionary of the form
<code>{'piece': 'rook', 'colour': 'white'}</code> where there is a piece and
containing <code>None</code> where there isn't. </p></li>
<li><p><code>Rook.grid_position</code> is a tuple containing the grid coordinates of
the piece.</p></li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T13:11:43.853",
"Id": "438193",
"Score": "0",
"body": "Since this is part of a class, we'd need the rest of the class to see whether it makes sense or not. A usage example of the class would be helpful too."
}
] |
[
{
"body": "<p>The difference between the code for moving right:</p>\n\n<blockquote>\n<pre><code> for x in range(self.grid_position[0] + 1, grid.columns):\n # Position to check\n position = (x, self.grid_position[1])\n\n # If there is nothing in the space it is available\n if grid.board_layout[position[1]][position[0]] is None:\n available_spaces[position[1]][position[0]] = True\n\n # If there is a piece of the opposite colour in the space it is available, but further spaces are not\n elif grid.board_layout[position[1]][position[0]]['colour'] != self.colour:\n available_spaces[position[1]][position[0]] = True\n break\n\n # If there is a piece of the same colour in the space it is not available, neither are further spaces\n else:\n break\n</code></pre>\n</blockquote>\n\n<p>and for moving forward is just the definition of <code>position</code>:</p>\n\n<blockquote>\n<pre><code> position = (self.grid_position[0], y)\n</code></pre>\n</blockquote>\n\n<p>So you can certainly factor out a function looking something like this:</p>\n\n<pre><code>def update_line(chessman, grid, available_spaces, line_positions):\n for position in line_positions:\n\n # If there is nothing in the space it is available\n if grid.board_layout[position[1]][position[0]] is None:\n available_spaces[position[1]][position[0]] = True\n\n # If there is a piece of the opposite colour in the space it is available, but further spaces are not\n elif grid.board_layout[position[1]][position[0]]['colour'] != chessman.colour:\n available_spaces[position[1]][position[0]] = True\n break\n\n # If there is a piece of the same colour in the space it is not available, neither are further spaces\n else:\n break\n</code></pre>\n\n<p>This can be shared between the rook, bishop, and queen. The rook would call it something like</p>\n\n<pre><code> update_line(self, grid, available_spaces,\n ((x, self.grid_position[1]) for x in range(self.grid_position[0] + 1, grid.columns))\n update_line(...)\n ...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T16:16:34.763",
"Id": "225659",
"ParentId": "225620",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "225659",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T23:42:00.060",
"Id": "225620",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"chess"
],
"Title": "Finding possible moves in a chess game"
}
|
225620
|
<p>I am currently working through learning C++'s variadic templates and I wanted to create an example use of them that is less trivial than the one in my book. I decided to create a modification of printf's interface where the type of each argument does not need to be specified. Here is an example:</p>
<pre><code>print(std::cout, "Welcome to this computer program, % son of %!", "bob", "some klingon");
//prints "Welcome to this computer program, bob son of some klingon."
</code></pre>
<p>I have also added the ability to escape a <code>%</code> character (or any other character, like the escape character itself) with a <code>/</code>.</p>
<pre><code>#include <iostream>
#include <string>
#include <ostream>
namespace printpriv{
using itr = std::string::const_iterator;
template<typename T>
void print(std::ostream &out, itr it, itr end, const T &t){
bool flagged = false;
while(it != end){
if(flagged){
out << *it;
flagged = false;
}else{
if(*it == '/'){
flagged = true;
}else if(*it=='%') {
out << t;
}else{
out << *it;
}
}
++it;
}
}
template<typename T, typename ... Args>
void print(std::ostream &out, itr it, itr end, const T &t, const Args &...args){
bool flagged = false;
while(it != end){
if(flagged){
out << *it;
flagged = false;
}else{
if(*it == '/'){
flagged = true;
}else if(*it=='%') {
out<<t;
print(out, ++it, end, args...);
break;
}else{
out << *it;
}
}
++it;
}
}
}
//to handle case of no arguments
void print(std::ostream &out, const std::string &pattern){
out << pattern;
}
template<typename ... Args>
void print(std::ostream &out, const std::string &pattern, const Args &...args){
printpriv::print(out, pattern.begin(), pattern.end(), args...);
}
int main() {
print(std::cout, "Hello, I am a % and my name is %.\n", "dog", "capybara");
print(std::cout, "There are % % here.\n", 32, std::string("capybaras"));
print(std::cout, "There are no arguments here.\n");
print(std::cout, "I am 80/% sure that this will work.", 10); //at least one argument is needed to prevent calling the version that just passes through the pattern to the output stream
return 0;
}
</code></pre>
<p>In this code, I have these primary concerns but I am also interested in a standard code review:</p>
<ul>
<li>There is a huge amount of code duplication between the two <code>privprint::print</code> overloads to handle parsing the input pattern, bur I don't see any good way to avoid it.</li>
<li>The <code>privprint</code> namespace stores two functions that the main <code>print</code> method uses internally in addition to a <code>using</code> declaration. This isn't ideal because I consider the content of this namespace to be an implementation detail of the <code>print</code> function, so it should not be accessible to the user. Adding "priv" in the name is a decent way to warn other programmers who may work with this code, but something that the compiler enforces would be ideal. My instinct is to put the using declaration and the function templates that are in <code>privprint</code> into <code>print</code>'s namespace, but C++ does not allow function templates to be in a function's namespace (nor does it seem to allow any templates at all, which breaks all of my usual ways of getting around this function restriction, like a functor type or a lambda). </li>
<li>The implementation here considers a mis-matched number of un-escaped <code>%</code>s and arguments to substitute to be undefined behavior, but it would be better if it were a compile-time error when the string is available. I could make it a run-time error, but that would add run-time cost and thus violate C++'s philosophy of preferring undefined behavior to increased run-time cost. Despite this, I don't see any good way of allowing the templates to parse the string at run time. I suspect that this is possible however by making some use of <code>constexpr</code>. This point is why a template-meta-programming tag is on this question.</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T04:20:15.940",
"Id": "438143",
"Score": "0",
"body": "Your English documentation says that `\\ ` is the escape character, but your code and your unit tests both indicate that `/` is the escape character."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T04:22:01.130",
"Id": "438144",
"Score": "0",
"body": "@Quuxplusone Oops. It's fixed now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T04:53:21.573",
"Id": "438146",
"Score": "4",
"body": "Do you know of the [fmt library](https://fmt.dev) that is likely to be standardized soon?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T14:24:46.937",
"Id": "438202",
"Score": "0",
"body": "@Incomputable: It did, actually => https://www.reddit.com/r/cpp/comments/cfk9de/201907_cologne_iso_c_committee_trip_report_the/ (though in a lightweight version)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T18:36:43.487",
"Id": "438237",
"Score": "0",
"body": "@MatthieuM., thanks for sharing the link, lots of useful info there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T19:25:27.063",
"Id": "438257",
"Score": "0",
"body": "@Incomputable: You can thank the multiple members of the committee who edited that post; it's simply the most accurate report of a C++ committee meeting I've ever seen."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T23:39:54.680",
"Id": "438282",
"Score": "0",
"body": "If you're going for `printf`-alike, why not use a doubled percent sign to indicate a literal `%`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T21:53:49.963",
"Id": "438566",
"Score": "0",
"body": "I have something similar but using streams. But here is a set of tests to validate that you are printing the values correctly as specified by the printf() format string specification. https://github.com/Loki-Astari/ThorsIOUtil/blob/master/src/ThorsIOUtil/test/testlist.h"
}
] |
[
{
"body": "<h1>General design</h1>\n\n<p>Currently, your function is defined to have \"undefined behavior\" if the number of arguments is wrong. This is sub-optimal. Checking is trivial in this case, so report the problem in some way instead of producing strange output.</p>\n\n<blockquote>\n <p>I could make it a run-time error, but that would add run-time cost and\n thus violate C++'s philosophy of preferring undefined behavior to\n increased run-time cost.</p>\n</blockquote>\n\n<p>No, in this case run-time checking incurs zero overload on valid input. Reporting the error on invalid input is much more efficient than outputting strange things.</p>\n\n<p>You are handling empty template parameter packs specially. This is unnecessary. And this makes calls like <code>print(\"80/%\")</code> produce the wrong result.</p>\n\n<p>It is advised to put your utilities in your own namespace with a unique name, and put the non-exposed parts in a nested <code>detail</code> namespace. (In C++20, we will be able to have fine-grained control over what to expose in a module.)</p>\n\n<p><code>print</code> should take a <code>std::string_view</code> instead of <code>const std::string&</code> to avoid unnecessary allocation. It would also be nice if the function is constrained to be SFINAE-friendly.</p>\n\n<p>Also, it would be nice if you make this into a I/O manipulator, so that it can be used like</p>\n\n<pre><code>std::cout << print(\"% * 80/% = %\", 5, 4) << '\\n';\n</code></pre>\n\n<h1>Code</h1>\n\n<p>Your code seems to be very conservative on the usage of spaces around braces. It will look nice if they don't squeeze together:</p>\n\n<pre><code>if (condition) {\n // ...\n} else {\n // ...\n}\n\nwhile (condition) {\n // ...\n}\n</code></pre>\n\n<p>The print code only needs <code><ostream></code>, not <code><iostream></code>.</p>\n\n<p>Your handling of escape sequences is a bit convoluted. A stray <code>/</code> at the end of the sequence should be <em>invalid</em>, not simply ignored.</p>\n\n<hr>\n\n<p>Here's my extended code:</p>\n\n<pre><code>// library\n\n#include <cassert>\n#include <ostream>\n#include <string_view>\n#include <tuple>\n#include <type_traits>\n\n// replace unicorn304 with your namespace\nnamespace unicorn304::detail {\n template <typename It>\n void print(std::ostream& os, It first, It last)\n {\n for (auto it = first; it != last; ++it) {\n switch (*it) {\n case '%':\n throw std::invalid_argument{\"too few arguments\"};\n case '/':\n ++it;\n if (it == last)\n throw std::invalid_argument{\"stray '/'\"};\n [[fallthrough]];\n default:\n os << *it;\n }\n }\n }\n\n template <typename It, typename T, typename... Args>\n void print(std::ostream& os, It first, It last,\n const T& arg, const Args&... args)\n {\n for (auto it = first; it != last; ++it) {\n switch (*it) {\n case '%':\n os << arg;\n return print(os, ++it, last, args...);\n case '/':\n ++it;\n if (it == last)\n throw std::invalid_argument{\"stray '/'\"};\n [[fallthrough]];\n default:\n os << *it;\n }\n }\n throw std::invalid_argument{\"too many arguments\"};\n }\n\n template <typename... Args>\n struct Printer {\n std::string_view format;\n std::tuple<const Args&...> args;\n };\n\n template <typename... Args, std::size_t... Is>\n void printer_helper(std::ostream& os, const Printer<Args...>& printer,\n std::index_sequence<Is...>)\n {\n print(os, printer.format.begin(), printer.format.end(),\n std::get<Is>(printer.args)...);\n }\n\n template <typename... Args>\n std::ostream& operator<<(std::ostream& os, const Printer<Args...>& printer)\n {\n printer_helper(os, printer, std::index_sequence_for<Args...>{});\n return os;\n }\n}\n\nnamespace unicorn304 {\n template <typename T, typename = void>\n struct is_ostreamable :std::false_type {};\n template <typename T>\n struct is_ostreamable<T, std::void_t<\n decltype(std::declval<std::ostream>() << std::declval<T>())>\n > :std::true_type {};\n template <typename T>\n inline constexpr bool is_ostreamable_v = is_ostreamable<T>::value;\n\n template <typename... Args,\n std::enable_if_t<std::conjunction_v<is_ostreamable<Args>...>, int> = 0>\n auto print(std::string_view format, const Args&... args)\n {\n return detail::Printer<Args...>{format, std::forward_as_tuple(args...)};\n }\n}\n</code></pre>\n\n<p>Example usage:</p>\n\n<pre><code>void print_test()\n{\n using unicorn304::print;\n\n std::cout << print(\"% * 80/% = %\\n\", 5, 4)\n << print(\"% son of %!\\n\", \"bob\", \"some klingon\")\n << print(\"slash is '//' percent is '/%'\\n\");\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T19:31:50.757",
"Id": "438258",
"Score": "0",
"body": "can you explain this std::declval<std::ostream>() << std::declval<T>() ? Also, can you make it c++11 compliant?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T23:48:09.297",
"Id": "438283",
"Score": "0",
"body": "@nomanpouigt `declval<T>()` is an function with return type `T&&`. It is used in unevaluated operands (e.g., inside `decltype`) to create an object of type `T` without requiring that `T` has a constructor. See https://stackoverflow.com/q/28532781."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T23:55:07.410",
"Id": "438284",
"Score": "0",
"body": "@nomanpouigt As for C++11, well, I didn't really think of that. That would make things a bit complicated, but in theory it should be doable. I don't feel like doing that now, though."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T06:38:26.827",
"Id": "225634",
"ParentId": "225630",
"Score": "8"
}
},
{
"body": "<h3>Shims are wonderful</h3>\n<p>I recommend using a shim to offload all the logic to a function manipulating a list (rather than a pack) of arguments. As a bonus, you'll also be able to push the bulk of the implementation into a <code>.cpp</code> file.</p>\n<p>Essentially, your goal is to invoke:</p>\n<pre><code>namespace details {\n\nclass Argument {\npublic:\n virtual void print(std::ostream& out) const = 0;\nprotected:\n ~Argument() = default;\n};\n\nvoid print_impl_inner(\n std::ostream& out,\n std::string_view format,\n std::span<Argument const*> arguments\n);\n</code></pre>\n<p>This is done by creating a shim for each argument:</p>\n<pre><code>template <typename T>\nclass ArgumentT final : public Argument {\npublic:\n explicit ArgumentT(T const& t): mData(t) {}\n\n void print(std::ostream& out) const final { out << mData; }\n\nprivate:\n T const& mData;\n};\n\ntemplate <typename T>\nArgumentT<T> make_argument(T const& t) { return ArgumentT<T>(t); }\n</code></pre>\n<p>And then automating the creation and passing of the shims:</p>\n<pre><code>template <typename... Args>\nvoid print_impl_outer(\n std::ostream& out,\n std::string_view format,\n Args const&... args\n)\n{\n Arguments const* const array[sizeof...(args)] =\n { static_cast<Argument const*>(&args)... };\n print_impl_inner(out, format, array);\n}\n\n} // namespace details\n\ntemplate <typename... Args>\nvoid print(\n std::ostream& out,\n std::string_view format,\n Args&&... args\n)\n{\n details::print_impl_outer(out, format,\n details::make_argument(std::forward<Args>(args))...);\n}\n</code></pre>\n<p>Thus the user interface is this variadic template <code>print</code> function, however the actual implementation is done in <code>details::print_impl_inner</code>, which is only declared in the header.</p>\n<p>Then, in a <code>.cpp</code> file:</p>\n<pre><code>void details::print_impl_inner(\n std::ostream& out,\n std::string_view format,\n std::span<Argument const*> arguments\n)\n{\n std::size_t a = 0;\n\n for (std::size_t i = 0, max = format.size(); i != max; ++i) {\n switch (format[i]) {\n case '%':\n if (a == arguments.size()) {\n throw std::invalid_argument{"Too few arguments"};\n }\n arguments[a]->print(out);\n ++a;\n break;\n case '\\\\':\n ++i;\n if (i == max) {\n throw std::invalid_argument{\n "Invalid format string: stray \\\\ at end of string"};\n }\n [[fallthrough]];\n default:\n os << format[i];\n }\n }\n}\n</code></pre>\n<p>Note: if you do not have access to <code>std::span</code>, you can use <code>gsl::span</code> with minor adaptations.</p>\n<h3>Extensibility</h3>\n<p>The beauty of this architecture is dual:</p>\n<ul>\n<li>You can easily improve the <code>format</code> scan pass and printing without any guilt at "polluting" the header.</li>\n<li>You can easily implement <em>indexed</em> access to the arguments, that is <code>%N</code> meaning print the N-th argument.</li>\n<li>You can easily specialize the printers for a specific subset of arguments, by adding multiple <code>make_argument</code> overloads returning dedicated printers.</li>\n</ul>\n<p>For example, consider implementing a Python-like format language:</p>\n<pre><code>print(std::cout, "Hello {1:<12}, I'm {0:x} years old", my_age, your_name);\n</code></pre>\n<p>Where 1 and 0 are the indexes and whatever is right of <code>:</code> is a specific format request (here alignment and width).</p>\n<p>With this shim implementation, it should be relatively straightforward, and the header will remain lightweight.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T17:25:41.450",
"Id": "438221",
"Score": "0",
"body": "Quite nice. Still, a slightly more complicated implementation, separating the array of formatters (compile-time-constant) from the array of arguments (dynamic) might be better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T17:48:26.987",
"Id": "438230",
"Score": "0",
"body": "@Deduplicator: I think I see where this is going, essentially have an array of pointer-to-function and an array of `void const*`, however I am not sure how helpful it would be."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T18:25:26.260",
"Id": "438235",
"Score": "0",
"body": "Well, if there are only two arguments or less, it doesn't matter much at all. If there are more, having them as statically allocated constants reduces the needed work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T18:31:41.667",
"Id": "438236",
"Score": "1",
"body": "@Deduplicator: Possibly, though I am not sure it would make a big difference compared to the cost of parsing (the format string) + formatting (the arguments). I'd rather keep it tidy unless proven to be a bottle-neck, and focus on improving the parsing/formatting performance."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T15:12:06.587",
"Id": "225655",
"ParentId": "225630",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "225634",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T03:17:17.313",
"Id": "225630",
"Score": "9",
"Tags": [
"c++",
"formatting",
"template",
"template-meta-programming",
"variadic"
],
"Title": "`printf` improvement with C++ variadic templates"
}
|
225630
|
<p>Can you please suggest how below code can be optimize? It takes around 2 minutes in Windows and 4 plus minutes in Excel 2016 for Mac.
I think I will have to use write once method, accumulating the inserts and write all at last but I am not getting the starting point.</p>
<p>There are initially 5718 rows and after the inserts row size is 31,003.</p>
<pre><code>Function SplitDescAndProcessRateType(ByRef wsData As Worksheet, ByRef wsConv As Worksheet, ByRef exColIndx() As Integer, ByVal bookName As String, _
ByRef rMessage As String) As Boolean
Dim descColIndx As Integer, lCol As Integer, rateColIndx As Integer, eqColIndx As Integer
Dim desc As String, weight2 As String, price As String, desc1 As String, bags2 As String, container2 As String
Dim lRow As Long, i As Long, iIndx As Long
Dim success As Boolean
Dim eqDesc() As String, equipments() As String
With application
.ScreenUpdating = False
.DisplayAlerts = False
.EnableEvents = False
.Calculation = xlCalculationAutomatic
End With
GetEquipmentDesc wsConv, eqDesc, equipments
descColIndx = FindDescColumnIndex(wsData, lCol)
rateColIndx = descColIndx + 1
eqColIndx = rateColIndx + 1
If descColIndx > 0 Then
With wsData
.Columns(rateColIndx).Resize(, 2).EntireColumn.Insert 'Bags
.Cells(1, 11).Value = "carrier_org_id"
.Cells(1, 15).Value = "Container"
.Cells(1, 16).Value = "Weight"
.Cells(1, 17).Value = "Bags"
.Cells(1, descColIndx).Value = "Descr"
.Cells(1, rateColIndx).Value = "ratetype"
.Cells(1, rateColIndx + 1).Value = "equipment_type"
.Cells(1, rateColIndx + 2).Value = "price"
lRow = .Cells(.Rows.Count, 1).End(xlUp).Row
lCol = lCol + 2
i = 2
Do While i <= lRow
desc = .Cells(i, descColIndx).Value
desc1 = .Cells(i, 18).Value
weight2 = .Cells(i, 20).Value
price = .Cells(i, 26).Value
bags2 = .Cells(i, 21).Value
container2 = .Cells(i, 19).Value
If desc = "40ft DC or HC" Then
.Cells(i, descColIndx).EntireRow.Offset(1).Resize(2).Insert Shift:=xlDown
.Range(.Cells(i, 1), .Cells(i, lCol)).Copy
.Range(.Cells(i, 1).Offset(1), .Cells(i + 2, lCol)).PasteSpecial Paste:=xlPasteValues
.Cells(i, descColIndx).Value = desc1
.Cells(i + 1, descColIndx).Value = "40ft DC"
.Cells(i + 2, descColIndx).Value = "40ft HC"
.Cells(i + 1, 16).Value = weight2
.Cells(i + 2, 16).Value = weight2
.Cells(i, 25).HorizontalAlignment = xlRight
.Cells(i + 1, 25).Value = price
.Cells(i + 2, 25).Value = price
.Cells(i, rateColIndx).Value = "ratetype1"
.Cells(i + 1, rateColIndx).Value = "ratetype2"
.Cells(i + 2, rateColIndx).Value = "ratetype2"
.Cells(i, eqColIndx).Value = GetEquipmentType(eqDesc, equipments, desc1)
.Cells(i + 1, eqColIndx).Value = GetEquipmentType(eqDesc, equipments, "40ft DC")
.Cells(i + 2, eqColIndx).Value = GetEquipmentType(eqDesc, equipments, "40ft HC")
iIndx = 2
ElseIf desc <> desc1 Then
.Cells(i, descColIndx).EntireRow.Offset(1).Resize(1).Insert Shift:=xlDown
.Range(.Cells(i, 1), .Cells(i, lCol)).Copy
.Range(.Cells(i, 1).Offset(1), .Cells(i + 1, lCol)).PasteSpecial Paste:=xlPasteValues
.Cells(i, descColIndx).Value = desc1
.Cells(i + 1, 15).Value = container2
.Cells(i + 1, 16).Value = weight2
.Cells(i + 1, 17).Value = bags2
.Cells(i, rateColIndx).Value = "ratetype1"
.Cells(i + 1, rateColIndx).Value = "ratetype2"
.Cells(i, eqColIndx).Value = GetEquipmentType(eqDesc, equipments, desc1)
.Cells(i + 1, eqColIndx).Value = GetEquipmentType(eqDesc, equipments, desc)
.Cells(i + 1, 25).Value = price
iIndx = 1
Else
.Cells(i, eqColIndx).Value = GetEquipmentType(eqDesc, equipments, desc1)
End If
i = i + 1 + iIndx
lRow = lRow + iIndx
iIndx = 0
Loop
.Columns(26).Delete
lCol = .Cells(1, .Columns.Count).End(xlToLeft).Column + 1
.Cells(1, lCol).Value = "additional_notes"
.Cells(2, lCol).Formula = "=IF(OR(OR(R2 = ""20ft DC"", R2 = ""40ft DC""),R2 = ""40ft HC""),"""",CONCATENATE(P2,""mt "",Q2,R2))"
.Cells(2, lCol).AutoFill Destination:=.Range(.Cells(2, lCol), .Cells(lRow, lCol))
.Columns(lCol).Calculate
.Columns(lCol).Value = .Columns(lCol).Value
.Range(.Cells(2, 16), .Cells(lRow, 16)).HorizontalAlignment = xlRight
.Range(.Cells(2, 17), .Cells(lRow, 17)).HorizontalAlignment = xlRight
.Range(.Cells(2, 21), .Cells(lRow, 21)).HorizontalAlignment = xlRight
End With
If i >= lRow Then
success = True
rMessage = rMessage & vbNewLine & "- Step 2 is complete."
Else
rMessage = rMessage & vbNewLine & "- Step 2: could not be completed"
End If
Else
rMessage = rMessage & vbNewLine & "- Step 2: Descr2 column not found"
End If
With application
.ScreenUpdating = True
.DisplayAlerts = True
.EnableEvents = True
.Calculation = xlCalculationAutomatic
End With
SplitDescAndProcessRateType = success
End Function
</code></pre>
<p>FindDescColumnIndex, GetEquipmentDesciption and GetEquipmentTypeDesciption are helper functions. There are only around 20 rows in the array and the problem is not in these functions.</p>
<p>EDIT: I have included all function code lines for completeness. The function works with 5718 rows and 26 columns in wsData sheet and produces 31,003 rows in the same sheet.
Most of the 5718 rows are either desc = "40ft DC or HC" or desc <> desc1 so there are heavy use of insert:</p>
<pre><code>.Cells(i, descColIndx).EntireRow.Offset(1).Resize(2).Insert Shift:=xlDown
.Range(.Cells(i, 1), .Cells(i, lCol)).Copy
.Range(.Cells(i, 1).Offset(1), .Cells(i + 2, lCol)).PasteSpecial Paste:=xlPasteValues
</code></pre>
<p>In my opinion, if I can write the above lines in another way, either using Range Union and writing the Range at once at last, the code will be much fast. I am looking for how I can Union the range (for the inserts) and appreciate if someone can provide some pointer.</p>
<p>Thanks</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T05:52:47.573",
"Id": "438149",
"Score": "0",
"body": "Welcome to Code Review. This question is a bit of a code dump. Please tell us more about the motivation for writing this code, what this code accomplishes, and what the inputs and results are. See [ask]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T06:43:39.327",
"Id": "438153",
"Score": "0",
"body": "The question has been edited to provide more information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T20:28:57.400",
"Id": "438274",
"Score": "0",
"body": "Can you provide some sample data and a \"TestWithSampleData\" that will call your function? These details will give reviews enough information to verify their own ideas and ensure you're getting good advice. Additionally, if you can provide \"stub\" routines for `GetEquipmentDesc`, `FindDescColumnIndex`, and `GetEquipmentType` that will make your submission above \"complete and verifiable\". (Simple returns of static values is just fine, those helper functions don't need to be functional.)"
}
] |
[
{
"body": "<p>I am going to provide the solution I have found (so that it be helpful for someone) and answers my own question:</p>\n\n<p>The solution is by use of Array and not doing insert, reading and writing cells in the existing sheet. Now the code takes around 35 seconds (to process 5718 rows and create 31,003 rows) instead of 2 minutes, a huge improvement. Important steps are commented in the code below: </p>\n\n<pre><code>With wsData\n .Columns(rateColIndx).Resize(, 2).EntireColumn.Insert 'Bags\n .Cells(1, 11).Value = \"carrier_org_id\"\n .Cells(1, 15).Value = \"Container\"\n .Cells(1, 16).Value = \"Weight\"\n .Cells(1, 17).Value = \"Bags\"\n .Cells(1, descColIndx).Value = \"Descr\"\n .Cells(1, rateColIndx).Value = \"ratetype\"\n .Cells(1, rateColIndx + 1).Value = \"equipment_type\"\n .Cells(1, rateColIndx + 2).Value = \"price\"\n lRow = .Cells(.Rows.Count, 1).End(xlUp).Row\n lCol = lCol + 2\n i = 2\n .Range(.Cells(1, 1), .Cells(1, lCol)).Copy\n wsData2.Cells(1, 1).PasteSpecial Paste:=xlPasteValues\n rIndxWsTemp = 2\n 'Load all data in a variant Array\n Arr = .Range(.Cells(1, 1), .Cells(lRow, lCol))\n\n ubArr = UBound(Arr, 1)\n Do While i <= ubArr\n desc = Arr(i, descColIndx)\n desc1 = Arr(i, 18)\n weight2 = Arr(i, 20)\n price = Arr(i, 26)\n bags2 = Arr(i, 21)\n container2 = Arr(i, 19)\n If desc = \"40ft DC or HC\" Then\n 'Do not do insert, reading and writing cells in the existing sheet, instead, use main data array (Arr) and helper/temporary array\n 'for reading and writing. Note the Array slicing Arr(i,0)\n ArrTemp = Arr(i, 0)\n 'Do processing in a temp array\n ArrTemp1 = ArrTemp\n ArrTemp2 = ArrTemp1\n ArrTemp(1, descColIndx) = desc1\n ArrTemp1(1, descColIndx) = \"40ft DC\"\n ArrTemp2(1, descColIndx) = \"40ft HC\"\n ArrTemp1(1, 16) = weight2\n ArrTemp2(1, 16) = weight2\n ArrTemp1(1, 25) = price\n ArrTemp2(1, 25) = price\n ArrTemp(1, rateColIndx) = \"ratetype1\"\n ArrTemp1(1, rateColIndx) = \"ratetype2\"\n ArrTemp2(1, rateColIndx) = \"ratetype2\"\n ArrTemp(1, eqColIndx) = GetEquipmentType(eqDesc, equipments, desc1)\n ArrTemp1(1, eqColIndx) = GetEquipmentType(eqDesc, equipments, \"40ft DC\")\n ArrTemp2(1, eqColIndx) = GetEquipmentType(eqDesc, equipments, \"40ft HC\")\n 'Use another array ArrComb so that we can write at once to a new sheet\n ReDim ArrComb(1 To 3, 1 To lCol)\n For m = 1 To 1\n For n = 1 To lCol\n ArrComb(m, n) = ArrTemp(m, n)\n ArrComb(m + 1, n) = ArrTemp1(m, n)\n ArrComb(m + 2, n) = ArrTemp2(m, n)\n Next\n Next\n 'Write to a new sheet instead of inserting to existing\n With wsData2\n .Range(.Cells(rIndxWsTemp, 1), .Cells(rIndxWsTemp + 2, lCol)).Value = ArrComb\n End With\n rIndxWsTemp = rIndxWsTemp + 3\n ElseIf desc <> desc1 Then\n ArrTemp = .Range(.Cells(i, 1), .Cells(i, lCol)).Value\n ArrTemp1 = ArrTemp\n ArrTemp(1, descColIndx) = desc1\n ArrTemp1(1, 15) = container2\n ArrTemp1(1, 16) = weight2\n ArrTemp1(1, 17) = bags2\n ArrTemp(1, rateColIndx) = \"ratetype1\"\n ArrTemp1(1, rateColIndx) = \"ratetype2\"\n ArrTemp(1, eqColIndx) = GetEquipmentType(eqDesc, equipments, desc1)\n ArrTemp1(1, eqColIndx) = GetEquipmentType(eqDesc, equipments, desc)\n ArrTemp1(1, 25) = price\n ReDim ArrComb(1 To 2, 1 To lCol)\n For m = 1 To 1\n For n = 1 To lCol\n ArrComb(m, n) = ArrTemp(m, n)\n ArrComb(m + 1, n) = ArrTemp1(m, n)\n Next\n Next\n With wsData2\n .Range(.Cells(rIndxWsTemp, 1), .Cells(rIndxWsTemp + 1, lCol)).Value = ArrComb\n End With\n rIndxWsTemp = rIndxWsTemp + 2\n End If\n i = i + 1\n Loop\nEnd With\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-09T02:41:03.453",
"Id": "227699",
"ParentId": "225631",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T04:02:08.330",
"Id": "225631",
"Score": "-1",
"Tags": [
"vba",
"excel"
],
"Title": "Excel VBA - How to optimize this code with a lot of inserts"
}
|
225631
|
<p>I have two dataframes: One contains of name and year.</p>
<pre><code>**name** **year**
ram 1873
rob 1900
</code></pre>
<p>Second contains names and texts.</p>
<pre><code>**name** **text**
ram A good kid
ram He was born on 1873
rob He is tall
rob He is 12 yrs old
rob His father died at 1900
</code></pre>
<p>I want to find the indices of the rows of second dataframe where the name of second dataframe matches with name of the first df and the text in second df contains the year in first df.</p>
<p>The result should be indices 1,4</p>
<p>My Code:</p>
<pre><code>ind_list = []
for ind1, old in enumerate(A.name):
for ind2, new in enumerate(B.name):
if A.name[ind1] == B.name[ind2]:
if A.year[ind1] in B.text[ind2]:
ind_list.append(ind2)
</code></pre>
<p>Any better way to write the above code?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T10:20:26.110",
"Id": "438185",
"Score": "1",
"body": "I have added the _python_ tag, this one should always be provided as companion of a _python-*_ tag."
}
] |
[
{
"body": "<p>Here is what we start with.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>In [16]: df1\nOut[16]:\n name year\n0 ram 1873\n1 rob 1900\n\nIn [17]: df2\nOut[17]:\n name text\n0 ram A good kid\n1 ram He was born on 1873\n2 rob He is tall\n3 rob He is 12 yrs old\n4 rob His father died at 1900\n</code></pre>\n\n<p>What you probably want to do is merge your two DataFrames. If you're familiar with SQL, this is just like a table join. The <code>pd.merge</code> step essentially \"adds\" the columns from <code>df1</code> to <code>df2</code> by checking where the two DataFrames match on the column \"name\". Then, once you have the columns you want (\"year\" and \"text\") matching according to the \"name\" column, we apply the function <code>lambda x: str(x.year) in x.text</code> (which checks if the year is present in the text) across the rows (<code>axis=1</code>).</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>In [18]: cond = pd.merge(\n ...: left=df2,\n ...: right=df1,\n ...: how=\"left\",\n ...: left_on=\"name\",\n ...: right_on=\"name\",\n ...: ).apply(lambda x: str(x.year) in x.text, axis=1)\n</code></pre>\n\n<p>This gives us a Series which has the same index as your second DataFrame, and contains boolean values telling you if your desired condition is met or not.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>In [19]: cond\nOut[19]:\n0 False\n1 True\n2 False\n3 False\n4 True\ndtype: bool\n</code></pre>\n\n<p>Then, we filter your Series to where the condition is true, and give the index, optionally converting it to a list.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>In [20]: cond[cond].index\nOut[20]: Int64Index([1, 4], dtype='int64')\nIn [21]: cond[cond].index.tolist()\nOut[21]: [1, 4]\n</code></pre>\n\n<p>If all you need later on is to iterate over the indices you've gotten, <code>In [18]</code> and <code>In [20]</code> will suffice.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T14:24:51.187",
"Id": "438961",
"Score": "0",
"body": "Thanks.. this is good. But if I apply it for different data-frames the 1/3 rd of the total number of rows from cond dataframe is NaN. What could be the possible reason"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T00:31:34.967",
"Id": "439039",
"Score": "0",
"body": "I can't know for sure, but if, for example, `df2` contains names not present in `df1`, then those rows will probably get filled in with NaN during the join/merge. Depending of your use case, you might treat those cases differently, but if I interpret your question strictly, then replacing `str(x.year) in x.text` with `(str(int(x.year)) in x.text) if not pd.isnull(x.year) else False` would probably be the best way to go (converting the NaN to False so they don't appear in the final list of indices)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T02:02:28.013",
"Id": "225694",
"ParentId": "225637",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T07:15:28.533",
"Id": "225637",
"Score": "2",
"Tags": [
"python",
"python-3.x"
],
"Title": "compare different pandas dataframes to find matching rows"
}
|
225637
|
<p>This code is a solution for <a href="https://www.codechef.com/problems/TREEMX" rel="nofollow noreferrer">CodeChef's Tree MEX problem</a>: </p>
<blockquote>
<p>Minimum excludant (or MEX for short) of a collection of integers is
the smallest non-negative integer not present in the set.</p>
<p>You have a tree <span class="math-container">\$ T \$</span> with <span class="math-container">\$n\$</span> vertices. Consider an ordering <span class="math-container">\$ P=(v_1,\ldots,v_n) \$</span>
of vertices of <span class="math-container">\$T\$</span>. We construct a sequence <span class="math-container">\$A(P)=(a_1,\ldots,a_n)\$</span> using the
following process:</p>
<ul>
<li>Set all <span class="math-container">\$a_i=−1\$</span>.</li>
<li>Process vertices in order <span class="math-container">\$v_1,\ldots,v_n\$</span>. For the current vertex <span class="math-container">\$v_i \$</span> set <span class="math-container">\$a_i=\operatorname{MEX}(a_{u_1},\ldots,a_{u_k})\$</span>, where <span class="math-container">\$u_1,\ldots,u_k\$</span> is the set of neighbours of
<span class="math-container">\$v_i\$</span>. </li>
</ul>
<p>For instance, let <span class="math-container">\$n=3\$</span> and <span class="math-container">\$T\$</span> be the tree with edges <span class="math-container">\$(1,2)\$</span> and
<span class="math-container">\$(2,3)\$</span>. Then, for the ordering <span class="math-container">\$P=(1,2,3)\$</span> we obtain the sequence
<span class="math-container">\$A(P)=(0,1,0)\$</span>, while for the ordering <span class="math-container">\$P=(2,3,1)\$</span> we obtain
<span class="math-container">\$A(P)=(1,0,1)\$</span>.</p>
<p>Consider all <span class="math-container">\$n!\$</span> orders <span class="math-container">\$P\$</span>. How many different sequences
<span class="math-container">\$A(P)\$</span> can we obtain? Print the answer modulo <span class="math-container">\$10^9+7\$</span>.</p>
</blockquote>
<hr>
<p>I have created a graph from list of tuples and then calculated <code>mex</code> values for each permutation.</p>
<pre><code>Ex: 3 # 3 vertices
1 2 # (1,2) edge
2 3 # (2,3) edge
</code></pre>
<p>permutations(1,2,3) ==> we get 6 combinations</p>
<p>For 6 combinations we will get 6 values. I need to print distinct count of that 6 values.</p>
<p><strong>Code:</strong></p>
<pre><code># https://www.codechef.com/problems/TREEMX
from collections import defaultdict
from itertools import permutations
class Graph:
""" Graph is data structure(directed). """
def __init__(self, connections):
""" Initializing graph with set as default value. """
self._graph = defaultdict(set)
self.add_connections(connections)
def add_connections(self, connections):
""" Add connections(list of tupules) to graph. """
for node1, node2 in connections:
self.add(node1,node2)
def add(self, node1, node2):
""" Add node1 and node2 to graph which is initialized with set by default. """
self._graph[node1].add(node2)
self._graph[node2].add(node1)
def get_graph(self):
return dict(self._graph)
def mex(arr_set):
mex = 0
while mex in arr_set:
mex+=1
return mex
def process(graph, order):
a_p = [-1] * len(order)
for el in order:
a_p[el-1] = mex([a_p[u-1] for u in graph[el]])
return a_p
t = int(input())
for _ in range(t):
v = int(input())
e = []
for i in range(v-1):
e.append(tuple(map(int, input().split())))
g = Graph(e)
all_vertices = {s for i in e for s in i}
result = []
for p in permutations(all_vertices, v):
out = process(g.get_graph(), p)
result.append(out) if out not in result else None
print(len(result) % ((10**9)+7))
</code></pre>
<p><strong>Constraints:</strong></p>
<ul>
<li><span class="math-container">\$1≤T≤10\$</span></li>
<li><span class="math-container">\$1≤n≤10^5\$</span></li>
<li><span class="math-container">\$1≤u_i,v_i≤n\$</span></li>
<li><span class="math-container">\$u_i≠v_i\$</span></li>
</ul>
<p>How can I optimize the code, to get rid of the "time limit exceeded" error?</p>
|
[] |
[
{
"body": "<blockquote>\n<pre><code> for p in permutations(all_vertices, v):\n</code></pre>\n</blockquote>\n\n\n\n<blockquote>\n <ul>\n <li><span class=\"math-container\">\\$1≤n≤10^5\\$</span></li>\n </ul>\n</blockquote>\n\n<p>Well, <span class=\"math-container\">\\$(10^5)! \\approx \\left(\\frac{10^5}{e}\\right)^{10^5} \\approx 10^{35657}\\$</span> so it's a waste of time trying to optimise this. The only thing to do is go back to the drawing board and spend a few hours thinking about the mathematics. At best the code you've written will serve to analyse all trees up to a small number of vertices (maybe 7 or 8) to see what patterns you can spot which can help to guide you in the right direction.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T15:48:54.230",
"Id": "226046",
"ParentId": "225640",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T08:46:49.943",
"Id": "225640",
"Score": "3",
"Tags": [
"python",
"performance",
"algorithm",
"time-limit-exceeded",
"graph"
],
"Title": "CodeChef's Tree MEX (Minimum Excludant) challenge"
}
|
225640
|
<p>I took quite some time to implement a fully standard-conforming <code>std::optional</code> in C++17. It turns out more sophisticated than I initially thought. My code is just below 1000 lines (excluding empty lines), and I have tested the functions extensively.</p>
<p>There have been some attempts to implement <code>std::optional</code> on Code Review. A simple <a href="https://codereview.stackexchange.com/search?q=%5Bc%2B%2B%5D+%5Breinventing-the-wheel%5D+optional+is%3Aquestion">search</a> brings up two:</p>
<ul>
<li><p><a href="https://codereview.stackexchange.com/q/158311">Reinventing std::optional</a> - far from standard conforming;</p></li>
<li><p><a href="https://codereview.stackexchange.com/q/216669">`std::optional` under C++14 v1</a> - nice in general, but doesn't implement the interaction between <code>constexpr</code> and triviality correctly.</p></li>
</ul>
<p>Some facts that complicate the implementation:</p>
<ul>
<li><p>Many operations are <code>constexpr</code> friendly. With <code>constexpr</code>, the <code>aligned_storage</code> + explicit construction / destruction technique becomes useless. The standard is effectively asking us to use a union. The fact that the <code>constexpr</code>-ness on the copy / move operations depends on the triviality of the corresponding operations on the value type is a clear evidence because that's exactly how unions work.</p></li>
<li><p>The special member functions conditionally get defined as deleted / participate in overload resolution. Since special member functions cannot be templates, SFINAE cannot be used, and the only way to implement this that I can think of is to write a chain of base classes and use class template specialization, and then use <code>= default</code> to "inherit" the (possibly deleted) special member functions.</p></li>
</ul>
<p>I used <a href="https://timsong-cpp.github.io/cppwp/n4659" rel="nofollow noreferrer">N4659</a> (C++17 final draft) as a reference. The relevant parts are <a href="https://timsong-cpp.github.io/cppwp/n4659/optional" rel="nofollow noreferrer">[optional]</a>, <a href="https://timsong-cpp.github.io/cppwp/n4659/unord.hash" rel="nofollow noreferrer">[unord.hash]</a>, and <a href="https://timsong-cpp.github.io/cppwp/n4659/depr.func.adaptor.binding" rel="nofollow noreferrer">[depr.func.adaptor.binding]</a> (for the deprecated <code>std::hash<...>::result_type</code> and <code>std::hash<...>::argument_type</code>).</p>
<p>Except for <code>std::hash</code>, all functionalities are provided in the <code>my_std</code> namespace. As you can see, basically everything is boilerplate code and the actual code is almost zero.</p>
<pre><code>// C++17 std::optional implementation
#ifndef INC_OPTIONAL_HPP_9AEkHPjv56
#define INC_OPTIONAL_HPP_9AEkHPjv56
#include <cassert>
#include <exception>
#include <initializer_list>
#include <memory> // for std::destroy_at
#include <typeindex> // for std::hash
#include <typeinfo>
#include <type_traits>
#include <utility>
namespace my_std {
// [optional.optional], class template optional
template <class T>
class optional;
// [utility.syn], [in-place construction]
struct in_place_t {
explicit in_place_t() = default;
};
inline constexpr in_place_t in_place{};
// [optional.nullopt], no-value state indicator
struct nullopt_t {
constexpr explicit nullopt_t(int) {}
};
inline constexpr nullopt_t nullopt{0};
// [optional.bad.access], class bad_optional_access
class bad_optional_access :public std::exception {
public:
bad_optional_access() = default;
};
// [optional.relops], relational operators
template <class T, class U>
constexpr bool operator==(const optional<T>&, const optional<U>&);
template <class T, class U>
constexpr bool operator!=(const optional<T>&, const optional<U>&);
template <class T, class U>
constexpr bool operator<(const optional<T>&, const optional<U>&);
template <class T, class U>
constexpr bool operator>(const optional<T>&, const optional<U>&);
template <class T, class U>
constexpr bool operator<=(const optional<T>&, const optional<U>&);
template <class T, class U>
constexpr bool operator>=(const optional<T>&, const optional<U>&);
// [optional.nullops], comparison with nullopt
template <class T>
constexpr bool operator==(const optional<T>&, nullopt_t) noexcept;
template <class T>
constexpr bool operator==(nullopt_t, const optional<T>&) noexcept;
template <class T>
constexpr bool operator!=(const optional<T>&, nullopt_t) noexcept;
template <class T>
constexpr bool operator!=(nullopt_t, const optional<T>&) noexcept;
template <class T>
constexpr bool operator<(const optional<T>&, nullopt_t) noexcept;
template <class T>
constexpr bool operator<(nullopt_t, const optional<T>&) noexcept;
template <class T>
constexpr bool operator>(const optional<T>&, nullopt_t) noexcept;
template <class T>
constexpr bool operator>(nullopt_t, const optional<T>&) noexcept;
template <class T>
constexpr bool operator<=(const optional<T>&, nullopt_t) noexcept;
template <class T>
constexpr bool operator<=(nullopt_t, const optional<T>&) noexcept;
template <class T>
constexpr bool operator>=(const optional<T>&, nullopt_t) noexcept;
template <class T>
constexpr bool operator>=(nullopt_t, const optional<T>&) noexcept;
// [optional.comp.with.t], comparison with T
template <class T, class U>
constexpr bool operator==(const optional<T>&, const U&);
template <class T, class U>
constexpr bool operator==(const U&, const optional<T>&);
template <class T, class U>
constexpr bool operator!=(const optional<T>&, const U&);
template <class T, class U>
constexpr bool operator!=(const U&, const optional<T>&);
template <class T, class U>
constexpr bool operator<(const optional<T>&, const U&);
template <class T, class U>
constexpr bool operator<(const U&, const optional<T>&);
template <class T, class U>
constexpr bool operator>(const optional<T>&, const U&);
template <class T, class U>
constexpr bool operator>(const U&, const optional<T>&);
template <class T, class U>
constexpr bool operator<=(const optional<T>&, const U&);
template <class T, class U>
constexpr bool operator<=(const U&, const optional<T>&);
template <class T, class U>
constexpr bool operator>=(const optional<T>&, const U&);
template <class T, class U>
constexpr bool operator>=(const U&, const optional<T>&);
// [optional.specalg], specialized algorithms
template <class T>
std::enable_if_t<std::is_move_constructible_v<T> && std::is_swappable_v<T>>
swap(optional<T>& x, optional<T>& y) noexcept(noexcept(x.swap(y)))
{
x.swap(y);
}
template <class T>
constexpr optional<std::decay_t<T>> make_optional(T&& v)
{
return optional<std::decay_t<T>>(std::forward<T>(v));
}
template <class T, class... Args>
constexpr optional<T> make_optional(Args&&... args)
{
return optional<T>(in_place, std::forward<Args>(args)...);
}
template <class T, class U, class... Args>
constexpr optional<T> make_optional(std::initializer_list<U> il, Args&&... args)
{
return optional<T>(in_place, il, std::forward<Args>(args)...);
}
}
namespace std {
// [optional.hash], hash support
template <class T>
struct hash<my_std::optional<T>>;
}
namespace my_std::detail {
template <class T, class U>
struct is_cv_same :std::is_same<
std::remove_const_t<std::remove_volatile_t<T>>,
std::remove_const_t<std::remove_volatile_t<U>>
> { };
template <class T, class U>
inline constexpr bool is_cv_same_v = is_cv_same<T, U>::value;
template <class T>
struct enable {
// constructors
template <class... Args>
using in_place = std::enable_if_t<std::is_constructible_v<T, Args...>, int>;
template <class U>
using conv_implicit =
std::enable_if_t<std::is_constructible_v<T, U&&> &&
!std::is_same_v<std::decay_t<U>, in_place_t> &&
!std::is_same_v<std::decay_t<U>, optional<T>> &&
std::is_convertible_v<U&&, T>, int>;
template <class U>
using conv_explicit =
std::enable_if_t<std::is_constructible_v<T, U&&> &&
!std::is_same_v<std::decay_t<U>, in_place_t> &&
!std::is_same_v<std::decay_t<U>, optional<T>> &&
!std::is_convertible_v<U&&, T>, int>;
template <class U>
static constexpr bool conv_common =
!std::is_constructible_v<T, optional<U>& > &&
!std::is_constructible_v<T, optional<U>&&> &&
!std::is_constructible_v<T, const optional<U>& > &&
!std::is_constructible_v<T, const optional<U>&&> &&
!std::is_convertible_v< optional<U>& , T> &&
!std::is_convertible_v< optional<U>&&, T> &&
!std::is_convertible_v<const optional<U>& , T> &&
!std::is_convertible_v<const optional<U>&&, T>;
template <class U>
using copy_conv_implicit =
std::enable_if_t<conv_common<U> &&
std::is_constructible_v<T, const U&> &&
std::is_convertible_v<const U&, T>, int>;
template <class U>
using copy_conv_explicit =
std::enable_if_t<conv_common<U> &&
std::is_constructible_v<T, const U&> &&
!std::is_convertible_v<const U&, T>, int>;
template <class U>
using move_conv_implicit =
std::enable_if_t<conv_common<U> &&
std::is_constructible_v<T, U&&> &&
std::is_convertible_v<U&&, T>, int>;
template <class U>
using move_conv_explicit =
std::enable_if_t<conv_common<U> &&
std::is_constructible_v<T, U&&> &&
!std::is_convertible_v<U&&, T>, int>;
// assignment
template <class U>
using conv_ass =
std::enable_if_t<!std::is_same_v<optional<T>, std::decay_t<U>> &&
!(std::is_scalar_v<T> &&
std::is_same_v<T, std::decay_t<U>>) &&
std::is_constructible_v<T, U> &&
std::is_assignable_v<T&, U>, int>;
template <class U>
static constexpr bool conv_ass_common = conv_common<U> &&
!std::is_assignable_v<T&, optional<U>& > &&
!std::is_assignable_v<T&, const optional<U>& > &&
!std::is_assignable_v<T&, optional<U>&&> &&
!std::is_assignable_v<T&, const optional<U>&&>;
template <class U>
using copy_conv_ass =
std::enable_if_t<conv_ass_common<U> &&
std::is_constructible_v<T, const U&> &&
std::is_assignable_v<T&, const U&>, int>;
template <class U>
using move_conv_ass =
std::enable_if_t<conv_ass_common<U> &&
std::is_constructible_v<T, U> &&
std::is_assignable_v<T&, U>, int>;
// emplace
template <class U, class... Args>
using emplace_ilist =
std::enable_if_t<
std::is_constructible_v<T, std::initializer_list<U>, Args...>
, int>;
};
// deal with destructor
// trivially destructible version
template <class T, bool = std::is_trivially_destructible_v<T>>
class destroy_base {
static_assert(std::is_object_v<T>, "[optional.optional]/3");
static_assert(std::is_destructible_v<T>, "[optional.optional]/3");
static_assert(!detail::is_cv_same_v<T, in_place_t>, "[optional.syn]/1");
static_assert(!detail::is_cv_same_v<T, nullopt_t>, "[optional.syn]/1");
public:
constexpr destroy_base() noexcept {}
~destroy_base() = default;
constexpr destroy_base(const destroy_base& rhs) = default;
constexpr destroy_base(destroy_base&& rhs) = default;
destroy_base& operator=(const destroy_base& rhs) = default;
destroy_base& operator=(destroy_base&& rhs) = default;
constexpr destroy_base(nullopt_t) noexcept {}
template <class... Args,
typename enable<T>::template in_place<Args...> = 0>
constexpr explicit destroy_base(in_place_t, Args&&... args)
:object(std::forward<Args>(args)...), contains{true}
{
}
template <class U, class... Args,
typename enable<T>::template in_place<std::initializer_list<U>&,
Args...> = 0>
constexpr explicit destroy_base(in_place_t, std::initializer_list<U> ilist,
Args&&... args)
:object(ilist, std::forward<Args>(args)...), contains{true}
{
}
constexpr bool has_value() const noexcept
{
return contains;
}
void reset() noexcept
{
destroy();
}
protected:
constexpr T* get() noexcept
{
return &object;
}
constexpr const T* get() const noexcept
{
return &object;
}
template <typename... Args>
void construct(Args&&... args)
{
assert(!has_value());
::new (get()) T(std::forward<Args>(args)...);
contains = true;
}
void destroy() noexcept
{
assert(has_value());
contains = false;
}
private:
union {
char dummy{'\0'};
T object;
};
bool contains{false};
};
// non-trivially destructible version
template <class T>
class destroy_base<T, false> {
static_assert(std::is_object_v<T>, "[optional.optional]/3");
static_assert(std::is_destructible_v<T>, "[optional.optional]/3");
static_assert(!detail::is_cv_same_v<T, in_place_t>, "[optional.syn]/1");
static_assert(!detail::is_cv_same_v<T, nullopt_t>, "[optional.syn]/1");
public:
constexpr destroy_base() noexcept {}
constexpr destroy_base(const destroy_base& rhs) = default;
constexpr destroy_base(destroy_base&& rhs) = default;
destroy_base& operator=(const destroy_base& rhs) = default;
destroy_base& operator=(destroy_base&& rhs) = default;
~destroy_base()
{
reset();
}
constexpr destroy_base(nullopt_t) noexcept {}
template <class... Args,
typename enable<T>::template in_place<Args...> = 0>
constexpr explicit destroy_base(in_place_t, Args&&... args)
:object(std::forward<Args>(args)...), contains{true}
{
}
template <class U, class... Args,
typename enable<T>::template in_place<std::initializer_list<U>&,
Args...> = 0>
constexpr explicit destroy_base(in_place_t, std::initializer_list<U> ilist,
Args&&... args)
:object(ilist, std::forward<Args>(args)...), contains{true}
{
}
constexpr bool has_value() const noexcept
{
return contains;
}
void reset() noexcept
{
if (has_value())
destroy();
}
protected:
constexpr T* get() noexcept
{
return &object;
}
constexpr const T* get() const noexcept
{
return &object;
}
template <typename... Args>
void construct(Args&&... args)
{
assert(!has_value());
::new (get()) T(std::forward<Args>(args)...);
contains = true;
}
void destroy() noexcept
{
assert(has_value());
std::destroy_at(get());
contains = false;
}
private:
union {
char dummy{'\0'};
T object;
};
bool contains{false};
};
template <class T>
class common_base :public destroy_base<T> {
public:
using destroy_base<T>::destroy_base;
constexpr common_base() = default;
constexpr common_base(const common_base&) = default;
constexpr common_base(common_base&&) = default;
common_base& operator=(const common_base&) = default;
common_base& operator=(common_base&&) = default;
constexpr T* operator->()
{
assert(*this);
return this->get();
}
constexpr const T* operator->() const
{
assert(*this);
return this->get();
}
constexpr T& operator*() &
{
assert(*this);
return *this->get();
}
constexpr const T& operator*() const &
{
assert(*this);
return *this->get();
}
constexpr T&& operator*() &&
{
return std::move(*this->get());
}
constexpr const T&& operator*() const &&
{
return std::move(*this->get());
}
constexpr explicit operator bool() const noexcept
{
return this->has_value();
}
protected:
// assign if has value, construct otherwise
template <typename U>
void assign(U&& arg)
{
if (this->has_value())
**this = std::forward<U>(arg);
else
this->construct(std::forward<U>(arg));
}
};
// deal with copy constructor
// trivially copy constructible version
template <class T, bool = std::is_copy_constructible_v<T>,
bool = std::is_trivially_copy_constructible_v<T>>
class copy_construct_base :public common_base<T> {
using Base = common_base<T>;
public:
using Base::Base;
constexpr copy_construct_base() = default;
constexpr copy_construct_base(const copy_construct_base& rhs) = default;
constexpr copy_construct_base(copy_construct_base&&) = default;
copy_construct_base& operator=(const copy_construct_base&) = default;
copy_construct_base& operator=(copy_construct_base&&) = default;
};
// non-trivially copy constructible version
template <class T>
class copy_construct_base<T, true, false> :public common_base<T> {
public:
using common_base<T>::common_base;
constexpr copy_construct_base() = default;
copy_construct_base(const copy_construct_base& rhs) // not constexpr
{
if (rhs)
this->construct(*rhs);
}
constexpr copy_construct_base(copy_construct_base&&) = default;
copy_construct_base& operator=(const copy_construct_base&) = default;
copy_construct_base& operator=(copy_construct_base&&) = default;
};
// non-copy constructible version
template <class T>
class copy_construct_base<T, false, false> :public common_base<T> {
public:
using common_base<T>::common_base;
constexpr copy_construct_base() = default;
copy_construct_base(const copy_construct_base&) = delete;
constexpr copy_construct_base(copy_construct_base&&) = default;
copy_construct_base& operator=(const copy_construct_base&) = default;
copy_construct_base& operator=(copy_construct_base&&) = default;
};
// deal with move constructor
// trivially move constructible version
template <class T, bool = std::is_move_constructible_v<T>,
bool = std::is_trivially_move_constructible_v<T>>
class move_construct_base :public copy_construct_base<T> {
using Base = copy_construct_base<T>;
public:
using Base::Base;
constexpr move_construct_base() = default;
constexpr move_construct_base(const move_construct_base&) = default;
constexpr move_construct_base(move_construct_base&& rhs)
noexcept(std::is_nothrow_move_constructible_v<T>) = default;
move_construct_base& operator=(const move_construct_base&) = default;
move_construct_base& operator=(move_construct_base&&) = default;
};
// non-trivially move constructible version
template <class T>
class move_construct_base<T, true, false> :public copy_construct_base<T> {
public:
using copy_construct_base<T>::copy_construct_base;
constexpr move_construct_base() = default;
constexpr move_construct_base(const move_construct_base&) = default;
move_construct_base(move_construct_base&& rhs) // not constexpr
noexcept(std::is_nothrow_move_constructible_v<T>)
{
if (rhs)
this->construct(std::move(*rhs));
}
move_construct_base& operator=(const move_construct_base&) = default;
move_construct_base& operator=(move_construct_base&&) = default;
};
// non-move constructible version
template <class T>
class move_construct_base<T, false, false> :public copy_construct_base<T> {
public:
using copy_construct_base<T>::copy_construct_base;
constexpr move_construct_base() = default;
constexpr move_construct_base(const move_construct_base&) = default;
move_construct_base(move_construct_base&& rhs) = delete;
move_construct_base& operator=(const move_construct_base&) = default;
move_construct_base& operator=(move_construct_base&&) = default;
};
// deal with copy assignment
// copy constructible and assignable version
template <class T, bool = (std::is_copy_constructible_v<T> &&
std::is_copy_assignable_v<T>)>
class copy_assign_base :public move_construct_base<T> {
using Base = move_construct_base<T>;
public:
using Base::Base;
constexpr copy_assign_base() = default;
constexpr copy_assign_base(const copy_assign_base&) = default;
constexpr copy_assign_base(copy_assign_base&&) = default;
copy_assign_base& operator=(const copy_assign_base& rhs)
{
if (rhs)
this->assign(*rhs);
else
this->reset();
return *this;
}
copy_assign_base& operator=(copy_assign_base&&) = default;
};
// non-(copy constructible and assignable) version
template <class T>
class copy_assign_base<T, false> :public move_construct_base<T> {
public:
using move_construct_base<T>::move_construct_base;
constexpr copy_assign_base() = default;
constexpr copy_assign_base(const copy_assign_base&) = default;
constexpr copy_assign_base(copy_assign_base&&) = default;
copy_assign_base& operator=(const copy_assign_base&) = delete;
copy_assign_base& operator=(copy_assign_base&&) = default;
};
// deal with move assignment
// move constructible and assignable version
template <class T, bool = (std::is_move_constructible_v<T> &&
std::is_move_assignable_v<T>)>
class move_assign_base :public copy_assign_base<T> {
using Base = copy_assign_base<T>;
public:
using Base::Base;
constexpr move_assign_base() = default;
constexpr move_assign_base(const move_assign_base&) = default;
constexpr move_assign_base(move_assign_base&&) = default;
move_assign_base& operator=(const move_assign_base&) = default;
move_assign_base& operator=(move_assign_base&& rhs)
noexcept(std::is_nothrow_move_assignable_v<T> &&
std::is_nothrow_move_constructible_v<T>)
{
if (rhs)
this->assign(std::move(*rhs));
else
this->reset();
return *this;
}
};
// non-(move constructible and assignable) version
template <class T>
class move_assign_base<T, false> :public copy_assign_base<T> {
public:
using copy_assign_base<T>::copy_assign_base;
constexpr move_assign_base() = default;
constexpr move_assign_base(const move_assign_base&) = default;
constexpr move_assign_base(move_assign_base&&) = default;
move_assign_base& operator=(const move_assign_base&) = default;
move_assign_base& operator=(move_assign_base&&) = delete;
};
}
namespace my_std {
template <class T>
class optional :public detail::move_assign_base<T> {
using Base = detail::move_assign_base<T>;
using Enable = detail::enable<T>;
public:
using value_type = T;
using Base::Base;
optional() = default;
~optional() = default;
optional(const optional&) = default;
optional(optional&&) = default;
optional& operator=(const optional&) = default;
optional& operator=(optional&&) = default;
template <class U = T,
typename Enable::template conv_implicit<U> = 0>
constexpr optional(U&& v)
:Base{in_place, std::forward<U>(v)}
{
}
template <class U = T,
typename Enable::template conv_explicit<U> = 0>
explicit constexpr optional(U&& v)
:Base{in_place, std::forward<U>(v)}
{
}
template <class U,
typename Enable::template copy_conv_implicit<U> = 0>
optional(const optional<U>& rhs)
{
if (rhs)
this->construct(*rhs);
}
template <class U,
typename Enable::template copy_conv_explicit<U> = 0>
explicit optional(const optional<U>& rhs)
{
if (rhs)
this->construct(*rhs);
}
template <class U,
typename Enable::template move_conv_implicit<U> = 0>
optional(optional<U>&& rhs)
{
if (rhs)
this->construct(std::move(*rhs));
}
template <class U,
typename Enable::template move_conv_explicit<U> = 0>
explicit optional(optional<U>&& rhs)
{
if (rhs)
this->construct(std::move(*rhs));
}
optional& operator=(nullopt_t) noexcept
{
this->reset();
return *this;
}
template <class U = T,
typename Enable::template conv_ass<U> = 0>
optional& operator=(U&& v)
{
this->assign(std::forward<U>(v));
return *this;
}
template <class U,
typename Enable::template copy_conv_ass<U> = 0>
optional& operator=(const optional<U>& rhs)
{
if (rhs)
this->assign(*rhs);
else
this->reset();
return *this;
}
template <class U,
typename Enable::template move_conv_ass<U> = 0>
optional& operator=(optional<U>&& rhs)
{
if (rhs)
this->assign(std::move(*rhs));
else
this->reset();
return *this;
}
template <class... Args>
T& emplace(Args&&... args)
{
static_assert(std::is_constructible_v<T, Args...>,
"[optional.assign]/25");
this->reset();
this->construct(std::forward<Args>(args)...);
return **this;
}
template <class U, class... Args,
typename Enable::template emplace_ilist<U, Args...> = 0>
T& emplace(std::initializer_list<U> ilist, Args&&... args)
{
this->reset();
this->construct(ilist, std::forward<Args>(args)...);
return **this;
}
void swap(optional& rhs)
noexcept(std::is_nothrow_move_constructible_v<T> &&
std::is_nothrow_swappable_v<T>)
{
if (*this && rhs) {
using std::swap;
swap(**this, *rhs);
} else if (*this) {
rhs.construct(std::move(**this));
this->destroy();
} else if (rhs) {
this->construct(std::move(*rhs));
rhs.destroy();
}
}
constexpr T& value() &
{
if (*this)
return **this;
else
throw bad_optional_access{};
}
constexpr const T& value() const &
{
if (*this)
return **this;
else
throw bad_optional_access{};
}
constexpr T&& value() &&
{
if (*this)
return std::move(**this);
else
throw bad_optional_access{};
}
constexpr const T&& value() const &&
{
if (*this)
return std::move(**this);
else
throw bad_optional_access{};
}
template <class U>
constexpr T value_or(U&& v) const &
{
static_assert(std::is_copy_constructible_v<T>, "[optional.observe]/18");
static_assert(std::is_convertible_v<U&&, T>, "[optional.observe]/18");
if (*this)
return **this;
else
return static_cast<T>(std::forward<U>(v));
}
template <class U>
constexpr T value_or(U&& v) &&
{
static_assert(std::is_move_constructible_v<T>, "[optional.observe]/20");
static_assert(std::is_convertible_v<U&&, T>, "[optional.observe]/20");
if (*this)
return std::move(**this);
else
return static_cast<T>(std::forward<U>(v));
}
};
template <class T>
optional(T) -> optional<T>;
template <class T, class U>
constexpr bool operator==(const optional<T>& x, const optional<U>& y)
{
if (x)
return y && static_cast<bool>(*x == *y);
else
return !y;
}
template <class T, class U>
constexpr bool operator!=(const optional<T>& x, const optional<U>& y)
{
if (x)
return !y || static_cast<bool>(*x != *y);
else
return static_cast<bool>(y);
}
template <class T, class U>
constexpr bool operator<(const optional<T>& x, const optional<U>& y)
{
if (x)
return y && static_cast<bool>(*x < *y);
else
return static_cast<bool>(y);
}
template <class T, class U>
constexpr bool operator>(const optional<T>& x, const optional<U>& y)
{
if (x)
return !y || static_cast<bool>(*x > *y);
else
return false;
}
template <class T, class U>
constexpr bool operator<=(const optional<T>& x, const optional<U>& y)
{
if (x)
return y && static_cast<bool>(*x <= *y);
else
return true;
}
template <class T, class U>
constexpr bool operator>=(const optional<T>& x, const optional<U>& y)
{
if (x)
return !y || static_cast<bool>(*x >= *y);
else
return !y;
}
template <class T>
constexpr bool operator==(const optional<T>& x, nullopt_t) noexcept
{
return !x;
}
template <class T>
constexpr bool operator==(nullopt_t, const optional<T>& x) noexcept
{
return !x;
}
template <class T>
constexpr bool operator!=(const optional<T>& x, nullopt_t) noexcept
{
return static_cast<bool>(x);
}
template <class T>
constexpr bool operator!=(nullopt_t, const optional<T>& x) noexcept
{
return static_cast<bool>(x);
}
template <class T>
constexpr bool operator<(const optional<T>&, nullopt_t) noexcept
{
return false;
}
template <class T>
constexpr bool operator<(nullopt_t, const optional<T>& x) noexcept
{
return static_cast<bool>(x);
}
template <class T>
constexpr bool operator<=(const optional<T>& x, nullopt_t) noexcept
{
return !x;
}
template <class T>
constexpr bool operator<=(nullopt_t, const optional<T>&) noexcept
{
return true;
}
template <class T>
constexpr bool operator>(const optional<T>& x, nullopt_t) noexcept
{
return static_cast<bool>(x);
}
template <class T>
constexpr bool operator>(nullopt_t, const optional<T>&) noexcept
{
return false;
}
template <class T>
constexpr bool operator>=(const optional<T>&, nullopt_t) noexcept
{
return true;
}
template <class T>
constexpr bool operator>=(nullopt_t, const optional<T>& x) noexcept
{
return !x;
}
template <class T, class U>
constexpr bool operator==(const optional<T>& x, const U& v)
{
if (x)
return *x == v;
else
return false;
}
template <class T, class U>
constexpr bool operator==(const U& v, const optional<T>& x)
{
if (x)
return v == *x;
else
return false;
}
template <class T, class U>
constexpr bool operator!=(const optional<T>& x, const U& v)
{
if (x)
return *x != v;
else
return true;
}
template <class T, class U>
constexpr bool operator!=(const U& v, const optional<T>& x)
{
if (x)
return v != *x;
else
return true;
}
template <class T, class U>
constexpr bool operator<(const optional<T>& x, const U& v)
{
if (x)
return *x < v;
else
return true;
}
template <class T, class U>
constexpr bool operator<(const U& v, const optional<T>& x)
{
if (x)
return v < *x;
else
return false;
}
template <class T, class U>
constexpr bool operator<=(const optional<T>& x, const U& v)
{
if (x)
return *x <= v;
else
return true;
}
template <class T, class U>
constexpr bool operator<=(const U& v, const optional<T>& x)
{
if (x)
return v <= *x;
else
return false;
}
template <class T, class U>
constexpr bool operator>(const optional<T>& x, const U& v)
{
if (x)
return *x > v;
else
return false;
}
template <class T, class U>
constexpr bool operator>(const U& v, const optional<T>& x)
{
if (x)
return v > *x;
else
return true;
}
template <class T, class U>
constexpr bool operator>=(const optional<T>& x, const U& v)
{
if (x)
return *x >= v;
else
return false;
}
template <class T, class U>
constexpr bool operator>=(const U& v, const optional<T>& x)
{
if (x)
return v >= *x;
else
return true;
}
}
namespace my_std::detail {
template <typename T>
struct hash_is_enabled
:std::is_default_constructible<std::hash<std::remove_const_t<T>>> {};
template <typename T>
inline constexpr bool hash_is_enabled_v = hash_is_enabled<T>::value;
template <typename T>
struct optional_hash {
using result_type [[deprecated]] = std::size_t;
using argument_type [[deprecated]] = my_std::optional<T>;
constexpr std::size_t operator()(const optional<T>& o)
{
if (o)
return std::hash<std::remove_const_t<T>>{}(*o);
else
return typeid(T).hash_code();
}
};
struct disabled_hash {
disabled_hash() = delete;
disabled_hash(const disabled_hash&) = delete;
disabled_hash& operator=(const disabled_hash&) = delete;
disabled_hash(disabled_hash&&) = delete;
disabled_hash& operator=(disabled_hash&&) = delete;
};
}
namespace std {
template <typename T>
struct hash<my_std::optional<T>>
:std::conditional_t<my_std::detail::hash_is_enabled_v<T>,
my_std::detail::optional_hash<T>,
my_std::detail::disabled_hash> {};
}
#endif
</code></pre>
<p>Here's the test if you want to see. It's a bit unorganized, and not the most important part :)</p>
<pre><code>#include <cassert>
#include <string>
#include <vector>
#include "optional.hpp"
using namespace my_std;
struct Disabled {
Disabled() = delete;
Disabled(const Disabled&) = delete;
Disabled& operator=(const Disabled&) = delete;
Disabled(Disabled&&) = delete;
Disabled& operator=(Disabled&&) = delete;
~Disabled() = default;
};
struct Nontrivial_copy {
Nontrivial_copy() = default;
Nontrivial_copy(const Nontrivial_copy&) {}
Nontrivial_copy& operator=(const Nontrivial_copy&) = delete;
};
template <bool Noexcept = true>
struct Moveonly {
Moveonly() = default;
Moveonly(const Moveonly&) = delete;
Moveonly& operator=(const Moveonly&) = delete;
Moveonly(Moveonly&&) noexcept(Noexcept) {}
Moveonly& operator=(Moveonly&&) noexcept(Noexcept) {}
};
struct Direct_init {
// strict pattern
constexpr Direct_init(int&, int&&) {}
// no braced init
template <class U>
Direct_init(std::initializer_list<U>) = delete;
};
int main()
{
// ill formed instantiation
{
// optional<int&> a;
// optional<const in_place_t> b;
// optional<volatile nullopt_t> c;
}
// value_type
{
static_assert(std::is_same_v<optional<int>::value_type, int>);
}
// deduction guide
{
static_assert(std::is_same_v<optional<int>, decltype(optional{42})>);
static_assert(std::is_same_v<optional<Moveonly<>>,
decltype(optional{Moveonly<>{}})>);
}
// default / nullopt constructor
{
constexpr optional<int> a{};
constexpr optional<int> b = nullopt;
static_assert(!a);
static_assert(!b);
constexpr optional<Disabled> c{};
constexpr optional<Disabled> d = nullopt;
static_assert(!c);
static_assert(!d);
static_assert(std::is_nothrow_constructible_v<optional<Disabled>>);
static_assert(std::is_nothrow_constructible_v<optional<int>, nullopt_t>);
}
// trivial (constexpr) copy constructor
{
constexpr optional<int> a{};
constexpr auto b = a;
static_assert(!a && !b);
constexpr optional c{42};
constexpr auto d = c;
static_assert(c == 42 && d == 42);
}
// non-trivial (non-constexpr) copy constructor
{
constexpr optional<Nontrivial_copy> a{};
constexpr optional<Nontrivial_copy> b{in_place};
/* constexpr */ auto c = a;
/* constexpr */ auto d = b;
assert(!c);
assert(d);
}
// deleted copy constructor
{
static_assert(!std::is_copy_constructible_v<optional<Disabled>>);
static_assert(!std::is_copy_constructible_v<optional<Moveonly<>>>);
}
// move constructor
{
optional<Moveonly<true>> a{};
auto b = std::move(a);
assert(!a);
assert(!b);
optional<Moveonly<false>> c{in_place};
auto d = std::move(c);
assert(c);
assert(d);
}
// move constructor noexcept specification
{
static_assert(std::is_nothrow_move_constructible_v<Moveonly<true>>);
static_assert(!std::is_nothrow_move_constructible_v<Moveonly<false>>);
}
// deleted move constructor
{
static_assert(!std::is_move_constructible_v<optional<Disabled>>);
}
// in place constructor
{
int x = 21;
constexpr optional<Direct_init> a{in_place, x, 42};
static_assert(a);
}
// in place initializer list constructor
{
optional<std::vector<int>> b{in_place, {30, 36, 39, 42, 45}};
assert((b == std::vector<int>{30, 36, 39, 42, 45}));
}
// in place constructor explicit
{
static_assert(!std::is_convertible_v<in_place_t, optional<Direct_init>>);
}
// single value constructor
{
optional<std::vector<int>> a{5}; // => std::vector<int>(5)
assert(a->size() == 5); // not 1
constexpr optional<double> b = 42;
static_assert(b == 42.0);
}
// explicit
{
static_assert(std::is_convertible_v<const char*, optional<std::string>>);
static_assert(!std::is_convertible_v<std::size_t,
optional<std::vector<int>>>);
}
// copying converting constructor
{
optional<int> a{5};
optional<double> b = a;
optional<std::vector<int>> v{a}; // => std::vector<int>(5)
assert(b == 5);
assert(v->size() == 5); // not 1
static_assert(std::is_convertible_v<const optional<int>&,
optional<double>>);
static_assert(!std::is_convertible_v<const optional<int>&,
optional<std::vector<int>>>);
optional<int> c{};
optional<double> d = c;
optional<std::vector<int>> w{c};
assert(!d && !w);
}
// moving converting constructor
{
optional<int> a{5};
optional<double> b = std::move(a);
optional<std::vector<int>> v{std::move(a)};
assert(a == 5 && b == 5 && v->size() == 5);
static_assert(!std::is_convertible_v<optional<int>&&,
optional<std::vector<int>>>);
}
// destructor
{
static_assert(std::is_trivially_destructible_v<optional<Disabled>>);
static_assert(!std::is_trivially_destructible_v<optional<std::string>>);
}
// nullopt assignment
{
optional<std::vector<std::string>> a{in_place, 5, "foo"};
auto b = a;
a = nullopt;
assert(!a && b);
}
// copy assignment
{
optional<std::string> a;
optional<std::string> b{"foo"};
optional<std::string> c{"bar"};
a = b;
assert(a == "foo");
a = c;
assert(a == "bar");
static_assert(!std::is_copy_assignable_v<optional<Disabled>>);
static_assert(!std::is_copy_assignable_v<optional<Moveonly<>>>);
}
// move assignment
{
static_assert(std::is_nothrow_move_assignable_v<optional<Moveonly<>>>);
static_assert(!std::is_nothrow_move_assignable_v<
optional<Moveonly<false>>>);
static_assert(!std::is_move_assignable_v<Disabled>);
optional<std::string> a{"foo"};
optional<std::string> b{"bar"};
b = std::move(a);
assert(a == "" && b == "foo");
}
// single value assignment
{
optional<std::string> a{"foo"};
a = "bar";
static_assert(std::is_assignable_v<optional<std::string>&, const char*>);
static_assert(!std::is_assignable_v<optional<std::string>&, int>);
}
// converting copy assignment
{
optional<std::string> a{"foo"};
optional<const char*> b{"bar"};
a = b;
assert(a == "bar");
static_assert(!std::is_assignable_v<optional<std::string>&,
optional<int>&>);
}
// converting move assignment
{
optional<std::string> a{"foo"};
optional<const char*> b{"bar"};
a = std::move(b);
assert(a == "bar" && b);
static_assert(!std::is_assignable_v<optional<std::string>&, optional<int>>);
}
// emplace
{
optional<std::string> a{"foo"};
optional<std::string> b{"bar"};
a.emplace(5, 'a');
assert(a == "aaaaa");
a.emplace({'a', 'b', 'c'});
assert(a == "abc");
a.emplace(std::move(*b));
assert(a == "bar" && b == "");
}
// swap, general
{
static_assert(std::is_nothrow_swappable_v<optional<Moveonly<>>>);
static_assert(!std::is_nothrow_swappable_v<optional<Moveonly<false>>>);
static_assert(!std::is_swappable_v<optional<Disabled>>);
}
// swap, case one
{
optional<int> a{1}, b{2};
a.swap(b);
assert(a == 2 && b == 1);
swap(a, b);
assert(a == 1 && b == 2);
}
// swap, case two
{
optional<int> a{1}, b;
a.swap(b);
assert(!a && b == 1);
swap(a, b);
assert(a == 1 && !b);
}
// swap, case three
{
optional<int> a, b{2};
a.swap(b);
assert(a == 2 && !b);
swap(a, b);
assert(!a && b == 2);
}
// swap, case four
{
optional<int> a, b;
a.swap(b);
assert(!a && !b);
swap(a, b);
assert(!a && !b);
}
// observers
{
optional<std::string> a{"foo"};
assert(a->size() == 3);
assert(*a == "foo");
assert(a);
assert(a.has_value());
assert(a.value() == "foo");
assert(a.value_or("bar") == "foo");
optional<std::string> b{*std::move(a)};
assert(a == "");
a = "foo";
b = std::move(a).value();
assert(a == "");
a = "foo";
b = std::move(a).value_or("bar");
assert(a == "" && b == "foo");
constexpr optional<std::pair<int, int>> c;
static_assert(!c && !c.has_value());
// static_assert(c.value().first == 5); // throws bad_optional_access
static_assert(c.value_or(std::pair(21, 42)) == std::pair(21, 42));
}
// reset
{
optional<std::string> a{"foo"};
a.reset();
assert(!a);
a.reset();
assert(!a);
}
// nullopt features
{
static_assert(std::is_empty_v<nullopt_t>);
static_assert(!std::is_default_constructible_v<nullopt_t>);
static_assert(!std::is_aggregate_v<nullopt_t>);
}
// bad_optional_access
{
static_assert(std::is_default_constructible_v<bad_optional_access>);
static_assert(std::is_base_of_v<std::exception, bad_optional_access> &&
std::is_convertible_v<bad_optional_access*, std::exception*>);
}
// comparison between optionals
{
constexpr optional<int> a{42}, b{21}, c;
static_assert(a == a && !(a == b) && c == c && !(a == c) && !(c == a));
static_assert(!(a != a) && a != b && !(c != c) && a != c && c != a);
static_assert(!(a < a) && !(a < b) && !(c < c) && !(a < c) && c < a);
static_assert(a <= a && !(a <= b) && c <= c && !(a <= c) && c <= a);
static_assert(!(a > a) && a > b && !(c > c) && a > c && !(c > a));
static_assert(a >= a && a >= b && c >= c && a >= c && !(c >= a));
}
// comparison with nullopt
{
constexpr optional<int> a{42};
static_assert(!(a == nullopt || nullopt == a));
static_assert(a != nullopt && nullopt != a);
static_assert(!(a < nullopt) && nullopt < a);
static_assert(!(a <= nullopt) && nullopt <= a);
static_assert(a > nullopt && !(nullopt > a));
static_assert(a >= nullopt && !(nullopt >= a));
constexpr optional<int> b;
static_assert(b == nullopt && nullopt == b);
static_assert(!(b != nullopt || nullopt != b));
static_assert(!(b < nullopt) && !(nullopt < b));
static_assert(b <= nullopt && nullopt <= b);
static_assert(!(b > nullopt) && !(nullopt > b));
static_assert(b >= nullopt && nullopt >= b);
}
// comparison with T
{
constexpr optional<double> a{42.0};
static_assert(a == 42 && 42 == a && !(a == 21) && !(21 == a));
static_assert(!(a != 42) && !(42 != a) && a != 21 && 21 != a);
static_assert(!(a < 42) && !(42 < a) && !(a < 21) && 21 < a);
static_assert(a <= 42 && 42 <= a && !(a <= 21) && 21 <= a);
static_assert(!(a > 42) && !(42 > a) && a > 21 && !(21 > a));
static_assert(a >= 42 && 42 >= a && a >= 21 && !(21 >= a));
constexpr optional<double> b;
static_assert(!(b == 42) && !(42 == b));
static_assert(b != 42 && 42 != b);
static_assert(b < 42 && !(42 < b));
static_assert(b <= 42 && !(42 <= b));
static_assert(!(b > 42) && 42 > b);
static_assert(!(b >= 42) && 42 >= b);
}
// make optional
{
constexpr int ans = 42;
auto a = make_optional(ans);
static_assert(std::is_same_v<decltype(a), optional<int>>);
assert(a == 42);
constexpr auto b = make_optional<std::pair<double, double>>(ans, ans);
static_assert(b == std::pair(42.0, 42.0));
auto c = make_optional<std::vector<int>>({39, 42});
assert((c == std::vector<int>{39, 42}));
}
// hash
{
assert(std::hash<optional<double>>{}(42) == std::hash<double>{}(42));
using disabled = std::hash<optional<std::vector<double>>>;
static_assert(!std::is_default_constructible_v<disabled>);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>This looks pretty good. My comments are trivial nitpicking.</p>\n\n<ul>\n<li><p>The constructor of <code>struct in_place_t</code> gains nothing from <code>explicit</code> (it can't be considered as a conversion if it has no arguments). Whilst <code>explicit</code> prevents users writing <code>in_place_t x = {}</code>, I certainly think that's a reasonable thing to want to do, and won't cause any <em>surprising</em> conversions.</p></li>\n<li><p>The comment <code>// [optional.comp.with.t], comparison with T</code> probably should read \"comparison with value\" or similar, given that the other argument is a <code>const U&</code>.</p></li>\n<li><p><del>It shouldn't be necessary to provide <code>my_std::swap()</code>: providing member swap should be sufficient to allow <code>std::swap()</code> to work.</del></p></li>\n<li><p>Instead of writing out the return type again in <code>make_optional</code>, we can simply use a brace-expression: <code>return {std::forward<T>(v)};</code>. Sadly this won't work for the <code>in_place</code> overloads as that uses an <code>explicit</code> constructor.</p></li>\n<li><p>I'm not a fan of <code>else return false</code> in this:</p>\n\n<blockquote>\n<pre><code> if (x)\n return *x == v;\n else\n return false;\n</code></pre>\n</blockquote>\n\n<p>I'd probably rewrite as <code>return x && *x == v;</code>; similarly for all these related comparisons.</p></li>\n<li><p>I don't think there's a need for <code>static_cast<bool></code> in the optional/optional comparisons, since the the arguments of logical operators are <a href=\"//stackoverflow.com/a/39995574/4850040\">contextually converted to <code>bool</code></a>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T12:45:57.337",
"Id": "438602",
"Score": "1",
"body": "Making the default constructor of `in_place_t` non-`explicit` allows code like `in_place_t ip = {};` which is ill-formed according to the standard. The \"comparison with T\" is how the standard calls these function templates (which doesn't make much sense to me either). Also, are you sure that `std::swap` calls the `swap` member function? Otherwise, great review!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T12:52:15.917",
"Id": "438603",
"Score": "0",
"body": "That's a good point about `explicit` that I hadn't appreciated before - thanks for educating me! As for `swap`, I read \"*The expected way to make a user-defined type swappable is to provide a non-member function swap in the same namespace as the type: see Swappable for details.*\" However, when I removed `my_std::swap()` and adding `using std::swap;` into the functions, I got a run-time assertion failure which I didn't probe further; I don't understand why there's a difference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T12:57:17.247",
"Id": "438604",
"Score": "0",
"body": "\"... and adding `using std::swap;` into the functions\" into which functions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T13:27:30.990",
"Id": "438605",
"Score": "0",
"body": "Into the test functions that call `swap()` (as indicated by compilation errors)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T18:13:53.023",
"Id": "451876",
"Score": "0",
"body": "Maybe I just can't read - that definitely says ***non**-member `swap`* right there! Sorry for that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-21T09:59:30.273",
"Id": "458449",
"Score": "1",
"body": "Actually, `= {}` *will* cause surprising conversions - it allows `{}` to match a function parameter of the tag type."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T12:28:14.053",
"Id": "225824",
"ParentId": "225642",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "225824",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T11:18:25.523",
"Id": "225642",
"Score": "6",
"Tags": [
"c++",
"reinventing-the-wheel",
"c++17",
"stl"
],
"Title": "A standard-conforming C++17 std::optional implementation"
}
|
225642
|
<p>I've implemented Goal Oriented Action Planning (GOAP) in Kotlin.</p>
<p>Goal Oriented Action Planning is an algorithm originally devised by J Orkin for the game F.E.A.R. and performs a state space search using A* in order to formulate a plan of actions to get from an initial state to a goal state.</p>
<p>I've commented the code comprehensively and written some tests.</p>
<p>I'm looking for a code review to make sure my naming is good, my comments are good and that overall it makes sense.</p>
<pre><code>import org.junit.Test
import java.lang.Math.*
import java.util.*
import kotlin.collections.HashSet
import kotlin.test.assertFalse
import kotlin.test.assertTrue
/**
* This set of algorithms is an example of a Goal Oriented Action Planner (aka GOAP)
*
* Goal Oriented Action Planning (GOAP) is a method of planning developed by J Orkin for the game F.E.A.R.
* It can be conceptualized in a few ways - I like to think of it as dynamically calculated FSM
* as you do not need to explicitly write the state transition table and it is instead calculated at run time
* by searching through states given a set of actions. In other words GOAP is a state space search algorithm that outputs plans.
* You can read more about GOAP here: http://alumni.media.mit.edu/~jorkin/goap.html
*
* First there is an implementation of A* which is the basis for the state space search
* I have also implemented simple Cartesian graph search to show the extensibility of the A* implementation
*
* The idea with GOAP is that you would have many agents in an environment, and each agent has sensors that update a state that the agent maintains
* The agents will then be able to formulate a plan of actions, given a goal state and their current state by using the GOAP algorith
* This plan would then be actuated by actuators which in turn would then affect the environment, causing the sensors to update the agents state
* This process continues in a feedback loop so the agents should be able to act autonomously within any given environment.
*
* In other words, this solution can be used for games, robotics or even abstract problem domains such as shipping systems
* Where plans must be formulated based on dynamically changing conditions
*
* The plans generated by this particular implementation of GOAP are totally ordered
* In future, work will be undertaken to modify this solution so that it can generate partially ordered plans
* But that is a much more challenging problem to solve as partially ordered plans would require a completely different approach than A*
*/
/**
* Searches for the shortest path [from] -> [to] and returns a [Stack] of [AStarNode] representing the path (i.e. this is A*)
* By applying [heuristic] and [cost] for each evaluated open node to calculate the f cost to the goal
* This is non greedy BFS so long as [heuristic] is admissible (i.e. never overestimates)
* For example, in the case of 2D geometric search, the [heuristic] can be considered admissible if it measures euclidean distance
* In addition [from] and [to] should be part of either an oriented or bi directional graph which can be navigated via calling [neighbours] on a given [AStarNode]
*/
fun<T> path(from: AStarNode<T>,
to: AStarNode<T>,
heuristic: ((AStarNode<T>, AStarNode<T>) -> Int),
cost: ((AStarNode<T>, AStarNode<T>) -> Int)) : Stack<AStarNode<T>> {
/**
* Reconstructs a path, represented as a [Stack] of [AStarNode]
* By updating a pointer to a node until the pointer points at null
*/
fun reconstructPath(from: AStarNode<T>) : Stack<AStarNode<T>> {
val path = mutableListOf<AStarNode<T>>()
var current: AStarNode<T>? = from
path.add(current!!)
while (current?.from !== null) {
path.add(current.from!!)
current = current.from
}
path.reverse()
return Stack<AStarNode<T>>().apply {
path.forEach { this.push(it) }
}
}
// Use a priority queue for maintaining the open boundary of the search
// This means the search will always expand the optimal edge of the border
val openQueue = PriorityQueue<AStarNode<T>>()
// Use a hash set for the closed nodes to increase performance on big graphs
val closedSet = HashSet<AStarNode<T>>()
// The g cost of the initial node is by definition 0
from.g = 0
// The heuristic cost of the initial node is the heuristic function applied to it and the goal
from.f = heuristic(from, to)
// Of course, the initial node is the only node on the open border of the search before searching
openQueue.offer(from)
// Begin the search
// While there are still nodes to explore on the open border
while (!openQueue.isEmpty()) {
// Get the highest priority node
val current = openQueue.poll()
// Check if we've reached the goal node
if (current == to)
return reconstructPath(current)
// Ok, we still need to search
// Add the node to the closed set so we don't evaluate it again
closedSet.add(current)
// For each neighbour of the node calculate it's g cost and update it's from pointer
current.neighbours().forEach { neighbour ->
// If the neighbour is in the closed set ignore it
if (closedSet.contains(neighbour))
return@forEach
// Calc a new g score
val tentativeG = current.g + cost(current, neighbour)
// Push the neighbour into the open border if it's not already there
// If it is already there and has a lower g cost then ignore it
if (!openQueue.contains(neighbour)) {
openQueue.offer(neighbour)
} else if (tentativeG >= neighbour.g) {
return@forEach
}
// We've found a shorter path
// Update the neighbours from pointer and costs
neighbour.from = current
neighbour.g = tentativeG
neighbour.f = neighbour.g + heuristic(neighbour, to)
}
}
// The open border was exhaustively checked, no path exists!
throw IllegalArgumentException("No path can be found from $from to $to")
}
/**
* Parameterized type which wraps some [data] along with a pointer to the [from] node and [g] and [f] costs used in A* search
* The type argument [T] means that A* can be performed for any type as long as there is an admissable heuristic calculable for the type [T]
*/
abstract class AStarNode<T>(val data: T?,
var from: AStarNode<T>? = null,
var g: Int = Int.MAX_VALUE,
var f: Int = Int.MAX_VALUE) : Comparable<AStarNode<T>> {
/**
* Returns a [Collection] of neighbour nodes
* In the case of euclidean nodes this is simply the connected nodes on the graph
* In the case of non euclidean nodes this could be a function of any number of things
* For instance, in a state space search, this could return any states which were transition to from valid actions
*/
abstract fun neighbours() : Collection<AStarNode<T>>
/**
* Implemented so these can be used in a priority queue
*/
override fun compareTo(other: AStarNode<T>): Int {
return when {
this.f < other.f -> -1
this.f > other.f -> 1
else -> 0
}
}
}
/**
* An implementation of [AStarNode] for cartesian space search
* A cartesian space search takes place on a 2D plane through a oriented or bi-direction graph of points in space
* A point in cartesian space is defined by an [x] and a [y] value and, in this case, also has an associated [label]
*/
class CartesianNode(val x: Int,
val y: Int,
label: String,
private val neighbours: MutableCollection<CartesianNode> = mutableListOf()) : AStarNode<String>(label) {
/**
* Distance to another node is euclidean and worked out using pythagorean theorem
*/
fun distanceTo(other: CartesianNode) : Int {
val dx = abs(this.x - other.x).toDouble()
val dy = abs(this.y - other.y).toDouble()
return round(sqrt(dx * dx) + sqrt(dy * dy)).toInt()
}
/**
* Used to add an [other] neighbour
*/
fun addNeighbour(other: CartesianNode) {
this.neighbours.add(other)
}
/**
* Implement the neighbours functionality by simply returning an immutable copy of the neighbours list
*/
override fun neighbours(): Collection<AStarNode<String>> {
return this.neighbours.toList()
}
/**
* A cartesian node is equal to another one if the coordinates are the same
*/
override fun equals(other: Any?): Boolean {
return if (other !is CartesianNode) {
false
} else {
this.x == other.x && this.y == other.y
}
}
/**
* Implement hash code so this can be used in a hash set
*/
override fun hashCode(): Int {
var hash = 7
hash = 31 * hash + g
hash = 31 * hash + f
hash = 31 * hash + data.hashCode()
return hash
}
}
/**
* Wraps [findPath] providing functions for the heuristic and cost in cartesian space
*/
class CartesianPathfinder {
fun findPath(from: CartesianNode, to: CartesianNode) = path(from, to, { x, y ->
(x as CartesianNode).distanceTo(y as CartesianNode)
}, { x, y ->
(x as CartesianNode).distanceTo(y as CartesianNode)
})
}
/**
* An implementation of [AStarNode] for state space search
* A state space search occurs in an abstract space where points within that space represent states
* and edges between the point represent actions taken to reach a state from a state
* A point in state space search is defined by a [worldState] and keep a reference to an [actionPool] of possible [GoapAction]
* These also keep a reference to the [actionTaken] to reach the state
*/
class GoapNode(val worldState: WorldState,
private val actionPool: Collection<GoapAction>,
actionTaken: GoapAction? = null) : AStarNode<GoapAction>(actionTaken) {
/**
* Implementation of neighbours for state space search
* Neighbours in this case are other states which can be reached by applying all possible valid actions to this state
*/
override fun neighbours(): Collection<AStarNode<GoapAction>> {
// For all actions in the action pool
// If they are valid, apply the action to this state, otherwise ignore it
return actionPool.mapNotNull { action ->
if (action.isValid(worldState)) {
GoapNode(worldState.applyAction(action), actionPool, action)
} else {
null
}
}
}
/**
* Goap nodes are equal if the amount of differences between the states is 0
*/
override fun equals(other: Any?): Boolean {
return if (other !is GoapNode) {
false
} else {
this.worldState.countDifferences(other.worldState) == 0
}
}
/**
* Implement hash code so that these can be used in a hash set
*/
override fun hashCode(): Int {
var hash = 7
hash = 31 * hash + g
hash = 31 * hash + f
hash = 31 * hash + data.hashCode()
return hash
}
}
/**
* An action is defined primarily by [preconditions], [postConditions] and a name
* An action can be applied to a [WorldState] if the given [WorldState] satisifes the actions [preconditions]
* The result of applying an action to a [WorldState] is the state of the world will be modified by applying the [postConditions] of the action
* When performing state space search, the action also has procedural checks performed to validate if it is not only statically valid but also dynamically valid
* This is achieved by running the [isProcedurallyValid] function at plan time (when working out the neighbours of world states)
* Actions can be also be determined to be dynamically complete via the [isComplete] function and can be executed in an environment using the [execute] function
*/
data class GoapAction(val name: String,
val preconditions: Map<String, Boolean>,
val postConditions: Map<String, Boolean>,
val cost: Int,
val isProcedurallyValid: ((GoapAgent) -> Boolean),
val isComplete: ((GoapAgent) -> Boolean),
val execute: ((GoapAgent) -> Unit))
/**
* Returns true if an action is valid [forWorldState]
*/
fun GoapAction.isValid(forWorldState: WorldState) : Boolean {
return forWorldState.isActionValid(this)
}
/**
* Define the contract for a planning agent
* This can be implemented for any number of environments
* Be it games, robotics or any other abstract domain
*/
interface GoapAgent {
val blackboard: Blackboard
fun hasPlan(): Boolean
fun plan()
fun onActionCompleted(fromAction: GoapAction)
}
/**
* A world state is simply a [Map] of facts about the world
* Facts are binary and have an associated name
* for instance:
* HasMoney = false
* HasReachedTarget = true
*/
data class WorldState(val state: Map<String, Boolean>)
/**
* Returns a [WorldState] by applying [action] to source [WorldState]
*/
fun WorldState.applyAction(action: GoapAction) : WorldState {
return WorldState(this.state.toMutableMap().apply {
this.putAll(action.postConditions)
})
}
/**
* Returns the number of differences between the source [WorldState] and the [against] state
*/
fun WorldState.countDifferences(against: WorldState) : Int {
// Fold the against state into an integer representing the differences
return against.state.keys.fold(0) { acc, key ->
acc + when (val prop = this.state[key]) {
null -> 1
else -> when (prop == against.state[key]) {
true -> 0
else -> 1
}
}
}
}
/**
* Creates a copy of the source [WorldState] with the updated [value] for the given [variable]
*/
fun WorldState.setStateVariable(variable: String, value: Boolean) : WorldState {
return WorldState(this.state.toMutableMap().apply { this[variable] = value })
}
/**
* Returns true if the [action] is valid for the source [WorldState]
*/
fun WorldState.isActionValid(action: GoapAction) : Boolean {
// Fold the actions preconditions into an integer representing the unsatisfied variables
// And return true if the unsatisfied variables are 0 else false
return action.preconditions.keys.fold(0) { acc, key ->
acc + when (val prop = this.state[key]) {
null -> 1
else -> {
when (prop == action.preconditions[key]) {
true -> 0
else -> 1
}
}
}
} == 0
}
/**
* A blackboard maintains a state of the world and has references to sensors and actuators
* An agent has a reference to a blackboard, which can be though of as the agents central system for sensing, remember and actuating in an environment
*/
class Blackboard(private val world: WorldState) {
fun updateState(variable: String, value: Boolean) {
this.world.setStateVariable(variable, value)
}
}
/**
* Wraps [path] providing state search specific heuristic and cost functions
*/
class GoapPlanner {
fun plan(actionPool: Collection<GoapAction>, fromState: WorldState, toState: WorldState) = Stack<GoapAction>().apply {
this.addAll(
path(
GoapNode(fromState, actionPool, null),
GoapNode(toState, actionPool, null),
{ a, b ->
(a as GoapNode).worldState.countDifferences((b as GoapNode).worldState)
}, { _, b ->
(b as GoapNode).data?.cost ?: 0
}
).mapNotNull { goapNode ->
goapNode.data
}
)
}
}
/**
* Provides a clean API to execute plans that an [agent] has formulated
*/
class PlanExecutor(private val agent: GoapAgent,
private val plan: Stack<GoapAction>) {
/**
* Returns true if the plan is not empty
*/
fun hasPlan() = plan.isNotEmpty()
/**
* Checks if the action on top of the stack is complete
* If it is, it pops the stack
* It then performs [execute] on the action on top of the stack
*/
fun execute() {
if (this.plan.isNotEmpty()) {
if (this.plan.peek().isComplete(this.agent)) {
agent.onActionCompleted(this.plan.pop() as GoapAction)
} else {
this.plan.peek().execute(this.agent)
}
}
}
}
/**
* Set of tests for validating the correctness of the GOAP algorithm
*/
class GoapTests {
@Test
fun testSimplePath() {
// Make a 2 node bi-directional graph
val a = CartesianNode(0, 0, "a")
val b = CartesianNode(10, 10, "b")
a.addNeighbour(b)
b.addNeighbour(a)
// Create a cartesian pathfinder
val pathfinder = CartesianPathfinder()
// Find a path from a -> b
val path = pathfinder.findPath(a, b)
// Assert that the path is of length 2
// And that it goes a -> b
assertTrue { path.size == 2 }
assertTrue { path[0] == a }
assertTrue { path[1] == b }
}
@Test
fun testComplexPath() {
// Make a more complicated bi-directional graph
val a = CartesianNode(0, 0, "a")
val b = CartesianNode(10, 10, "b")
val c = CartesianNode(20, 10, "c")
val d = CartesianNode(20, 20, "d")
val e = CartesianNode(30, 10, "e")
// Doubly link all the nodes
a.addNeighbour(b)
b.addNeighbour(a)
b.addNeighbour(c)
b.addNeighbour(d)
c.addNeighbour(b)
c.addNeighbour(e)
d.addNeighbour(b)
d.addNeighbour(e)
e.addNeighbour(c)
e.addNeighbour(d)
// Create a cartesian pathfindr
val pathfinder = CartesianPathfinder()
// Find a path from a -> e
val path = pathfinder.findPath(a, e)
// Assert that the path is of length 4
// And that the path is a -> b -> c -> e
assertTrue { path.size == 4 }
assertTrue { path[0] == a }
assertTrue { path[1] == b }
assertTrue { path[2] == c }
assertTrue { path[3] == e }
}
@Test
fun testSimplePlan() {
// Create an initial state where HasBread is false
val initialState = WorldState(mutableMapOf(
Pair("HasBread", false)
))
// Create a desired state where HasBread is true
val goalState = WorldState(mutableMapOf(
Pair("HasBread", true)
))
// Create a pool of actions
// In this case, there is 1 action "GetBread"
// That has no preconditions and a single postcondition where HasBread becomes true
val getBreadAction = GoapAction(
name = "GetBread",
preconditions = emptyMap(),
postConditions = mapOf(Pair("HasBread", true)),
cost = 5,
isProcedurallyValid = { true },
isComplete = { true },
execute = { })
val actionPool = listOf(getBreadAction)
// Create a GOAP planner
val planner = GoapPlanner()
// Find a plan of actions that take us from the initial state to the desired state
val plan = planner.plan(actionPool, initialState, goalState)
assertTrue { plan.size == 1 }
assertTrue { plan.peek() == getBreadAction }
}
@Test
fun testComplexPlan() {
// Create an initial state where all variables are false
val initialState = WorldState(mutableMapOf())
// Create a desired state where HasToast is true
val goalState = WorldState(mutableMapOf(
Pair("HasToast", true)
))
// Define some more complex actions
// With preconditions and postconditions
val workForMoneyAction = GoapAction(
name = "WorkForMoney",
preconditions = emptyMap(),
postConditions = mapOf(Pair("HasMoney", true)),
cost = 5,
isProcedurallyValid = { true },
isComplete = { true },
execute = { })
val getBreadAction = GoapAction(
name = "GetBread",
preconditions = mapOf(Pair("HasMoney", true)),
postConditions = mapOf(Pair("HasBread", true), Pair("HasMoney", false)),
cost = 5,
isProcedurallyValid = { true },
isComplete = { true },
execute = { })
val makeToastAction = GoapAction(
name = "MakeToast",
preconditions = mapOf(Pair("HasBread", true)),
postConditions = mapOf(Pair("HasToast", true), Pair("HasBread", false)),
cost = 5,
isProcedurallyValid = { true },
isComplete = { true },
execute = { })
// Create the action pool
val actionPool = listOf(
workForMoneyAction,
getBreadAction,
makeToastAction
)
// Create the planner
val planner = GoapPlanner()
// Find a plan to take us from the initial state to the desired state of having toast
val plan = planner.plan(actionPool, initialState, goalState)
// Assert that the plan is of length 3 and has the correct actions in the correct order
assertTrue { plan.size == 3 }
assertTrue { plan.pop() == makeToastAction }
assertTrue { plan.pop() == getBreadAction }
assertTrue { plan.pop() == workForMoneyAction }
}
@Test
fun testWorldStateDiffWhenStatesAreSame() {
val a = WorldState(mutableMapOf(
Pair("HasBread", true)
))
val b = WorldState(mutableMapOf(
Pair("HasBread", true)
))
assertTrue { a.countDifferences(b) == 0 }
}
@Test
fun testWorldStateDiffWhenStatesAreDifferent() {
val a = WorldState(mutableMapOf(
Pair("HasBread", true)
))
val b = WorldState(mutableMapOf(
Pair("HasBread", false)
))
assertTrue { a.countDifferences(b) == 1 }
}
@Test
fun testWorldStateDiffForDifferingLengthStateMaps() {
val a = WorldState(mutableMapOf(
Pair("HasBread", false),
Pair("HasMoney", true)
))
val b = WorldState(mutableMapOf(
Pair("HasBread", true)
))
assertTrue { a.countDifferences(b) == 1 }
}
@Test
fun testActionIsNotValidForWorldState() {
val forState = WorldState(mutableMapOf(
Pair("HasMoney", false)
))
val action = GoapAction("GetBread", mapOf(Pair("HasMoney", true)), mapOf(Pair("HasBread", true)), 5, { true }, { true }, { })
assertFalse { action.isValid(forState) }
}
@Test
fun testActionIsValidForWorldState() {
val forState = WorldState(mutableMapOf(
Pair("HasMoney", true)
))
val action = GoapAction("GetBread", mapOf(Pair("HasMoney", true)), mapOf(Pair("HasBread", true)), 5, { true }, { true }, { })
assertTrue { action.isValid(forState) }
}
@Test
fun testMakeToastIsInvalidForHasBreadFalseWorldState() {
val makeToast = GoapAction("MakeToast", mapOf(Pair("HasBread", true)), mapOf(Pair("HasToast", true), Pair("HasBread", false)), 5, { true }, { true }, { })
val forState = WorldState(mutableMapOf(
Pair("HasToast", false),
Pair("HasBread", false),
Pair("HasMoney", true)
))
val isValid = makeToast.isValid(forState)
assertTrue { !isValid }
}
@Test
fun testApplyAction() {
val initialState = WorldState(mutableMapOf(
Pair("HasMoney", true)
))
val action = GoapAction("GetBread", mapOf(Pair("HasMoney", true)), mapOf(Pair("HasBread", true)), 5, { true }, { true }, { })
val expectedWorldState = WorldState(mutableMapOf(
Pair("HasMoney", true),
Pair("HasBread", true)
))
val resultingWorldState = initialState.applyAction(action)
assertTrue { resultingWorldState == expectedWorldState }
}
@Test
fun testGoapNodeNeighboursSimple() {
val actionPool = listOf(
GoapAction("WorkForMoney", emptyMap(), mapOf(Pair("HasMoney", true)), 5, { true }, { true }, { }),
GoapAction("GetBread", mapOf(Pair("HasMoney", true)), mapOf(Pair("HasBread", true), Pair("HasMoney", false)), 5, { true }, { true }, { }),
GoapAction("MakeToast", mapOf(Pair("HasBread", true)), mapOf(Pair("HasToast", true), Pair("HasBread", false)), 5, { true }, { true }, { })
)
val forState = WorldState(mutableMapOf(
Pair("HasToast", false),
Pair("HasBread", false),
Pair("HasMoney", false)
))
val node = GoapNode(forState, actionPool)
val neighbours = node.neighbours()
assertTrue { neighbours.size == 1 }
}
@Test
fun testGoapNodeNeighboursComplex() {
val actionPool = listOf(
GoapAction("WorkForMoney", emptyMap(), mapOf(Pair("HasMoney", true)), 5, { true }, { true }, { }),
GoapAction("GetBread", mapOf(Pair("HasMoney", true)), mapOf(Pair("HasBread", true), Pair("HasMoney", false)), 5, { true }, { true }, { }),
GoapAction("MakeToast", mapOf(Pair("HasBread", true)), mapOf(Pair("HasToast", true), Pair("HasBread", false)), 5, { true }, { true }, { })
)
val forState = WorldState(mutableMapOf(
Pair("HasToast", false),
Pair("HasBread", false),
Pair("HasMoney", true)
))
val node = GoapNode(forState, actionPool)
val neighbours = node.neighbours()
assertTrue { neighbours.size == 2 }
}
}
</code></pre>
|
[] |
[
{
"body": "<p>This is quite a lot to analyze, so I will focus only few examples on semantics, best practices and language features.</p>\n\n<h1>Naming</h1>\n\n<h2>Good:</h2>\n\n<ul>\n<li>Have a structure</li>\n<li>well understandable</li>\n<li>not too long</li>\n</ul>\n\n<h2>Arguable:</h2>\n\n<p>Some of your parameter and field names are way too short.</p>\n\n<pre><code>abstract class AStarNode<T>(val data: T?,\n var from: AStarNode<T>? = null,\n var g: Int = Int.MAX_VALUE,\n var f: Int = Int.MAX_VALUE) : Comparable<AStarNode<T>> {\n</code></pre>\n\n<p><code>g</code>, <code>f</code></p>\n\n<pre><code>fun distanceTo(other: CartesianNode) : Int {\n val dx = abs(this.x - other.x).toDouble()\n val dy = abs(this.y - other.y).toDouble()\n return round(sqrt(dx * dx) + sqrt(dy * dy)).toInt()\n}\n</code></pre>\n\n<p><code>dx</code>, <code>dy</code> are arguable, because I can understand them through method name.</p>\n\n<h1>Comments</h1>\n\n<p>Very many of them - although they are well understandable, I'm a fan when the number of code lines is much bigger than the comment lines.</p>\n\n<p>A best practice is to use comments to describe the reason for something not obvious or complex - not the implementation. </p>\n\n<h2>Good:</h2>\n\n<p>Very good example of yours, where a comment says WHY and not WHAT:</p>\n\n<pre><code>/**\n * Implemented so these can be used in a priority queue\n */\noverride fun compareTo(other: AStarNode<T>): Int\n</code></pre>\n\n<h2>Arguable:</h2>\n\n<p>Many comments could be left out, because ...</p>\n\n<ul>\n<li><p>they are obvious</p>\n\n<pre><code>// Begin the search\n</code></pre>\n\n\n\n<pre><code>/**\n * Implement hash code so that these can be used in a hash set\n */\noverride fun hashCode(): Int {\n var hash = 7\n hash = 31 * hash + g\n hash = 31 * hash + f\n hash = 31 * hash + data.hashCode()\n return hash\n}\n</code></pre></li>\n<li><p>commenting a setter - I don't see any need here for a comment</p>\n\n<pre><code>// The g cost of the initial node is by definition 0\nfrom.g = 0\n</code></pre></li>\n<li><p>tell me something I could have figured out in 2 seconds looking into the code</p>\n\n<pre><code>/**\n * A cartesian node is equal to another one if the coordinates are the same\n */\noverride fun equals(other: Any?): Boolean {\n return if (other !is CartesianNode) {\n false\n } else {\n this.x == other.x && this.y == other.y\n }\n}\n</code></pre>\n\n\n\n<pre><code>/**\n * Returns true if the plan is not empty\n */\nfun hasPlan() = plan.isNotEmpty()\n</code></pre></li>\n</ul>\n\n<p>If you have to explain in the code how your method works (not necessarily classes), its neither well written, nor has it an understandable name.</p>\n\n<pre><code>// For each neighbour of the node calculate it's g cost and update it's from pointer\n</code></pre>\n\n<p>I strongly believe that comments can, and often do, pollute source code. The goal should be to write the code so well, that it explains itself.</p>\n\n<h1>Language features</h1>\n\n<h2>Good:</h2>\n\n<p>Almost nothing to complain about. You seem to get along with kotlin.</p>\n\n<h2>Arguable:</h2>\n\n<p>Some things are a bit more complex than they could be, or miss some existing helping functionalities:</p>\n\n<pre><code>override fun compareTo(other: AStarNode<T>): Int {\n return when {\n this.f < other.f -> -1\n this.f > other.f -> 1\n else -> 0\n }\n}\n</code></pre>\n\n<p>can be </p>\n\n<pre><code>override fun compareTo(other: AStarNode<T>): Int = this.f.compareTo(other.f)\n</code></pre>\n\n\n\n<pre><code>override fun hashCode(): Int {\n var hash = 7\n hash = 31 * hash + g\n hash = 31 * hash + f\n hash = 31 * hash + data.hashCode()\n return hash\n}\n</code></pre>\n\n<p>can be</p>\n\n<pre><code> override fun hashCode(): Int = HashCodeBuilder(13,17)\n .append(g)\n .append(f)\n .append(data)\n .toHashCode()\n</code></pre>\n\n<h1>Code readability</h1>\n\n<h2>Good:</h2>\n\n<ul>\n<li>Very small classes</li>\n<li>Well written to the ability of being testable</li>\n<li>Good and rare usage of interfaces and inheritance</li>\n<li>You wrote tests - this is already a big win </li>\n</ul>\n\n<h2>Arguble:</h2>\n\n<p>While your classes remain small and beautiful, some of your methods don't follow the same example.</p>\n\n<p><em>Method inside a method</em>: extract it. A Method usually has to do one thing and not create another one - quite unusual implementation I haven't seen so far:</p>\n\n<pre><code>fun<T> path(from: AStarNode<T>,\n to: AStarNode<T>,\n heuristic: ((AStarNode<T>, AStarNode<T>) -> Int),\n cost: ((AStarNode<T>, AStarNode<T>) -> Int)) : Stack<AStarNode<T>> {\n\n/**\n * Reconstructs a path, represented as a [Stack] of [AStarNode]\n * By updating a pointer to a node until the pointer points at null\n */\nfun reconstructPath(from: AStarNode<T>) : Stack<AStarNode<T>> {\n</code></pre>\n\n<p><em>Very long method</em>: extract the functionality into other functions / classes. The first method in the example has ~100 lines! </p>\n\n<pre><code>fun<T> path(...)\n</code></pre>\n\n<p>When the called instance / method has many parameters, it is always better to <em>use named params</em> - like here:</p>\n\n<pre><code>class GoapPlanner {\nfun plan(actionPool: Collection<GoapAction>, fromState: WorldState, toState: WorldState) = Stack<GoapAction>().apply {\n this.addAll(\n path(\n GoapNode(fromState, actionPool, null),\n GoapNode(toState, actionPool, null),\n { a, b ->\n (a as GoapNode).worldState.countDifferences((b as GoapNode).worldState)\n }, { _, b ->\n (b as GoapNode).data?.cost ?: 0\n }\n ).mapNotNull { goapNode ->\n goapNode.data\n }\n )\n}\n</code></pre>\n\n<h1>Tests</h1>\n\n<h2>Good:</h2>\n\n<ul>\n<li>Short</li>\n<li>Have comments</li>\n<li>Initialisation uses with named params</li>\n</ul>\n\n<h2>Arguable:</h2>\n\n<ul>\n<li><p>Much duplication for objects and parameters. Its better to define some fields to be used by other tests, which are not that important, but are needed e.g. for initialisation.</p>\n\n<pre><code>Pair(\"HasBread\", true)\n\nPair(\"HasMoney\", true)\n</code></pre></li>\n<li><p>Weird assertions</p>\n\n<pre><code>assertTrue { !isValid }\n</code></pre></li>\n<li><p>Assertions which will tell nothing valuable when they fail </p>\n\n<pre><code>assertTrue { resultingWorldState == expectedWorldState }\n</code></pre>\n\n<p>The error message would be something like \"Expected to be true, but was false\". This is worthless! You need to debug to find out WHY they are not equal. \nThere are plenty of methods and other libraries which offer so much better solutions, like <a href=\"https://joel-costigliola.github.io/assertj/\" rel=\"nofollow noreferrer\">AssertJ</a>. There you could write </p>\n\n<pre><code>assertThat(resultingWorldState).isEqualTo(expectedWorldState)\n</code></pre>\n\n<p>and when it fails, it would tell you what was expected, what is the result and what is the difference - much more information.</p>\n\n<p>Or here:</p>\n\n<pre><code> // Assert that the plan is of length 3 and has the correct actions in the correct order\n assertTrue { plan.size == 3 }\n assertTrue { plan.pop() == makeToastAction }\n assertTrue { plan.pop() == getBreadAction }\n assertTrue { plan.pop() == workForMoneyAction }\n</code></pre>\n\n<p>When any of this fails, you don't know which one (besides the <em>exception on line xy</em>), what was the real value, what is the difference? </p></li>\n<li><p>Naming</p>\n\n<p>Yes, here we are again. The names of a test are allowed to be longer than usual and should be very explainable. Names like <code>testSimplePath</code>,<code>testComplexPath</code>, <code>testComplexPath</code>, .. tell me nothing! </p>\n\n<p>Companies have often their own patterns and standards on test names, but my advice would be to start every test with the word 'should'. Like: <code>should return true, when property xy is bigger than zero</code>.</p>\n\n<p>A test should be as simple as it can be and as explainable as it is possible. This includes the name where you can define your case in prose. BTW: <a href=\"https://kotlinlang.org/docs/reference/coding-conventions.html#function-names\" rel=\"nofollow noreferrer\">You can use backticks to have a function name with spaces in between.</a></p></li>\n</ul>\n\n<hr>\n\n<p>Thanks for reading and I hope I could give you some advice which is actually valuable.</p>\n\n<p>The END</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T13:24:07.137",
"Id": "447942",
"Score": "2",
"body": "Great feedback, appreciate the time you must have put in to write this up. \n\nWhilst I agree with most of your comments, one in particular I am not so sure I agree with:\n\n\"Method inside a method: extract it\"\n\nI hear a lot of people saying this, and I honestly do not see the benefit of extracting a method that will have a single call site into a private function. My argument for this is;\n\nA) it is not re-used \nB) by moving it you have just made the method with the single call site more complex to understand (you haven't made it any less complex, you've just moved the logic)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T13:40:40.623",
"Id": "447946",
"Score": "1",
"body": "Thanks. To your reply: \"B) by moving it you have just made the method with the single call site more complex to understand\" I don't get it, how an extracted method - which reduces the outside functions size - makes it more complex. It sounds contradicting. If something is so long I need to encapsulate it in multiple functions which only are interesting in this (method) context - It would even make sence to create an own class for it. Small methods - even iff its just for the lines of code - are always easier to read"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T13:12:22.367",
"Id": "230095",
"ParentId": "225644",
"Score": "6"
}
},
{
"body": "<p>I took a single method as example how to make the code simpler:</p>\n\n<pre><code>fun WorldState.isActionValid(action: GoapAction): Boolean {\n // Fold the actions preconditions into an integer representing the unsatisfied variables\n // And return true if the unsatisfied variables are 0 else false\n return action.preconditions.keys.fold(0) { acc, key ->\n acc + when (val prop = this.state[key]) {\n null -> 1\n else -> {\n when (prop == action.preconditions[key]) {\n true -> 0\n else -> 1\n }\n }\n }\n } == 0\n}\n</code></pre>\n\n<p>One thing I noticed is that the comment describes the implementation.\nI don't like these comments since they are better expressed in code.</p>\n\n<p>First step: replace <code>fold</code> with <code>all</code>.</p>\n\n<pre><code>fun WorldState.isActionValid(action: GoapAction): Boolean {\n return action.preconditions.keys.all { key ->\n when (val prop = this.state[key]) {\n null -> false\n else -> {\n when (prop == action.preconditions[key]) {\n true -> true\n else -> false\n }\n }\n }\n }\n}\n</code></pre>\n\n<p>I replaced <code>fold</code> with <code>all</code>, since you were effectively using integers to represent a simple boolean decision. By the way, your code had the potential to break unexpectedly when the code would add <span class=\"math-container\">\\$2^{32}\\$</span> times a 1.</p>\n\n<p>Curiously, IntelliJ doesn't notice that the innermost <code>when</code> can be made much simpler, so I have to do it manually.</p>\n\n<pre><code>fun WorldState.isActionValid(action: GoapAction): Boolean {\n return action.preconditions.keys.all { key ->\n when (val prop = this.state[key]) {\n null -> false\n else -> prop == action.preconditions[key]\n }\n }\n}\n</code></pre>\n\n<p>Next, I extracted the <code>prop</code> variable and converted the <code>when</code> to an <code>if</code>, since I though that IntelliJ might be able to simplify this condition. But it wasn't helpful at all.</p>\n\n<pre><code>fun WorldState.isActionValid(action: GoapAction): Boolean {\n return action.preconditions.keys.all { key ->\n val prop = this.state[key]\n if (prop == null) false else prop == action.preconditions[key]\n }\n}\n</code></pre>\n\n<p>Next, I replaced the <code>if-then-else</code> with a simple <code>and</code>.</p>\n\n<pre><code>fun WorldState.isActionValid(action: GoapAction): Boolean {\n return action.preconditions.keys.all { key ->\n val prop = this.state[key]\n prop != null && prop == action.preconditions[key]\n }\n}\n</code></pre>\n\n<p>One thing that I don't like is the <code>action.preconditions[key]</code>, since the lookup is unnecessary:</p>\n\n<pre><code>fun WorldState.isActionValid(action: GoapAction): Boolean {\n return action.preconditions.all { entry ->\n val prop = this.state[entry.key]\n prop != null && prop == entry.value\n }\n}\n</code></pre>\n\n<p>Now that's much more readable.</p>\n\n<p>I ran the unit tests you provided after each step, to ensure that I didn't make any mistakes. I trusted you to have written good tests, I didn't look at them. In the first try of this refactoring, I had inverted one of the conditions and your tests failed. That was good and encouraging.</p>\n\n<p>One last minification:</p>\n\n<pre><code>fun WorldState.isActionValid(action: GoapAction): Boolean {\n return action.preconditions.all { state[it.key] ?: false == it.value }\n}\n</code></pre>\n\n<p>And another:</p>\n\n<pre><code>fun WorldState.isActionValid(action: GoapAction): Boolean {\n return action.preconditions.all { state[it.key] == it.value }\n}\n</code></pre>\n\n<p>Same for <code>countDifferences</code>:</p>\n\n<pre><code>fun WorldState.countDifferences(against: WorldState): Int {\n return against.state.count { state[it.key] != it.value }\n}\n</code></pre>\n\n<p>Oh, I cannot resist. If the code is down to a three-liner, a one-liner is possible as well:</p>\n\n<pre><code>fun WorldState.countDifferences(against: WorldState) = against.state.count { state[it.key] != it.value }\n\nfun WorldState.isActionValid(action: GoapAction) = action.preconditions.all { state[it.key] == it.value }\n</code></pre>\n\n<p>I normally prefer code that is less than 100 columns wide on the screen, but you seem to like longer lines, so it's ok that there are horizontal scrollbars in this particular code example.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T16:17:09.687",
"Id": "447975",
"Score": "0",
"body": "Great answer, really good points in here"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T13:58:04.053",
"Id": "230100",
"ParentId": "225644",
"Score": "2"
}
},
{
"body": "<p>There's a bug in <code>distanceTo</code>:</p>\n\n<pre><code>/**\n * Distance to another node is euclidean and worked out using pythagorean theorem\n */\nfun distanceTo(other: CartesianNode): Int {\n val dx = abs(this.x - other.x).toDouble()\n val dy = abs(this.y - other.y).toDouble()\n return round(sqrt(dx * dx) + sqrt(dy * dy)).toInt()\n}\n</code></pre>\n\n<p>What you compute here is the Manhattan distance, not the Euclidean distance.</p>\n\n<p>Calculating <code>sqrt(a * a)</code> doesn't make sense since it is the same as <code>a</code>.</p>\n\n<p>Did you mean <code>sqrt(dx * dx + dy * dy)</code>?</p>\n\n<p>Kotlin has <code>roundToInt</code>, which lets you combine the <code>round</code> and <code>toInt</code> calls.</p>\n\n<p>Here's a unit test for it:</p>\n\n<pre><code>@Test\nfun cartesianDistance() {\n val node1 = CartesianNode(0, 0, \"\")\n val node2 = CartesianNode(3000, 4000, \"\")\n assertEquals(5000, node1.distanceTo(node2))\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T16:09:19.997",
"Id": "447969",
"Score": "1",
"body": "In general, `sqrt(a²)` is the same as **`abs(a)`**. It's only the same as `a` here because we already did `abs()` when creating `a`. Of course, the corrected code for Euclidean distance need not (and should not) call `abs()` there, because negatives always square to a positive value. It's not a language I know, but is there really no provided `hypot()` function such as exists in C?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T16:14:36.177",
"Id": "447973",
"Score": "0",
"body": "Parp! goot spot"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T16:14:50.123",
"Id": "447974",
"Score": "0",
"body": "God how did I do that?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-03T14:23:33.007",
"Id": "230102",
"ParentId": "225644",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "230095",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T12:44:42.217",
"Id": "225644",
"Score": "3",
"Tags": [
"algorithm",
"kotlin"
],
"Title": "Kotlin Goal Oriented Action Planning"
}
|
225644
|
<p>I was actually kind of bored and since I'm studying some Python data structures I decided to make some size(MB) and time(secs) comparisons between different containers when conducting the operation of adding n items to each container type.
I included:</p>
<ul>
<li>List appending</li>
<li>List initialization</li>
<li>List comprehensions</li>
<li>Array</li>
<li>Set comprehensions</li>
<li>Generator comprehensions</li>
<li>Dictionary comprehensions</li>
<li>Tuple</li>
<li>Set add</li>
<li>Dictionary assignment</li>
</ul>
<p>I hope you enjoy using it, since it's mainly for fun purposes and might give you some insight on efficiency.</p>
<pre><code>from time import time
from array import array
import sys
import operator
class MakeContainers:
"""Produce containers of different types."""
def __init__(self, n):
self.size = n
def get_appends(self):
"""Return time and size for appending a list."""
start_time = time()
sequence = []
for i in range(self.size):
sequence.append(i)
return time() - start_time, sys.getsizeof(sequence)
def get_initialization(self):
"""Return time and size for list initialization."""
start_time = time()
sequence = [None] * self.size
for i in range(self.size - 1):
sequence[i] = i
return time() - start_time, sys.getsizeof(sequence)
def get_list_comprehensions(self):
"""Return time and size for list comprehensions."""
start_time = time()
sequence = [x for x in range(self.size)]
return time() - start_time, sys.getsizeof(sequence)
def get_array(self):
"""Return array time and size."""
start_time = time()
sequence = array('i', [x for x in range(self.size)])
return time() - start_time, sys.getsizeof(sequence)
def get_generator_comprehensions(self):
"""Return generator comprehensions time and size."""
start_time = time()
sequence = (x for x in range(self.size))
return time() - start_time, sys.getsizeof(sequence)
def get_set_comprehensions(self):
"""Return set comprehensions time and size."""
start_time = time()
sequence = {x for x in range(self.size)}
return time() - start_time, sys.getsizeof(sequence)
def get_dictionary_comprehensions(self):
"""Return dictionary comprehensions time and size."""
start_time = time()
sequence = {x: x for x in range(self.size)}
return time() - start_time, sys.getsizeof(sequence)
def get_tuple(self):
"""Return time and size of making a tuple."""
start_time = time()
sequence = tuple(x for x in range(self.size))
return time() - start_time, sys.getsizeof(sequence)
def get_set_add(self):
"""Return time and size of adding items to a set."""
start_time = time()
sequence = set()
for i in range(self.size):
sequence.add(i)
return time() - start_time, sys.getsizeof(sequence)
def get_dictionary_assignment(self):
"""Return time and size of assigning values to a dictionary."""
start_time = time()
sequence = {}
for i in range(self.size):
sequence[i] = i
return time() - start_time, sys.getsizeof(sequence)
def test_containers(n):
"""Test containers of different types and print results for size n."""
test = MakeContainers(n)
size_rank = time_rank = 1
operation_index = 0
sizes = {}
times = {}
operations = [
'List appends', 'List initializations', 'List comprehensions', 'Array', 'Generator comprehensions',
'Set comprehensions', 'Dictionary comprehensions', 'Tuple', 'Set add', 'Dictionary assignment'
]
values = [
test.get_appends(), test.get_initialization(), test.get_list_comprehensions(), test.get_array(),
test.get_generator_comprehensions(), test.get_set_comprehensions(), test.get_dictionary_comprehensions(),
test.get_tuple(), test.get_set_add(), test.get_dictionary_assignment()
]
for value in values:
times[operations[operation_index]] = value[0]
sizes[operations[operation_index]] = value[1]
operation_index += 1
print('Size ranks:')
print(35 * '=')
for operation, size in sorted(sizes.items(), key=operator.itemgetter(1)):
print(f'Rank: {size_rank}')
print(f'Operation: {operation}\nSize: {size / 10 ** 6} MB.')
print(f'Number of items: {n}')
size_rank += 1
print(35 * '=')
print()
print('Time ranks:')
print(35 * '=')
for operation, timing in sorted(times.items(), key=operator.itemgetter(1)):
print(f'Rank: {time_rank}')
print(f'Operation: {operation}\nTime: {timing} seconds.')
print(f'Number of items: {n}')
time_rank += 1
print(35 * '=')
if __name__ == '__main__':
st_time = time()
test_containers(10 ** 7)
print(f'Total time: {time() - st_time} seconds.')
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T20:00:33.660",
"Id": "438262",
"Score": "0",
"body": "And the winners are ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T20:14:36.660",
"Id": "438265",
"Score": "1",
"body": "Generators on top of course, followed by list comprehensions and intializations and tupling in terms of speed... sets and dictionaries are worst in terms of size. and btw there is a window of like 4 seconds between list comprehensions and list appending (n = 10 ** 8)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T20:28:17.663",
"Id": "438272",
"Score": "0",
"body": "test run on macbook pro 2015 2.7 GHz Intel Core i5 8 GB 1867 MHz DDR3"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T22:54:37.537",
"Id": "438442",
"Score": "0",
"body": "Two problems. #1) `get_generator_comprehensions()` creates a generator that is never iterated over. It is like saying \"get ready to count to 10 million. You ready? Great! How much time has that taken you?\" You haven't done any counting yet. #2) `sys.getsizeof()` returns the size of the container, but not (necessarily) the contents, because the contents are (usually) references to other objects, so may not be \"owned\" by the container. `array.array()` is an exception. It directly contains the values it stores. Memory wise, it looks 2x better than a list, but is actually **9x** better!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T23:34:39.097",
"Id": "438447",
"Score": "0",
"body": "@AJNeufeld yeah, I know I just included the generator for fun purposes, I know it does not use any memory or anything and as I'm not the hardcore programmer type yet, I still do not see any significant importance to arrays in Python because Python lists in my narrow perspective, do most of the work, so can you point a few things/applications to arrays where they are better than lists or must be applied?"
}
] |
[
{
"body": "<p>There is a lot of repetition in your methods and the only reason you have a class at all is so you can pass the size. Instead I would make this into standalone functions to which you can add a <a href=\"https://realpython.com/primer-on-python-decorators/\" rel=\"nofollow noreferrer\">decorator</a>. The functions themselves, together with the decorator, I would put into another module.</p>\n\n<p>I would also use <a href=\"https://docs.python.org/3/library/time.html#time.perf_counter\" rel=\"nofollow noreferrer\"><code>time.perf_counter</code></a> as it makes sure to use the best time resolution available on the system the code is running.</p>\n\n<pre><code>from array import array\nfrom functools import wraps\nfrom time import perf_counter\nfrom sys import getsizeof\n\ndef time_and_memory(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n start = perf_counter()\n ret = func(*args, **kwargs)\n return perf_counter() - start, getsizeof(ret)\n return wrapper\n\n\n@time_and_memory\ndef list_append(n):\n \"\"\"list append\"\"\"\n sequence = []\n for i in range(n):\n sequence.append(i)\n return sequence\n\n\n@time_and_memory\ndef list_pre_initialized(n):\n \"\"\"list pre-initialized\"\"\"\n sequence = [None] * n\n for i in range(n - 1):\n sequence[i] = i\n return sequence\n\n\n@time_and_memory\ndef list_comprehension(n):\n \"\"\"list comprehension\"\"\"\n return [x for x in range(n)]\n\n\n@time_and_memory\ndef array_int(n):\n \"\"\"array.array with integers\"\"\"\n return array('i', [x for x in range(n)])\n\n\n@time_and_memory\ndef generator_expression(n):\n \"\"\"generator expression\"\"\"\n return (x for x in range(n))\n\n\n@time_and_memory\ndef range_object(n):\n \"\"\"range\"\"\"\n return range(n)\n\n\n@time_and_memory\ndef set_comprehension(n):\n \"\"\"set comprehension\"\"\"\n return {x for x in range(n)}\n\n\n@time_and_memory\ndef dictionary_comprehension(n):\n \"\"\"dictionary comprehension\"\"\"\n return {x: x for x in range(n)}\n\n\n@time_and_memory\ndef tuple_constructor(n):\n \"\"\"tuple\"\"\"\n return tuple(x for x in range(n))\n\n\n@time_and_memory\ndef set_add(n):\n \"\"\"set add\"\"\"\n s = set()\n s_add = s.add\n for i in range(n):\n s_add(i)\n return s\n\n\n@time_and_memory\ndef dict_assignment(n):\n \"\"\"dict assign\"\"\"\n sequence = {}\n for i in range(n):\n sequence[i] = i\n return sequence\n\n\nall_funcs = [list_append, list_pre_initialized, list_comprehension, array_int,\n generator_expression, range_object, set_comprehension,\n dictionary_comprehension, tuple_constructor, set_add, dict_assignment]\n</code></pre>\n\n<p>I also added the <code>range</code> object and interned <code>set.add</code> before the loop to slightly speed it up, just for fun.</p>\n\n<p>As an alternative to the decorator, you could also just have a function that runs a given function with the given arguments and returns the time and memory size:</p>\n\n<pre><code>def get_time_and_memory(func, *args, **kwargs):\n start = perf_counter()\n ret = func(*args, **kwargs)\n return perf_counter() - start, getsizeof(ret)\n</code></pre>\n\n<p>Then you call this on all inputs:</p>\n\n<pre><code>for n in values:\n for func in all_funcs:\n time, size = get_time_and_memory(func, n)\n ...\n</code></pre>\n\n<hr>\n\n<p>The analyzing script can then be quite short. I would read all times and sizes into one data structure. I generated logarithmically spaced values using <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.logspace.html\" rel=\"nofollow noreferrer\"><code>numpy.logspace</code></a> and saved the results in a <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html\" rel=\"nofollow noreferrer\"><code>pandas.DataFrame</code></a>. I also added some plotting (using <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html\" rel=\"nofollow noreferrer\"><code>matplotlib</code></a>). Note that I (ab)used the docstring as the label in the plot.</p>\n\n<pre><code>import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nfrom python_containers_funcs import all_funcs\n\n\ndef test_containers(values):\n df = pd.DataFrame(columns=[\"func\", \"n\", \"time\", \"size\"])\n for n in values:\n for func in all_funcs:\n time, size = func(n)\n df = df.append({\"func\": func.__doc__, \"n\": n,\n \"time\": time, \"size\": size / 10**6},\n ignore_index=True)\n return df\n\n\ndef plot_results(df):\n fig = plt.figure()\n ax1 = plt.subplot(2, 2, 1)\n ax2 = plt.subplot(2, 2, 3)\n\n for group, gdf in df.groupby(\"func\"):\n # print(group)\n ax1.plot(gdf[\"n\"], gdf[\"time\"], label=group)\n ax2.plot(gdf[\"n\"], gdf[\"size\"], label=group)\n ax1.set_xlabel(\"n\")\n ax1.set_ylabel(\"Time [s]\")\n ax1.set_xscale(\"log\")\n ax1.set_yscale(\"log\")\n ax1.legend(bbox_to_anchor=(1.04, 1), borderaxespad=0)\n ax2.set_xlabel(\"n\")\n ax2.set_ylabel(\"Memory size [MB]\")\n ax2.set_xscale(\"log\")\n ax2.set_yscale(\"log\")\n return fig\n\n\nif __name__ == \"__main__\":\n values = np.logspace(1, 6, dtype=int)\n df = test_containers(values)\n print(\"Sorted by time [s]:\")\n print(df.groupby(\"func\").time.max().sort_values())\n print(\"\\nSorted by memory size [MB]:\")\n print(df.groupby(\"func\")[\"size\"].max().sort_values())\n fig = plot_results(df)\n plt.show()\n</code></pre>\n\n<p>This produces the following output in the terminal:</p>\n\n<pre><code>Sorted by time [s]:\nfunc\ngenerator expression 0.000032\nrange 0.000036\nlist comprehension 0.160947\nlist pre-initialized 0.236695\nset comprehension 0.264900\ntuple 0.312254\narray.array with integers 0.350580\ndictionary comprehension 0.353248\nset add 0.398240\ndict assign 0.412190\nlist append 0.418838\nName: time, dtype: float64\n\nSorted by memory size [MB]:\nfunc\nrange 0.000048\ngenerator expression 0.000088\narray.array with integers 4.000064\ntuple 8.000048\nlist pre-initialized 8.000064\nlist append 8.697464\nlist comprehension 8.697464\nset add 33.554656\nset comprehension 33.554656\ndict assign 41.943144\ndictionary comprehension 41.943144\nName: size, dtype: float64\n</code></pre>\n\n<p>And the following figure, which is admittedly a bit hard to read with this many lines.</p>\n\n<p><a href=\"https://i.stack.imgur.com/qEwMM.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/qEwMM.png\" alt=\"enter image description here\"></a></p>\n\n<p>Fun fact: the memory footprint of <code>range</code> is even smaller than that of a generator expression, since it only needs to store <code>start, stop, step</code>, whereas the generator needs to store the entire state (which in this case includes a <code>range</code> object, but also other objects).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T08:45:02.390",
"Id": "438345",
"Score": "1",
"body": "You can make a decorator for a class which applies a decorator to all methods of that class. You don't need to necessarily split them up."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T08:47:50.300",
"Id": "438346",
"Score": "0",
"body": "@HoboProber True. That would be the only reason to put it into a class, though, so I would hesitate a bit before doing that. Where to draw the line between \"Write More Classes\" and \"Stop Writing Classes\" is a matter of debate and personal opinion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T08:57:42.287",
"Id": "438348",
"Score": "0",
"body": "That's very informative, thank you. As I'm a beginner, I'm not too familiar with decorators, pandas and matplotlib, actually I really wanted to make a plot but I wasn't sure how to do it. And generally I do not like classes, I used a class for readabilty, because at first I just did only one function(which sucks of course) lots of repetition, that's why I then changed to a class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T12:23:26.140",
"Id": "438374",
"Score": "0",
"body": "@emadboctor I added a link to a tutorial about decorators and how to do a version without decorators."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T12:37:11.037",
"Id": "438375",
"Score": "1",
"body": "@Graipher thanks a lot for the very thorough review, I'll check the link and btw I'm reading a technical O'Reilly book about Python as well sooner or later I'll come across the decorators and whatever other features."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T22:57:40.473",
"Id": "438443",
"Score": "2",
"body": "Two problems. #1) `generator_expression()` creates a generator that is never iterated over. It is like saying \"get ready to count to 10 million. You ready? Great! How much time has that taken you?\" You haven't done any counting yet. #2) `sys.getsizeof()` returns the size of the container, but not (necessarily) the contents, because the contents are (usually) references to other objects, so may not be \"owned\" by the container. `array.array()` is an exception. It directly contains the values it stores. Memory wise, it looks 2x better than a list, but is actually **9x** better!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T23:01:26.283",
"Id": "438445",
"Score": "2",
"body": "@AJNeufeld 1) I am aware. However, that is how it is in the OP, and I took that to be on purpose. 2) True. I have not looked into it, but would something like `getsizeof(sequence) + sum(map(getsizeof, sequence))` work (disregarding for now that this *would* iterate over the generator)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T23:02:36.293",
"Id": "438446",
"Score": "1",
"body": "With, `x = [i for i in range(1_000_000)]`, then `getsizeof(x) + sum(getsizeof(e) for e in x)` return `36697460`. With `y = array('i', (x for x in range(1_000_000)))`, then `getsizeof(y)` return `4091932`. Advantage of `array.array()` is `36697460 / 4091932` which is `8.968247761693009`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T23:57:07.390",
"Id": "438448",
"Score": "0",
"body": "@AJNeufeld yeah, I know I just included the generator for fun purposes, I know it does not use any memory or anything and as I'm not the hardcore programmer type yet, I still do not see any significant importance to arrays in Python because Python lists in my narrow perspective, do most of the work, so can you point a few things/applications to arrays where they are better than lists or must be applied?"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T08:39:48.537",
"Id": "225707",
"ParentId": "225647",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "225707",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T13:24:35.057",
"Id": "225647",
"Score": "8",
"Tags": [
"python",
"python-3.x",
"benchmarking"
],
"Title": "Measure time and space requirements of different Python containers"
}
|
225647
|
<p>Which of the 2 solutions is written better? Personally I prefer the one line method but it does make it slightly more difficult to debug. Is perhaps doing it the long way first then refactoring to the second method once we know all is tested to be working.</p>
<p>Please note Environment var "FT_SOURCE" is set to "c:\filemover\"</p>
<p><strong>Original solution...</strong> </p>
<pre><code>func ensureDirold(dirName string) (string, error) {
err := os.Mkdir(dirName, os.ModeDir)
if err == nil || os.IsExist(err) {
return dirName, nil
} else {
return dirName, err
}
}
</code></pre>
<p>Usage...</p>
<pre><code>func OldWay() {
dir := os.Getenv("FT_SOURCE") //is set to c:\filemover
fmt.Print(ensureDirold(dir))
_, err := os.Create(dir + "myfile-old.txt")
check(err)
}
</code></pre>
<p><strong>Alternate Solution...</strong></p>
<pre><code>type strerr struct {
str string
err error
}
func ensureDirnew(dirName string) strerr {
err := os.Mkdir(dirName, os.ModeDir)
if err == nil || os.IsExist(err) {
return strerr{
str: dirName,
err: nil,
}
} else {
return strerr{
str: dirName,
err: err,
}
}
}
</code></pre>
<p>Usage...</p>
<pre><code>func NewWay() {
_, err := os.Create(ensureDirnew(os.Getenv("FT_SOURCE")).str + "myfile.txt")
check(err)
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T14:03:12.173",
"Id": "438199",
"Score": "0",
"body": "Instead of `dir + \"myfile-old.txt\"` it should be `filepath.Join(dir, \"myfile-old.txt\")`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T14:07:18.503",
"Id": "438200",
"Score": "0",
"body": "To me it makes no sense that `ensureDir` returns it's argument. It's asking a boolean yes/no question (that can possibly fail). Your \"alternate\" doesn't seem at all idiomatic to me and you appear to completely ignore any error from `ensureDirnew`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T14:14:18.563",
"Id": "438201",
"Score": "0",
"body": "@Dave C - Thanks for your feedback, are you saying what I am trying to achieve is not desirable or purely my solutions does it badly?"
}
] |
[
{
"body": "<blockquote>\n <p>Create a directory if it doesn't exist.</p>\n \n <p>Don't report an error if the directory exists.</p>\n</blockquote>\n\n<hr>\n\n<p>Isn't that a simple wrapper for the Go standard library <code>os.Mkdir</code> function?</p>\n\n<p>For example,</p>\n\n<pre><code>// mkdir, like os.Mkdir, creates a new directory\n// with the specified name and permission bits.\n// If the directory exists, mkdir returns nil.\nfunc mkdir(name string, perm os.FileMode) error {\n err := os.Mkdir(name, perm)\n if err != nil {\n if !os.IsExist(err) {\n return err\n }\n }\n return nil\n}\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p>Personally I prefer the one line method.</p>\n</blockquote>\n\n<p>In Go, we favor readability and simplicity for correct and maintainable code. Use the Go idiom for creating a file:</p>\n\n<pre><code>f, err := Create(fileName)\nif err != nil {\n // handle error\n}\ndefer f.Close()\n</code></pre>\n\n<p>For your usage, use a wrapper for the Go standard library <code>os.Create</code> function.</p>\n\n<p>For example,</p>\n\n<pre><code>// createFT, like os.Create, creates the named file with mode 0666 (before umask),\n// truncating it if it already exists.\n// The file is created in the directory named in the FT_SOURCE environment variable.\nfunc createFT(fileName string) (*os.File, error) {\n dirKey := \"FT_SOURCE\"\n dirName, ok := os.LookupEnv(dirKey)\n if !ok {\n err := fmt.Errorf(\"%s environmemt variable not found\", dirKey)\n return nil, err\n }\n\n perm := os.FileMode(0666)\n err := mkdir(dirName, perm)\n if err != nil {\n return nil, err\n }\n\n f, err := os.Create(filepath.Join(dirName, fileName))\n if err != nil {\n return nil, err\n }\n return f, nil\n}\n</code></pre>\n\n<p>Functions are used to encapsulate implementation details. Functions can also be used to hide complexity and \"ugly\" code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T11:11:36.230",
"Id": "225714",
"ParentId": "225651",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "225714",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T13:44:53.700",
"Id": "225651",
"Score": "2",
"Tags": [
"comparative-review",
"error-handling",
"file-system",
"go"
],
"Title": "Go functions to create a directory if it doesn't exist"
}
|
225651
|
<p>The cofactor of a 4×4 matrix can be used to convert a "regular geometry" matrix into the matrix that transforms the normals. It's an alternative to the common inverse-transpose pattern. In this post I use row-major matrixes.</p>
<p>Here is reference scalar code from <a href="https://github.com/graphitemaster/normals_revisited" rel="nofollow noreferrer">https://github.com/graphitemaster/normals_revisited</a></p>
<blockquote>
<pre><code>float minor(const float m[16], int r0, int r1, int r2, int c0, int c1, int c2) {
return m[4*r0+c0] * (m[4*r1+c1] * m[4*r2+c2] - m[4*r2+c1] * m[4*r1+c2]) -
m[4*r0+c1] * (m[4*r1+c0] * m[4*r2+c2] - m[4*r2+c0] * m[4*r1+c2]) +
m[4*r0+c2] * (m[4*r1+c0] * m[4*r2+c1] - m[4*r2+c0] * m[4*r1+c1]);
}
void cofactor(const float src[16], float dst[16]) {
dst[ 0] = minor(src, 1, 2, 3, 1, 2, 3);
dst[ 1] = -minor(src, 1, 2, 3, 0, 2, 3);
dst[ 2] = minor(src, 1, 2, 3, 0, 1, 3);
dst[ 3] = -minor(src, 1, 2, 3, 0, 1, 2);
dst[ 4] = -minor(src, 0, 2, 3, 1, 2, 3);
dst[ 5] = minor(src, 0, 2, 3, 0, 2, 3);
dst[ 6] = -minor(src, 0, 2, 3, 0, 1, 3);
dst[ 7] = minor(src, 0, 2, 3, 0, 1, 2);
dst[ 8] = minor(src, 0, 1, 3, 1, 2, 3);
dst[ 9] = -minor(src, 0, 1, 3, 0, 2, 3);
dst[10] = minor(src, 0, 1, 3, 0, 1, 3);
dst[11] = -minor(src, 0, 1, 3, 0, 1, 2);
dst[12] = -minor(src, 0, 1, 2, 1, 2, 3);
dst[13] = minor(src, 0, 1, 2, 0, 2, 3);
dst[14] = -minor(src, 0, 1, 2, 0, 1, 3);
dst[15] = minor(src, 0, 1, 2, 0, 1, 2);
}
</code></pre>
</blockquote>
<p>With SSE it could be implemented as:</p>
<pre><code>void cofactorSSE(const float src[16], float dst[16]) {
__m128 r0 = _mm_load_ps(&src[0]);
__m128 r1 = _mm_load_ps(&src[4]);
__m128 r2 = _mm_load_ps(&src[8]);
__m128 r3 = _mm_load_ps(&src[12]);
__m128 r0_0001 = _mm_shuffle_ps(r0, r0, _MM_SHUFFLE(0, 0, 0, 1));
__m128 r1_0001 = _mm_shuffle_ps(r1, r1, _MM_SHUFFLE(0, 0, 0, 1));
__m128 r2_0001 = _mm_shuffle_ps(r2, r2, _MM_SHUFFLE(0, 0, 0, 1));
__m128 r3_0001 = _mm_shuffle_ps(r3, r3, _MM_SHUFFLE(0, 0, 0, 1));
__m128 r0_1122 = _mm_shuffle_ps(r0, r0, _MM_SHUFFLE(1, 1, 2, 2));
__m128 r1_1122 = _mm_shuffle_ps(r1, r1, _MM_SHUFFLE(1, 1, 2, 2));
__m128 r2_1122 = _mm_shuffle_ps(r2, r2, _MM_SHUFFLE(1, 1, 2, 2));
__m128 r3_1122 = _mm_shuffle_ps(r3, r3, _MM_SHUFFLE(1, 1, 2, 2));
__m128 r0_2333 = _mm_shuffle_ps(r0, r0, _MM_SHUFFLE(2, 3, 3, 3));
__m128 r1_2333 = _mm_shuffle_ps(r1, r1, _MM_SHUFFLE(2, 3, 3, 3));
__m128 r2_2333 = _mm_shuffle_ps(r2, r2, _MM_SHUFFLE(2, 3, 3, 3));
__m128 r3_2333 = _mm_shuffle_ps(r3, r3, _MM_SHUFFLE(2, 3, 3, 3));
__m128 odd = _mm_set_ps(0.0, -0.0, 0.0, -0.0);
__m128 even = _mm_set_ps(-0.0, 0.0, -0.0, 0.0);
__m128 res0 = _mm_mul_ps(_mm_mul_ps(r1_0001, r2_1122), r3_2333);
__m128 res1 = _mm_mul_ps(_mm_mul_ps(r0_0001, r2_1122), r3_2333);
__m128 res2 = _mm_mul_ps(_mm_mul_ps(r0_0001, r1_1122), r3_2333);
__m128 res3 = _mm_mul_ps(_mm_mul_ps(r0_0001, r1_1122), r2_2333);
res0 = _mm_add_ps(res0, _mm_mul_ps(_mm_mul_ps(r1_1122, r2_2333), r3_0001));
res1 = _mm_add_ps(res1, _mm_mul_ps(_mm_mul_ps(r0_1122, r2_2333), r3_0001));
res2 = _mm_add_ps(res2, _mm_mul_ps(_mm_mul_ps(r0_1122, r1_2333), r3_0001));
res3 = _mm_add_ps(res3, _mm_mul_ps(_mm_mul_ps(r0_1122, r1_2333), r2_0001));
res0 = _mm_add_ps(res0, _mm_mul_ps(_mm_mul_ps(r1_2333, r2_0001), r3_1122));
res1 = _mm_add_ps(res1, _mm_mul_ps(_mm_mul_ps(r0_2333, r2_0001), r3_1122));
res2 = _mm_add_ps(res2, _mm_mul_ps(_mm_mul_ps(r0_2333, r1_0001), r3_1122));
res3 = _mm_add_ps(res3, _mm_mul_ps(_mm_mul_ps(r0_2333, r1_0001), r2_1122));
res0 = _mm_sub_ps(res0, _mm_mul_ps(_mm_mul_ps(r1_2333, r2_1122), r3_0001));
res1 = _mm_sub_ps(res1, _mm_mul_ps(_mm_mul_ps(r0_2333, r2_1122), r3_0001));
res2 = _mm_sub_ps(res2, _mm_mul_ps(_mm_mul_ps(r0_2333, r1_1122), r3_0001));
res3 = _mm_sub_ps(res3, _mm_mul_ps(_mm_mul_ps(r0_2333, r1_1122), r2_0001));
res0 = _mm_sub_ps(res0, _mm_mul_ps(_mm_mul_ps(r1_1122, r2_0001), r3_2333));
res1 = _mm_sub_ps(res1, _mm_mul_ps(_mm_mul_ps(r0_1122, r2_0001), r3_2333));
res2 = _mm_sub_ps(res2, _mm_mul_ps(_mm_mul_ps(r0_1122, r1_0001), r3_2333));
res3 = _mm_sub_ps(res3, _mm_mul_ps(_mm_mul_ps(r0_1122, r1_0001), r2_2333));
res0 = _mm_sub_ps(res0, _mm_mul_ps(_mm_mul_ps(r1_0001, r2_2333), r3_1122));
res1 = _mm_sub_ps(res1, _mm_mul_ps(_mm_mul_ps(r0_0001, r2_2333), r3_1122));
res2 = _mm_sub_ps(res2, _mm_mul_ps(_mm_mul_ps(r0_0001, r1_2333), r3_1122));
res3 = _mm_sub_ps(res3, _mm_mul_ps(_mm_mul_ps(r0_0001, r1_2333), r2_1122));
_mm_store_ps(&dst[0], _mm_xor_ps(res0, even));
_mm_store_ps(&dst[4], _mm_xor_ps(res1, odd));
_mm_store_ps(&dst[8], _mm_xor_ps(res2, even));
_mm_store_ps(&dst[12], _mm_xor_ps(res3, odd));
}
</code></pre>
<p>But it's not that fast compared to scalar code, only about 2.6 times faster (compiled with MSVC 2010, tested on Haswell). Of course, there are many shuffles. Also a couple of spills, which don't help, but there are not as many as it naively looks like there might be (MSVC changes the order and interleaves the shuffles and their uses somewhat).</p>
<p>Can this be done more efficiently? For example, a trick to save some shuffles? SSE through SSE3 can definitely be used, AVX(2) answers are also interesting (but I will have to dual-wield two versions of the function). AVX512 as a bonus but I doubt it will see much use.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T16:40:20.933",
"Id": "438214",
"Score": "0",
"body": "You could use `restrict` (C11) in your parameters: `void cofactorSSE(const float [static restrict 16], float [static restrict 16])`. Maybe it would help optimizations. I would be surprised if MSVC supported it, though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T16:43:10.257",
"Id": "438216",
"Score": "0",
"body": "@CacahueteFrito isn't that a C thing technically? sorry for the C tag by the way someone else added it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T16:43:57.477",
"Id": "438217",
"Score": "0",
"body": "Ah sorry then. I saw the C tag :). GCC has it also in C++ as an extension (as `__restrict__`, but you can easily do the macro). Maybe other compilers also provide it as an extension."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T16:48:56.030",
"Id": "438218",
"Score": "0",
"body": "Also, if you care about performance, why not program the function in C (or Fortran or assembly) and just export it to C++ with an extern \"C\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T17:02:46.790",
"Id": "438219",
"Score": "1",
"body": "@CacahueteFrito I've tried `__restrict` now but it didn't do anything. I don't have an assembly version that's actually better, if you have one I can consider that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T17:25:15.553",
"Id": "438220",
"Score": "0",
"body": "No, I don't. I just thought that C would provide more tricks than C++ for such a low level function, but in this case it seems that `restrict` doesn't improve it, so that's all I could help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T12:49:01.033",
"Id": "438377",
"Score": "0",
"body": "@CacahueteFrito Visual Studio 2010 is not compliant with C++11, they didn't fully implement C++11 until VS 2013."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T14:00:30.130",
"Id": "225652",
"Score": "4",
"Tags": [
"c++",
"performance",
"matrix",
"simd",
"sse"
],
"Title": "4×4 cofactor in SSE"
}
|
225652
|
<p>I've created a simulator for the Premier League, which takes in all of the 20 teams and plays them against each other, recording the results and outputting a table at the end.</p>
<p>The skill levels are based off a prediction in <a href="https://www.telegraph.co.uk/football/2019/07/30/biggest-brains-sports-data-predict-premier-league-201920-season/" rel="noreferrer">an article by The Telegraph</a>.</p>
<p>I am wondering whether or not my code can be improved, condensed or even added to with other features. Very new to coding so expecting lots of repetition/errors.</p>
<pre><code>import math, random
# HIGHER RATED TEAM
higher = 1.148698355
# LOWER RATED TEAM
lower = 0.8705505633
# DEFINING THE TEAM CLASS
class Team:
def __init__(self, name, skill):
self.name = name
self.skill = skill
self.points = self.gf = self.ga = self.wins = self.draws = self.losses = 0
def add_goals(self, goals):
self.gf += goals
# INITIALISING ALL OF THE TEAMS - NAMES AND SKILL LEVELS
arsenal = Team("Arsenal", 16)
aston_villa = Team("Aston Villa", 6)
bournemouth = Team("AFC Bournemouth", 8)
brighton = Team("Brighton and Hove Albion", 5)
burnley = Team("Burnley", 4)
chelsea = Team("Chelsea", 17)
crystal_palace = Team("Crystal Palace", 11)
everton = Team("Everton", 14)
leicester = Team("Leicester City", 12)
liverpool = Team("Liverpool", 19)
man_city = Team("Manchester City", 20)
man_united = Team("Manchester United", 15)
newcastle = Team("Newcastle United", 3)
norwich = Team("Norwich City", 2)
sheffield_united = Team("Sheffield United", 1)
southampton = Team("Southampton", 7)
tottenham = Team("Tottenham Hotspur", 18)
watford = Team("Watford", 9)
west_ham = Team("West Ham United", 10)
wolves = Team("Wolverhampton Wanderers", 13)
# HOME/AWAY TEAMS FOR PLAYING EACH TIME AGAINST EACH OTHER
teams = [arsenal, aston_villa, bournemouth, brighton, burnley, chelsea,
crystal_palace, everton, leicester, liverpool, man_city, man_united,
newcastle, norwich, sheffield_united, southampton, tottenham, watford,
west_ham, wolves]
# PRINT ALL TEAMS' NAME AND SKILL
for team in teams:
print(team.name, team.skill)
# RANDOM SYSTEM FOR HOME GOALS
def home_score(home, away):
homeSkill = home.skill / 3
awaySkill = away.skill / 3
if homeSkill == awaySkill:
raise ValueError
if homeSkill > awaySkill:
homeGoals = 0
lambHome = higher ** (homeSkill - awaySkill)
z = random.random()
while z > 0:
z = z - (((lambHome ** homeGoals) * math.exp(-1 * lambHome)) /
math.factorial(homeGoals))
homeGoals += 1
return (homeGoals - 1)
if homeSkill < awaySkill:
homeGoals = 0
lambHome = higher ** (homeSkill - awaySkill)
z = random.random()
while z > 0:
z = z - (((lambHome ** homeGoals) * math.exp(-1 * lambHome)) /
math.factorial(homeGoals))
homeGoals += 1
return (homeGoals - 1)
# RANDOM SYSTEM FOR AWAY GOALS
def away_score(home, away):
homeSkill = home.skill / 3
awaySkill = away.skill / 3
if homeSkill == awaySkill:
return "Teams cannot play themselves!!!"
if awaySkill > homeSkill:
awayGoals = 0
lambAway = lower ** (homeSkill - awaySkill)
x = random.random()
while x > 0:
x = x - (((lambAway ** awayGoals) * math.exp(-1 * lambAway)) /
math.factorial(awayGoals))
awayGoals += 1
return (awayGoals - 1)
if awaySkill < homeSkill:
awayGoals = 0
lambAway = lower ** (homeSkill - awaySkill)
x = random.random()
while x > 0:
x = x - (((lambAway ** awayGoals) * math.exp(-1 * lambAway)) /
math.factorial(awayGoals))
awayGoals += 1
return (awayGoals - 1)
# LEAGUE SIZE AND SETTING UP THE LEAGUE
league_size = 20
POINTS = []
GOALS_FOR = []
GOALS_AGAINST = []
WINS =[]
DRAWS = []
LOSSES = []
for x in range(league_size):
POINTS += [0]
GOALS_FOR += [0]
GOALS_AGAINST += [0]
WINS += [0]
DRAWS += [0]
LOSSES += [0]
# PLAYING ALL TEAMS AGAINST EACH OTHER AND UPDATING STATISTICS
for x in range(league_size):
print("========================================")
print(teams[x].name + "'s home games: ")
print("========================================")
for y in range(league_size):
error = 0
try:
homeScore = home_score(teams[x], teams[y])
except ValueError:
pass
error += 1
try:
awayScore = away_score(teams[x], teams[y])
except ValueError:
pass
if error == 0:
print(teams[x].name, homeScore, ":", awayScore, teams[y].name)
GOALS_FOR[x] += homeScore
GOALS_FOR[y] += awayScore
GOALS_AGAINST[x] += awayScore
GOALS_AGAINST[y] += homeScore
if homeScore > awayScore:
WINS[x] += 1
LOSSES[y] += 1
POINTS[x] += 3
elif homeScore == awayScore:
DRAWS[x] += 1
DRAWS[y] += 1
POINTS[x] += 1
POINTS[y] += 1
else:
WINS[y] += 1
LOSSES[x] += 1
POINTS[y] += 3
else:
pass
# ASSIGNING STATISTICS TO EACH TEAM
for x in range(league_size):
teams[x].points = POINTS[x]
teams[x].gf = GOALS_FOR[x]
teams[x].ga = GOALS_AGAINST[x]
teams[x].wins = WINS[x]
teams[x].draws = DRAWS[x]
teams[x].losses = LOSSES[x]
sorted_teams = sorted(teams, key=lambda t: t.points, reverse=True)
# PRITNING THE FINAL LEAGUE TABLE
print("| TEAM | POINTS | WINS | DRAWS | LOSSES | GOALS FOR | GOALS AGAINST |")
for team in sorted_teams:
print("|",team.name," "*(24 - len(team.name)),"| ",team.points," "*(3 - len(str(team.points))),"| ",team.wins," "*(2 - len(str(team.wins))),"| ",
team.draws," "*(2 - len(str(team.draws))),"| ",team.losses," "*(3 - len(str(team.losses))),"| ",team.gf," "*(4 - len(str(team.gf))),"| ",
team.ga," "*(7 - len(str(team.ga))),"|")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T09:56:25.897",
"Id": "438358",
"Score": "9",
"body": "Think there's a typo in your code. It should be `arsenal = Team(\"Arsenal\", 20)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T10:00:14.560",
"Id": "438359",
"Score": "5",
"body": "Spotted the typo - should be ```arsenal = Team(\"Arsenal, 1)```"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T10:03:07.727",
"Id": "438360",
"Score": "3",
"body": "that hurts buddy"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T14:59:05.260",
"Id": "438392",
"Score": "6",
"body": "@ediblecode could be worse, I ran the code on [TIO](https://tio.run/#) and it took 120 attempts for Man Utd to win the league..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T12:42:39.477",
"Id": "438490",
"Score": "0",
"body": "@crazyloonybin That's commitment to the cause"
}
] |
[
{
"body": "<p>This looks good overall. For the code review, I'll start with general comments and then try to get into smaller details.</p>\n\n<p><strong>Documentation</strong></p>\n\n<p>Documentating the code looks like an easy task but doing it properly so that it actually adds interesting information without adding too much noise can be pretty hard.</p>\n\n<p>Let's see what could be improved here.</p>\n\n<p>For a start, you do not need to write the comments in upper case. it actually makes things harder to read.</p>\n\n<p>In order to document a module, a class, a function, a method, you can use docstrings. You'll find more details about this in <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"noreferrer\">PEP 257 -- Docstring Conventions</a>.</p>\n\n<p>As you document the code, a pretty common tip is to say that <a href=\"https://blog.codinghorror.com/code-tells-you-how-comments-tell-you-why/\" rel=\"noreferrer\">Code Tells You How, Comments Tell You Why</a>.</p>\n\n<p>Here are a few instances:</p>\n\n<ul>\n<li><code># DEFINING THE TEAM CLASS</code> tells you nothing that the code does not show. Having a docstring explaining the point of the Team class whould be more helpful.</li>\n<li><code># INITIALISING ALL OF THE TEAMS - NAMES AND SKILL LEVELS</code> - here again, we can easily see that this is initialising teams.</li>\n</ul>\n\n<p><strong>Style</strong></p>\n\n<p>Python has a <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">Style Guide called PEP 8</a>. It could be a good idea to read it and try to see what could be applied to your code. A good example to start with could be the variable names.</p>\n\n<p>You'll find various tools online to check your code compliancy to PEP 8 and/or to fix it.</p>\n\n<p><strong>Code organisation</strong></p>\n\n<p>It is good practice to split the definitions from your code such as functions and classes from the part of your code actually doing something when the script is called with <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\">an <code>if __name__ == \"__main__\":</code> guard</a>.</p>\n\n<p>This helps for the re-usability of your code (and also makes the organisation clearer/more conventional).</p>\n\n<p><strong>Improving <code>home_score</code> & <code>away_score</code></strong></p>\n\n<p>These 2 functions are complicated, pretty long and fairly similar.\nFor all these reasons, there is probably something we can improve in them.</p>\n\n<p>For a start, we could rename <code>z</code> into <code>x</code> to make the 2 functions even more similar and be able to see what differs from one to another.</p>\n\n<p>Same for <code>lambAway</code> and <code>lambHome</code> renamed into <code>lamb</code>.</p>\n\n<p><em>(Disclaimer: nothing here has been even remotely tested)</em></p>\n\n<p>At this stage, we have:</p>\n\n<pre><code>\ndef home_score(home, away):\n homeSkill = home.skill / 3\n awaySkill = away.skill / 3\n\n if homeSkill == awaySkill:\n raise ValueError\n\n if homeSkill > awaySkill:\n goals = 0\n lamb = higher ** (homeSkill - awaySkill)\n x = random.random()\n while x > 0:\n x = x - (((lamb ** goals) * math.exp(-1 * lamb)) / math.factorial(goals))\n goals += 1\n return (goals - 1)\n\n if homeSkill < awaySkill:\n goals = 0\n lamb = higher ** (homeSkill - awaySkill)\n x = random.random()\n while x > 0:\n x = x - (((lamb ** goals) * math.exp(-1 * lamb)) / math.factorial(goals))\n goals += 1\n\n return (goals - 1)\n\ndef away_score(home, away):\n homeSkill = home.skill / 3\n awaySkill = away.skill / 3\n\n if homeSkill == awaySkill:\n raise ValueError\n\n if awaySkill > homeSkill:\n goals = 0\n lamb = lower ** (homeSkill - awaySkill)\n x = random.random()\n while x > 0:\n x = x - (((lamb ** goals) * math.exp(-1 * lamb)) / math.factorial(goals))\n goals += 1\n return (goals - 1)\n\n if awaySkill < homeSkill:\n goals = 0\n lamb = lower ** (homeSkill - awaySkill)\n x = random.random()\n while x > 0:\n x = x - (((lamb ** goals) * math.exp(-1 * lamb)) / math.factorial(goals))\n goals += 1\n return (goals - 1)\n\n</code></pre>\n\n<p>which is not really that much better.</p>\n\n<p>Trying to factorise out the common parts from the <code>if homeSkill > awaySkill</code> and <code>if homeSkill < awaySkill</code>, it looks like we could have:</p>\n\n<pre><code>def home_score(home, away):\n homeSkill = home.skill / 3\n awaySkill = away.skill / 3\n\n if homeSkill == awaySkill:\n raise ValueError\n\n goals = 0\n lamb = higher ** (homeSkill - awaySkill)\n x = random.random()\n while x > 0:\n x = x - (((lamb ** goals) * math.exp(-1 * lamb)) / math.factorial(goals))\n goals += 1\n return (goals - 1)\n\n\ndef away_score(home, away):\n homeSkill = home.skill / 3\n awaySkill = away.skill / 3\n\n if homeSkill == awaySkill:\n raise ValueError\n\n goals = 0\n lamb = lower ** (homeSkill - awaySkill)\n x = random.random()\n while x > 0:\n x = x - (((lamb ** goals) * math.exp(-1 * lamb)) / math.factorial(goals))\n goals += 1\n return (goals - 1)\n</code></pre>\n\n<p>But we could go further and extract the common parts of the function in a different function:</p>\n\n<pre><code>def home_score(home, away):\n return generate_random_score(home.skill / 3, away.skill / 3, higher)\n\ndef away_score(home, away):\n return generate_random_score(home.skill / 3, away.skill / 3, lower)\n\ndef generate_random_score(home_skill, away_skill, param):\n if home_skill == away_skill:\n raise ValueError\n\n goals = 0\n lamb = param ** (home_skill - away_skill)\n x = random.random()\n while x > 0:\n x = x - (((lamb ** goals) * math.exp(-1 * lamb)) / math.factorial(goals))\n goals += 1\n return (goals - 1)\n</code></pre>\n\n<p>It looks pretty good so far but we can still improve details.</p>\n\n<p>For a start, it is clear now that <code>lower</code> and <code>higher</code> are not such great names. Maybe something mentionning <code>home</code> and <code>away</code> would be better.</p>\n\n<p>Also, maybe the 2 methods do not really correspond to what you want: what you usually want is to simulate a full game and not just the score for a team. You could define a function returning a tuple:</p>\n\n<pre><code>def generate_random_score(home, away):\n delta_skill = (home - away) / 3\n return (generate_random_goal_number(delta_skill, higher), generate_random_goal_number(delta_skill, lower))\n\n\ndef generate_random_goal_number(delta_skill, param):\n if delta_skill == 0:\n raise ValueError\n\n goals = 0\n lamb = param ** delta_skill\n x = random.random()\n while x > 0:\n x = x - (((lamb ** goals) * math.exp(-1 * lamb)) / math.factorial(goals))\n goals += 1\n return (goals - 1)\n</code></pre>\n\n<p>A tiny improvement could be to rewrite:</p>\n\n<pre><code>x = x - long_expression\n</code></pre>\n\n<p>as:</p>\n\n<pre><code>x -= long_expression\n</code></pre>\n\n<p><strong>Settings for the league</strong></p>\n\n<p>Havnig \"league_size = 20\" is a bit obscure and easy to break. You probably should have <code>league_size = len(teams)</code>.</p>\n\n<p>Also, in order to initialise the different arrays, you could have something like:</p>\n\n<pre><code> GOALS_AGAINST = [0] * league_size\n</code></pre>\n\n<p>Finally, the team list could be initialised directly without defining so many variables that won't get reused.</p>\n\n<p>You could write:</p>\n\n<pre><code>teams = [\n Team(\"Arsenal\", 16),\n Team(\"Aston Villa\", 6),\n Team(\"AFC Bournemouth\", 8),\n...\n]\n</code></pre>\n\n<p><strong>More code organisation</strong></p>\n\n<p>At the moment, you keep tracks of the stats for the teams in the class instances and in separate lists.</p>\n\n<p>It would probably make sense to define a function/method <code>simulate_game</code> taking 2 teams as parameters and that would take care of generating a score and updating the team stats accordingly.</p>\n\n<p>By the way, you do not necessarly need to keep track of the points. You could define a method in the <code>Team</code> objects to compute it on demand from the other statistics.</p>\n\n<p><strong>Special tip</strong></p>\n\n<p>I've said many things and there are still many things to say.</p>\n\n<p>For learning purposes (and because I may have gotten things wrong in a few places), it could be a good idea to try to perform the changes described on your side.</p>\n\n<p>Also, when random elements are involved, it can be hard to detect when you break something. My suggestion would be to initialise the random number generator with your favorite seed (for instance <code>random.seed(42)</code>), run your script, save the output and then keep that seed during your developments. If everything goes fine, the output should stay the same.</p>\n\n<p>It does NOT exactly mean that:</p>\n\n<ul>\n<li><p>it the output stays the same, nothing got broken</p></li>\n<li><p>if the output changes, something got broken</p></li>\n</ul>\n\n<p>but it does help to give you some confidence as you go.</p>\n\n<hr>\n\n<p>Here is the updated version of the code based on the comments above and more:</p>\n\n<pre><code>import math\nimport random\n\nrandom.seed(42) # Removing randomness\n\nclass Team:\n def __init__(self, name, skill):\n self.name = name\n self.skill = skill\n self.points = self.gf = self.ga = self.wins = self.draws = self.losses = 0\n\n\ndef generate_random_score(home, away):\n param_home = 1.148698355\n param_away = 0.8705505633\n delta_skill = (home.skill / 3 - away.skill / 3)\n return (generate_random_number_of_goals(delta_skill, param_home),\n generate_random_number_of_goals(delta_skill, param_away))\n\n\ndef generate_random_number_of_goals(delta_skill, param):\n if delta_skill == 0:\n raise ValueError\n goals = 0\n lamb = param ** delta_skill\n x = random.random()\n while x > 0:\n x = x - (((lamb ** goals) * math.exp(-1 * lamb)) / math.factorial(goals))\n goals += 1\n return (goals - 1)\n\n\ndef simulate_league(teams):\n \"\"\"Play all teams against each other and update statistics.\"\"\"\n for home_team in teams:\n print(\"========================================\")\n print(home_team.name + \"'s home games: \")\n print(\"========================================\")\n for away_team in teams:\n if home_team != away_team:\n home_score, away_score = generate_random_score(home_team, away_team)\n print(home_team.name, home_score, \":\", away_score, away_team.name)\n home_team.gf += home_score\n away_team.gf += away_score\n home_team.ga += away_score\n away_team.ga += home_score\n if home_score == away_score:\n home_team.draws += 1\n away_team.draws += 1\n home_team.points += 1\n away_team.points += 1\n else:\n winning, losing = (home_team, away_team) if (home_score > away_score) else (away_team, home_team)\n winning.wins += 1\n winning.points += 3\n losing.losses += 1\n\n\nif __name__ == \"__main__\":\n teams = [\n Team(\"Arsenal\", 16),\n Team(\"Aston Villa\", 6),\n Team(\"AFC Bournemouth\", 8),\n Team(\"Brighton and Hove Albion\", 5),\n Team(\"Burnley\", 4),\n Team(\"Chelsea\", 17),\n Team(\"Crystal Palace\", 11),\n Team(\"Everton\", 14),\n Team(\"Leicester City\", 12),\n Team(\"Liverpool\", 19),\n Team(\"Manchester City\", 20),\n Team(\"Manchester United\", 15),\n Team(\"Newcastle United\", 3),\n Team(\"Norwich City\", 2),\n Team(\"Sheffield United\", 1),\n Team(\"Southampton\", 7),\n Team(\"Tottenham Hotspur\", 18),\n Team(\"Watford\", 9),\n Team(\"West Ham United\", 10),\n Team(\"Wolverhampton Wanderers\", 13),\n ]\n\n for team in teams:\n print(team.name, team.skill)\n\n simulate_league(teams)\n\n # printing the final league table\n print(\"| TEAM | POINTS | WINS | DRAWS | LOSSES | GOALS FOR | GOALS AGAINST |\")\n for team in sorted(teams, key=lambda t: t.points, reverse=True):\n print(\"|\",team.name.ljust(25),\"|\",str(team.points).ljust(6),\"|\",str(team.wins).ljust(4),\"|\",\n str(team.draws).ljust(5),\"|\",str(team.losses).ljust(6),\"|\",str(team.gf).ljust(9),\"|\",\n str(team.ga).ljust(13),\"|\")\n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T09:47:41.873",
"Id": "438355",
"Score": "1",
"body": "Thank you very much! I am going to make some changes based on your advice and I will edit the post with my updated code!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T10:19:52.493",
"Id": "438364",
"Score": "3",
"body": "@woody101298 You shouldn't edit the code in the question after getting a review. For details read here: [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T10:33:11.677",
"Id": "438367",
"Score": "1",
"body": "@Georgy Thanks for letting me know, I'll post any updates in another 'answer' to this question!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T19:52:56.773",
"Id": "225680",
"ParentId": "225653",
"Score": "14"
}
},
{
"body": "<p>Very nice program for a beginner! Great attempt! Here are some points.</p>\n\n<h2>Imports</h2>\n\n<p>For multiple imports for the same module, you use <code>,</code></p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from x_module import y, z\n</code></pre>\n\n<p>But for our purpose, </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import math\nimport random\n</code></pre>\n\n<p>works better. Python is concerned about readability and space saving might not always be the best option.</p>\n\n<h2>Naming</h2>\n\n<p>Python follows a style convention known as <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a>. The normal variable naming convention can be summarised as:</p>\n\n<ul>\n<li>use snake_case instead of PascalCase or camelCase. <code>my_pencil</code> instead of <code>MyPencil</code> and <code>myPencil</code></li>\n<li>use CAPITAL for constants. PI = 3.14, as the value of this variable won't change but like pencils = [], pencils will be reduced and expanded.</li>\n</ul>\n\n<p>Some improvements</p>\n\n<p><code>homeSkill</code> -> <code>home_skill</code></p>\n\n<p><code>POINTS</code> -> <code>points</code> as we see points being modified at <code>POINTS += [0]</code></p>\n\n<p><code>higher = 1.148698355</code> -> <code>HIGHER = 1.148698355</code> since it is a constant</p>\n\n<h2>A note on objects</h2>\n\n<p>Since i see nowhere you needed to use the teams individually and since this is a simulation, teams could be defined as:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>teams = [\n Team(\"Arsenal\", 16),\n Team(\"Aston Villa\", 6),\n Team(\"AFC Bournemouth\", 8),\n ...,\n Team(\"Wolverhampton Wanderers\", 13)\n]\n</code></pre>\n\n<h2>String formatting</h2>\n\n<p>The table can be simplified.\nThis</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(\"| TEAM | POINTS | WINS | DRAWS | LOSSES | GOALS FOR | GOALS AGAINST |\")\n</code></pre>\n\n<p>can be written as</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(\"| {:<20} | {:^10} | {:^10} | {:^10} | {:^10} | {:^10} | {:^10} |\".format('TEAM',\n 'POINTS', 'WINS', 'DRAWS', 'LOSSES', 'GOALS FOR', 'GOALS')\n</code></pre>\n\n<p>so that the following loop can be simplified to</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for team in sorted_teams:\n print(\"| {:<20} | {:<10} | {:<10} | {:<10} | {:<10} | {:<10} | {:<10} |\".format(team.name, \n team.points, team.wins, team.draws, team.losses, team.gf, team.ga))\n</code></pre>\n\n<p>where <code><</code> means left align and <code>^</code> means align to the center.</p>\n\n<h2>Looping</h2>\n\n<pre class=\"lang-py prettyprint-override\"><code>league_size = 20\nPOINTS = []\nGOALS_FOR = []\n...\nfor x in range(league_size):\n POINTS += [0]\n ...\n</code></pre>\n\n<p>can be written as </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>league_size = 20\nPOINTS = [0] * league_size\nGOALS_FOR = [0] * league_size\n...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T09:48:18.173",
"Id": "438356",
"Score": "1",
"body": "Thank you for your help! I am going to do some updates based on advice and I will post them later!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T19:58:31.397",
"Id": "225681",
"ParentId": "225653",
"Score": "12"
}
},
{
"body": "<p>I won't comment on the code itself, since I am not a Python person, but in terms of your <em>approach</em>, I will say this:</p>\n\n<p>Using estimated table position seems like a poor predictor of performance, since it is has very low precision. It also does not allow for groupings of teams at a similar level. </p>\n\n<p>Take for example last season's top 3:</p>\n\n<pre><code>man_city = Team(\"Manchester City\", 20)\nliverpool = Team(\"Liverpool\", 19)\ntottenham = Team(\"Tottenham Hotspur\", 18)\n</code></pre>\n\n<p>Was the difference in quality between Man City and Liverpool somewhat similar to the difference in quality between Liverpool and Spurs? The points tally would suggest that it was not even close - Liverpool got ~34% more points than Spurs, while City only clinched the title by a single point.</p>\n\n<p>Similarly, six of last year's mid-table teams were separated by only 7 points.</p>\n\n<pre><code>52 Leicester\n52 West Ham\n50 Watford\n49 Crystal Palace\n45 Newcastle\n45 Bournemouth\n</code></pre>\n\n<p>Under your system, Leicester would be 5 \"skill points\" higher than Bournemouth - a seemingly huge gulf in class - while in reality the table would suggest that they're both at a similar level. Without a late equalizer in <a href=\"https://www.bbc.co.uk/sport/football/43178521\" rel=\"noreferrer\">this game</a>, these two would have even closer. When one goal has the potential to throw off your whole prediction, you know something's up. </p>\n\n<p>I suspect that a much better predictor would be the points tally obtained in the previous season. Of course, for the 3 promoted teams you will not have this information. For these, you could look at the historic difference between a previous season's Championship points tally against their Premier League performance the following season. If there's a correlation then you could use this to estimate a points tally.</p>\n\n<p>You could then start to factor in other factors such as net spend over the summer, number of arrivals and departures, etc. This may start to account for the fact that a team like Chelsea did well last season but have lost an expensive key player.</p>\n\n<p>You could of course start to go much deeper and start to analyse previous results individually and use that to predict the outcome of each game more accurately. Maybe Arsenal do well at home and poorly away, or Burnley get better results against stronger opposition, or a derby game generally has fewer goals than a normal one.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T10:42:51.387",
"Id": "225713",
"ParentId": "225653",
"Score": "7"
}
},
{
"body": "<p>I have incorporated advice from @Josay and @Abdur-Rahmaan Janhangeer and updated my code. I will also work on using a system to better set skill levels to teams so that the simulation becomes more accurate as @Michael suggested. Thank you for all your help on my first project.</p>\n\n<p>Changes include:</p>\n\n<ul>\n<li><p>cleaning up all of the formatting errors i.e. upper-case in the wrong places.</p></li>\n<li><p>home and away goals functions simplified and made into a single function as suggested by @Josay.</p></li>\n<li><p>using</p></li>\n</ul>\n\n<pre><code>if __name__ = \"__main__\"\n</code></pre>\n\n<p>to separate the functions from the code that will be run. </p>\n\n<ul>\n<li>cleaned up the table as suggested by @Abdur-Rahmaan Janhangeer.</li>\n</ul>\n\n<p>I have also included a goal difference concept to the league and I was wondering how I can sort the list of teams first by points and then by goal difference?</p>\n\n<p>Below is the full revised code: </p>\n\n<pre><code>import math\nimport random\n\nH_PARAMETER = 1.148698355\nA_PARAMETER = 0.8705505633\n\n\nclass Team:\n def __init__(self, name, skill):\n self.name = name\n self.skill = skill\n self.points = self.gf = self.ga = self.wins = self.draws = self.losses = self.gdiff = self.mp = 0\n\n\ndef generate_random_goals(delta_skill, parameter):\n if delta_skill == 0:\n raise ValueError\n goals = 0\n lamb = parameter ** (delta_skill)\n z = random.random()\n while z > 0:\n z = z - (((lamb ** goals) * math.exp(-1 * lamb)) /\n math.factorial(goals))\n goals += 1\n return goals - 1\n\n\ndef generate_random_score(home, away):\n delta_skill = (home.skill - away.skill) / 3\n return (generate_random_goals(delta_skill,\n H_PARAMETER), generate_random_goals(delta_skill, A_PARAMETER))\n\n\ndef simulate_league(teams):\n for home_team in teams:\n print(\"=\" * 50)\n print(home_team.name + \"'s home games: \")\n print(\"=\" * 50)\n for away_team in teams:\n if home_team == away_team:\n pass\n if home_team != away_team:\n home_score, away_score = generate_random_score(home_team, away_team)\n print(home_team.name, home_score, \":\", away_score, away_team.name)\n home_team.gf += home_score\n away_team.gf += away_score\n home_team.ga += away_score\n away_team.ga += home_score\n home_team.gdiff += (home_score - away_score)\n away_team.gdiff += (away_score - home_score)\n home_team.mp += 1\n away_team.mp += 1\n if home_score == away_score:\n home_team.draws += 1\n away_team.draws += 1\n home_team.points += 1\n away_team.points += 1\n if home_score > away_score:\n home_team.wins += 1\n away_team.losses += 1\n home_team.points += 3\n if away_score > home_score:\n away_team.wins += 1\n home_team.losses += 1\n away_team.points += 3\n\n\nif __name__ == \"__main__\":\n teams = [\n Team(\"Arsenal\", 16), Team(\"Aston Villa\", 6), Team(\"AFC Bournemouth\", 8), Team(\"Brighton and Hove Albion\", 5),\n Team(\"Burnley\", 4), Team(\"Chelsea\", 17), Team(\"Crystal Palace\", 11), Team(\"Everton\", 14),\n Team(\"Leicester City\", 12), Team(\"Liverpool\", 19), Team(\"Manchester City\", 20), Team(\"Manchester United\", 15),\n Team(\"Newcastle United\", 3), Team(\"Norwich City\", 2), Team(\"Sheffield United\", 1), Team(\"Southampton\", 7),\n Team(\"Tottenham Hotspur\", 18), Team(\"Watford\", 9), Team(\"West Ham United\", 10),\n Team(\"Wolverhampton Wanderers\", 13)\n ]\n\n for team in teams:\n print(team.name, team.skill)\n\n simulate_league(teams)\n\n sorted_teams = sorted(teams, key=lambda t: t.points, reverse=True)\n\n print(\"=\" * 108)\n print(\n \"| {:<25} | {:^4} | {:^3} | {:^3} | {:^3} | {:^4} | {:^4} | {:^4} | {:^6} |\".format(\"CLUB\", \"MP\", \"W\", \"D\",\n \"L\", \"GF\",\n \"GA\",\n \"GD\", \"PTS\"))\n for team in sorted_teams:\n print(\"| {:<25} | {:^4} | {:^3} | {:^3} | {:^3} | {:^4} | {:^4} | {:^4} | {:^6} |\".format(team.name, team.mp,\n team.wins,\n team.draws,\n team.losses,\n team.gf,\n team.ga, team.gdiff,\n team.points))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T15:39:37.577",
"Id": "438396",
"Score": "1",
"body": "A pleasure to read!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T20:40:57.130",
"Id": "438554",
"Score": "0",
"body": "I suggest you add methods on the `Team` class to record home/away games: `def record_home_score()` and `def record_away_score()`. This would move most of the code inside your `simulate_leage` function into the class, and make both sets of code more clear."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T13:27:04.753",
"Id": "225718",
"ParentId": "225653",
"Score": "5"
}
},
{
"body": "<p>At the end of my first year programming I developed the exact same program with Python as well.</p>\n\n<p>What I encourage you to do, and what I did, is to read the teams and their skill levels from a separate file. This way you can even prompt the user for which league they want to use.</p>\n\n<p>i.e.</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Which country's league do you wish to simulate?\n$ England\n</code></pre>\n\n<p>And it will look for the file called England.csv and read its content for clubs and skill levels.</p>\n\n<p>Also, read how many lines are in the file so that you can make the amount of clubs in the division dynamic and not simply 20 all the time.</p>\n\n<p>Good luck and happy programming!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T15:34:44.333",
"Id": "225724",
"ParentId": "225653",
"Score": "5"
}
},
{
"body": "<p>Further development...</p>\n\n<p>As @Michael suggested the skill levels previously used were fairly inaccurate and did not sufficiently describe the level of each team.</p>\n\n<p>I have used the previous year's point tally in the code below and also incorporated a method to re-run the season with the points tally simulated. For now, promoted teams are given skill levels just below the lowest positioned teams from the Premier League last season.</p>\n\n<pre><code>if __name__ == \"__main__\":\n teams = [\n Team(\"Arsenal\", 70),\n Team(\"Aston Villa\", 33),\n Team(\"AFC Bournemouth\", 45),\n Team(\"Brighton and Hove Albion\", 36),\n Team(\"Burnley\", 40),\n Team(\"Chelsea\", 72),\n Team(\"Crystal Palace\", 49),\n Team(\"Everton\", 54),\n Team(\"Leicester City\", 53),\n Team(\"Liverpool\", 97),\n Team(\"Manchester City\", 98),\n Team(\"Manchester United\", 66),\n Team(\"Newcastle United\", 46),\n Team(\"Norwich City\", 35),\n Team(\"Sheffield United\", 34),\n Team(\"Southampton\", 39),\n Team(\"Tottenham Hotspur\", 71),\n Team(\"Watford\", 50),\n Team(\"West Ham United\", 52),\n Team(\"Wolverhampton Wanderers\", 57)\n ]\n\n for team in teams:\n print(team.name, team.skill)\n\n simulate_league(teams)\n\n sorted_teams = sorted(teams, key=lambda t: t.points, reverse=True)\n\n print(\"=\" * 108)\n print(\n \"| {:<25} | {:^4} | {:^3} | {:^3} | {:^3} | {:^4} | {:^4} | {:^4} | {:^6} |\".format(\"CLUB\", \"MP\", \"W\", \"D\",\n \"L\", \"GF\",\n \"GA\",\n \"GD\", \"PTS\"))\n for team in sorted_teams:\n print(\"| {:<25} | {:^4} | {:^3} | {:^3} | {:^3} | {:^4} | {:^4} | {:^4} | {:^6} |\".format(team.name, team.mp,\n team.wins,\n team.draws,\n team.losses, team.gf,\n team.ga, team.gdiff,\n team.points))\n for team in teams:\n print(team.name, team.skill)\n team.gf = team.ga = team.gdiff = team.mp = team.wins = team.losses = team.draws = team.points = 0\n\n simulate_league(teams)\n\n sorted_teams = sorted(teams, key=lambda t: t.points, reverse=True)\n\n print(\"=\" * 108)\n print(\"| {:<25} | {:^4} | {:^3} | {:^3} | {:^3} | {:^4} | {:^4} | {:^4} | {:^6} |\".format(\"CLUB\", \"MP\", \"W\", \"D\",\n \"L\", \"GF\",\n \"GA\",\n \"GD\", \"PTS\"))\n for team in sorted_teams:\n print(\"| {:<25} | {:^4} | {:^3} | {:^3} | {:^3} | {:^4} | {:^4} | {:^4} | {:^6} |\".format(team.name, team.mp,\n team.wins,\n team.draws,\n team.losses, team.gf,\n team.ga, team.gdiff,\n team.points))\n</code></pre>\n\n<p>A small change was made to the goal-scoring function in order to allow for there to now be identical skill levels (in case two teams get the same point tally in the first simulated league).</p>\n\n<pre><code># Used this\nif home == away:\n# Instead of this\nif delta_skill == 0:\n</code></pre>\n\n<p>I am wondering how I could incorporate a new feature which introduces the possibility of teams suffering from injuries and therefore affecting their performance?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T20:42:21.160",
"Id": "225795",
"ParentId": "225653",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T14:33:16.600",
"Id": "225653",
"Score": "19",
"Tags": [
"python",
"beginner",
"python-3.x",
"simulation"
],
"Title": "Premier League simulation"
}
|
225653
|
<p>Basically I'm looking for a way to improve my code, and avoid making a lot of if statements and parameter combination manually, 'cause I need to return a query result depending in the parameters that were sent.</p>
<p>I've read some posts, and tried some stuffs but nothing that works.</p>
<p>For each if statement and param's combination a report or statistic is generated with the data collected from a data base with EntityFramework according to the params sent and it's displayed in a view to the user.</p>
<pre><code>public class MultipleParameterSearch
{
public string strCod { get; set; }
public string strRack { get; set; }
public string strPosi { get; set; }
public int? strLvl { get; set; }
public int? intCantMin { get; set; }
public int? intCantMax { get; set; }
}
public ActionResult MultipleParameterSearch(MultipleParameterSearch multiple)
{
if (multiple.strCod != null && multiple.strRack == null && multiple.strPosi == null && multiple.strLvl == null && multiple.intCantMin == null && multiple.intCantMax == null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
//getData method return a IQueryable<Model>
var x = getData(db)
.Where(a => a.CodProd == multiple.strCod && a.Stock > 0).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod == null && multiple.strRack != null && multiple.strPosi == null && multiple.strLvl == null && multiple.intCantMin == null && multiple.intCantMax == null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.Partida == multiple.strRack && a.Stock > 0).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod == null && multiple.strRack == null && multiple.strPosi != null && multiple.strLvl == null && multiple.intCantMin == null && multiple.intCantMax == null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.Pieza.Contains(multiple.strPosi) && a.Stock > 0).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod == null && multiple.strRack == null && multiple.strPosi == null && multiple.strLvl != null && multiple.intCantMin == null && multiple.intCantMax == null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.Pieza.Substring(1).Contains(multiple.strLvl.ToString()) && a.Stock > 0).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod == null && multiple.strRack == null && multiple.strPosi == null && multiple.strLvl == null && multiple.intCantMin != null && multiple.intCantMax == null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.Stock >= multiple.intCantMin).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod == null && multiple.strRack == null && multiple.strPosi == null && multiple.strLvl == null && multiple.intCantMin == null && multiple.intCantMax != null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db).Where(a => a.Stock <= multiple.intCantMax).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod == null && multiple.strRack == null && multiple.strPosi == null && multiple.strLvl == null && multiple.intCantMin != null && multiple.intCantMax != null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var q = getData(db).Where(x => x.Stock >= multiple.intCantMin && x.Stock <= multiple.intCantMax).ToList();
return PartialView("multi", q);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod == null && multiple.strRack == null && multiple.strPosi == null && multiple.strLvl != null && multiple.intCantMin == null && multiple.intCantMax != null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.Stock <= multiple.intCantMax && a.Pieza.Substring(1).Contains(multiple.strLvl.ToString())).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod == null && multiple.strRack == null && multiple.strPosi != null && multiple.strLvl == null && multiple.intCantMin == null && multiple.intCantMax != null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.Stock <= multiple.intCantMax && a.Pieza.Contains(multiple.strPosi)).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod == null && multiple.strRack != null && multiple.strPosi == null && multiple.strLvl == null && multiple.intCantMin == null && multiple.intCantMax != null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.Stock <= multiple.intCantMax && a.Partida == multiple.strRack).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod != null && multiple.strRack == null && multiple.strPosi == null && multiple.strLvl == null && multiple.intCantMin == null && multiple.intCantMax != null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.Stock <= multiple.intCantMax && a.CodProd == multiple.strCod).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod != null && multiple.strRack != null && multiple.strPosi == null && multiple.strLvl == null && multiple.intCantMin == null && multiple.intCantMax == null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.CodProd == multiple.strCod && a.Partida == multiple.strRack && a.Stock > 0).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod != null && multiple.strRack == null && multiple.strPosi != null && multiple.strLvl == null && multiple.intCantMin == null && multiple.intCantMax == null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.CodProd == multiple.strCod && a.Pieza.Contains(multiple.strPosi) && a.Stock > 0).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod != null && multiple.strRack == null && multiple.strPosi == null && multiple.strLvl != null && multiple.intCantMin == null && multiple.intCantMax == null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.CodProd == multiple.strCod && a.Pieza.Substring(1).Contains(multiple.strLvl.ToString()) && a.Stock > 0).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod != null && multiple.strRack == null && multiple.strPosi == null && multiple.strLvl == null && multiple.intCantMin != null && multiple.intCantMax == null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.CodProd == multiple.strCod && a.Stock >= multiple.intCantMin).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod == null && multiple.strRack == null && multiple.strPosi == null && multiple.strLvl != null && multiple.intCantMin != null && multiple.intCantMax == null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.Stock >= multiple.intCantMin && a.Pieza.Substring(1).Contains(multiple.strLvl.ToString())).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod == null && multiple.strRack == null && multiple.strPosi != null && multiple.strLvl == null && multiple.intCantMin != null && multiple.intCantMax == null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.Stock >= multiple.intCantMin && a.Pieza.Contains(multiple.strPosi)).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod == null && multiple.strRack != null && multiple.strPosi == null && multiple.strLvl == null && multiple.intCantMin != null && multiple.intCantMax == null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.Stock >= multiple.intCantMin && a.Partida == multiple.strRack).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod == null && multiple.strRack != null && multiple.strPosi != null && multiple.strLvl == null && multiple.intCantMin == null && multiple.intCantMax == null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.Partida == multiple.strRack && a.Pieza.Contains(multiple.strPosi) && a.Stock > 0).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod == null && multiple.strRack != null && multiple.strPosi == null && multiple.strLvl != null && multiple.intCantMin == null && multiple.intCantMax == null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.Partida == multiple.strRack && a.Pieza.Substring(1).Contains(multiple.strLvl.ToString()) && a.Stock > 0).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod == null && multiple.strRack == null && multiple.strPosi != null && multiple.strLvl != null && multiple.intCantMin == null && multiple.intCantMax == null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.Pieza == String.Concat(multiple.strPosi,multiple.strLvl) && a.Stock > 0).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod != null && multiple.strRack != null && multiple.strPosi != null && multiple.strLvl == null && multiple.intCantMin == null && multiple.intCantMax == null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.CodProd == multiple.strCod && a.Partida == multiple.strRack && a.Pieza.Contains(multiple.strPosi) && a.Stock > 0).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod != null && multiple.strRack != null && multiple.strPosi == null && multiple.strLvl != null && multiple.intCantMin == null && multiple.intCantMax == null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.CodProd == multiple.strCod && a.Partida == multiple.strRack && a.Pieza.Substring(1).Contains(multiple.strLvl.ToString()) && a.Stock > 0).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod != null && multiple.strRack != null && multiple.strPosi == null && multiple.strLvl == null && multiple.intCantMin != null && multiple.intCantMax == null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.CodProd == multiple.strCod && a.Partida == multiple.strRack && a.Stock >= multiple.intCantMin).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod != null && multiple.strRack != null && multiple.strPosi == null && multiple.strLvl == null && multiple.intCantMin == null && multiple.intCantMax != null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.CodProd == multiple.strCod && a.Partida == multiple.strRack && a.Stock <= multiple.intCantMax).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod != null && multiple.strRack == null && multiple.strPosi != null && multiple.strLvl != null && multiple.intCantMin == null && multiple.intCantMax == null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.CodProd == multiple.strCod && a.Pieza == String.Concat(multiple.strPosi, multiple.strLvl) && a.Stock > 0).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod != null && multiple.strRack == null && multiple.strPosi != null && multiple.strLvl == null && multiple.intCantMin != null && multiple.intCantMax == null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.CodProd == multiple.strCod && a.Pieza.Contains(multiple.strPosi) && a.Stock >= multiple.intCantMin).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod != null && multiple.strRack == null && multiple.strPosi != null && multiple.strLvl == null && multiple.intCantMin == null && multiple.intCantMax != null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.CodProd == multiple.strCod && a.Pieza.Contains(multiple.strPosi) && a.Stock <= multiple.intCantMax).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod != null && multiple.strRack == null && multiple.strPosi == null && multiple.strLvl != null && multiple.intCantMin != null && multiple.intCantMax == null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.CodProd == multiple.strCod && a.Pieza.Substring(1).Contains(multiple.strLvl.ToString()) && a.Stock >= multiple.intCantMin).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod != null && multiple.strRack == null && multiple.strPosi == null && multiple.strLvl != null && multiple.intCantMin == null && multiple.intCantMax != null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.CodProd == multiple.strCod && a.Pieza.Substring(1).Contains(multiple.strLvl.ToString()) && a.Stock <= multiple.intCantMax).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod != null && multiple.strRack == null && multiple.strPosi == null && multiple.strLvl == null && multiple.intCantMin != null && multiple.intCantMax != null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.CodProd == multiple.strCod && a.Stock >= multiple.intCantMin && a.Stock <= multiple.intCantMax).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod == null && multiple.strRack != null && multiple.strPosi != null && multiple.strLvl != null && multiple.intCantMin == null && multiple.intCantMax == null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.Partida == multiple.strRack && a.Pieza == String.Concat(multiple.strPosi, multiple.strLvl) && a.Stock > 0).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod == null && multiple.strRack != null && multiple.strPosi != null && multiple.strLvl == null && multiple.intCantMin != null && multiple.intCantMax == null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.Partida == multiple.strRack && a.Pieza.Contains(multiple.strPosi) && a.Stock >= multiple.intCantMin).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod == null && multiple.strRack != null && multiple.strPosi != null && multiple.strLvl == null && multiple.intCantMin == null && multiple.intCantMax != null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.Partida == multiple.strRack && a.Pieza.Contains(multiple.strPosi) && a.Stock <= multiple.intCantMax).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod == null && multiple.strRack != null && multiple.strPosi == null && multiple.strLvl != null && multiple.intCantMin != null && multiple.intCantMax == null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.Partida == multiple.strRack && a.Pieza.Substring(1).Contains(multiple.strLvl.ToString()) && a.Stock >= multiple.intCantMin).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod == null && multiple.strRack != null && multiple.strPosi == null && multiple.strLvl != null && multiple.intCantMin == null && multiple.intCantMax != null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.Partida == multiple.strRack && a.Pieza.Substring(1).Contains(multiple.strLvl.ToString()) && a.Stock <= multiple.intCantMax).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod == null && multiple.strRack != null && multiple.strPosi == null && multiple.strLvl == null && multiple.intCantMin != null && multiple.intCantMax != null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.Partida == multiple.strRack && a.Stock >= multiple.intCantMin && a.Stock <= multiple.intCantMax).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod == null && multiple.strRack == null && multiple.strPosi != null && multiple.strLvl != null && multiple.intCantMin != null && multiple.intCantMax == null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.Pieza == String.Concat(multiple.strPosi, multiple.strLvl) && a.Stock >= multiple.intCantMin).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod == null && multiple.strRack == null && multiple.strPosi != null && multiple.strLvl != null && multiple.intCantMin == null && multiple.intCantMax != null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.Pieza == String.Concat(multiple.strPosi, multiple.strLvl) && a.Stock <= multiple.intCantMax).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod == null && multiple.strRack == null && multiple.strPosi == null && multiple.strLvl != null && multiple.intCantMin != null && multiple.intCantMax != null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.Pieza.Substring(1).Contains(multiple.strLvl.ToString()) && a.Stock >= multiple.intCantMin && a.Stock <= multiple.intCantMax).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod != null && multiple.strRack != null && multiple.strPosi != null && multiple.strLvl != null && multiple.intCantMin == null && multiple.intCantMax == null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.CodProd == multiple.strCod && a.Partida == multiple.strRack && a.Pieza == String.Concat(multiple.strPosi, multiple.strLvl) && a.Stock > 0).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod != null && multiple.strRack != null && multiple.strPosi != null && multiple.strLvl == null && multiple.intCantMin != null && multiple.intCantMax == null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.CodProd == multiple.strCod && a.Partida == multiple.strRack && a.Pieza.Contains(multiple.strPosi) && a.Stock >= multiple.intCantMin).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod != null && multiple.strRack != null && multiple.strPosi != null && multiple.strLvl == null && multiple.intCantMin == null && multiple.intCantMax != null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.CodProd == multiple.strCod && a.Partida == multiple.strRack && a.Pieza.Contains(multiple.strPosi) && a.Stock <= multiple.intCantMax).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod != null && multiple.strRack != null && multiple.strPosi == null && multiple.strLvl != null && multiple.intCantMin != null && multiple.intCantMax == null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.CodProd == multiple.strCod && a.Partida == multiple.strRack && a.Pieza.Substring(1).Contains(multiple.strLvl.ToString()) && a.Stock >= multiple.intCantMin).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod != null && multiple.strRack != null && multiple.strPosi == null && multiple.strLvl != null && multiple.intCantMin == null && multiple.intCantMax != null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.CodProd == multiple.strCod && a.Partida == multiple.strRack && a.Pieza.Substring(1).Contains(multiple.strLvl.ToString()) && a.Stock <= multiple.intCantMax).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod != null && multiple.strRack != null && multiple.strPosi == null && multiple.strLvl == null && multiple.intCantMin != null && multiple.intCantMax != null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.CodProd == multiple.strCod && a.Partida == multiple.strRack && a.Stock >= multiple.intCantMin && a.Stock <= multiple.intCantMax).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod != null && multiple.strRack == null && multiple.strPosi != null && multiple.strLvl != null && multiple.intCantMin != null && multiple.intCantMax == null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.CodProd == multiple.strCod && a.Pieza == String.Concat(multiple.strPosi, multiple.strLvl) && a.Stock >= multiple.intCantMin).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod != null && multiple.strRack == null && multiple.strPosi != null && multiple.strLvl != null && multiple.intCantMin == null && multiple.intCantMax != null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.CodProd == multiple.strCod && a.Pieza == String.Concat(multiple.strPosi, multiple.strLvl) && a.Stock <= multiple.intCantMax).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod != null && multiple.strRack == null && multiple.strPosi != null && multiple.strLvl == null && multiple.intCantMin != null && multiple.intCantMax != null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.CodProd == multiple.strCod && a.Pieza.Contains(multiple.strPosi) && a.Stock >= multiple.intCantMin && a.Stock <= multiple.intCantMax).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod == null && multiple.strRack != null && multiple.strPosi != null && multiple.strLvl != null && multiple.intCantMin != null && multiple.intCantMax == null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.Partida == multiple.strRack && a.Pieza == String.Concat(multiple.strPosi, multiple.strLvl) && a.Stock >= multiple.intCantMin).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod == null && multiple.strRack != null && multiple.strPosi != null && multiple.strLvl != null && multiple.intCantMin == null && multiple.intCantMax != null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.Partida == multiple.strRack && a.Pieza == String.Concat(multiple.strPosi, multiple.strLvl) && a.Stock <= multiple.intCantMax).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod == null && multiple.strRack != null && multiple.strPosi != null && multiple.strLvl == null && multiple.intCantMin != null && multiple.intCantMax != null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.Partida == multiple.strRack && a.Pieza.Contains(multiple.strPosi) && a.Stock >= multiple.intCantMin && a.Stock <= multiple.intCantMax).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod == null && multiple.strRack == null && multiple.strPosi != null && multiple.strLvl != null && multiple.intCantMin != null && multiple.intCantMax != null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.Pieza == String.Concat(multiple.strPosi, multiple.strLvl) && a.Stock >= multiple.intCantMin && a.Stock <= multiple.intCantMax).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod != null && multiple.strRack != null && multiple.strPosi != null && multiple.strLvl != null && multiple.intCantMin != null && multiple.intCantMax == null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.CodProd == multiple.strCod && a.Partida == multiple.strRack && a.Pieza == String.Concat(multiple.strPosi, multiple.strLvl) && a.Stock >= multiple.intCantMin).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod != null && multiple.strRack != null && multiple.strPosi != null && multiple.strLvl != null && multiple.intCantMin == null && multiple.intCantMax != null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.CodProd == multiple.strCod && a.Partida == multiple.strRack && a.Pieza == String.Concat(multiple.strPosi, multiple.strLvl) && a.Stock <= multiple.intCantMax).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod != null && multiple.strRack == null && multiple.strPosi != null && multiple.strLvl != null && multiple.intCantMin != null && multiple.intCantMax != null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.CodProd == multiple.strCod && a.Pieza == String.Concat(multiple.strPosi, multiple.strLvl) && a.Stock >= multiple.intCantMin && a.Stock <= multiple.intCantMax).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod != null && multiple.strRack != null && multiple.strPosi == null && multiple.strLvl != null && multiple.intCantMin != null && multiple.intCantMax != null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.CodProd == multiple.strCod && a.Partida == multiple.strRack && a.Pieza.Substring(1).Contains(multiple.strLvl.ToString()) && a.Stock >= multiple.intCantMin && a.Stock <= multiple.intCantMax).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod != null && multiple.strRack != null && multiple.strPosi != null && multiple.strLvl == null && multiple.intCantMin != null && multiple.intCantMax != null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.CodProd == multiple.strCod && a.Partida == multiple.strRack && a.Pieza.Contains(multiple.strPosi) && a.Stock >= multiple.intCantMin && a.Stock <= multiple.intCantMax).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod != null && multiple.strRack != null && multiple.strPosi != null && multiple.strLvl != null && multiple.intCantMin == null && multiple.intCantMax != null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.CodProd == multiple.strCod && a.Partida == multiple.strRack && a.Pieza == String.Concat(multiple.strPosi, multiple.strLvl) && a.Stock <= multiple.intCantMax).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod == null && multiple.strRack != null && multiple.strPosi != null && multiple.strLvl != null && multiple.intCantMin != null && multiple.intCantMax != null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.Partida == multiple.strRack && a.Pieza == String.Concat(multiple.strPosi, multiple.strLvl) && a.Stock >= multiple.intCantMin && a.Stock <= multiple.intCantMax).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
else if (multiple.strCod != null && multiple.strRack != null && multiple.strPosi != null && multiple.strLvl != null && multiple.intCantMin != null && multiple.intCantMax != null)
{
using (ELECTROPEntities db = new ELECTROPEntities())
{
try
{
var x = getData(db)
.Where(a => a.CodProd == multiple.strCod && a.Partida == multiple.strRack && a.Pieza == String.Concat(multiple.strPosi, multiple.strLvl) && a.Stock >= multiple.intCantMin && a.Stock <= multiple.intCantMax).ToList();
return PartialView("multi", x);
}
catch (Exception ex)
{
return Json(ex.ToString(), JsonRequestBehavior.AllowGet);
}
}
}
return Json(multiple, JsonRequestBehavior.AllowGet);
}
</code></pre>
<p>I pasted the version with linq instead of query string</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T17:22:29.980",
"Id": "438629",
"Score": "0",
"body": "I have rolled back your last edit. Once answers are available, you should be careful to edit a question in order not to invalidate answers. It might be better you either write a self-answer or ask a follow-up question. You could also decide whether to accept any of the answers here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T17:46:55.130",
"Id": "438636",
"Score": "1",
"body": "@dfhwze Perfect mate, thanks"
}
] |
[
{
"body": "<p>So now basically rewriting the whole answer. As OP asks:</p>\n\n<blockquote>\n <p>Basically I'm looking for a way to [...] avoid making a lot of if\n statements and parameter combination manually</p>\n</blockquote>\n\n<p>This answer provides an alternate solution to tackle exactly that. Precisely, it is easier to maintain and can be adapted to other models as well.</p>\n\n<p>In the whole code I only found a single special case: If <code>strPosi</code> and <code>strLvl</code> are set, the <code>.Where</code> differs. In all other cases you execute the exact same code.</p>\n\n<p>I divided the whole method in 3 methods. Starting with <code>GetParamsToExecute</code>. This method uses <code>GetProperties</code> and <code>GetValue</code> to dynamically generate a list of all parameters not null. Thus, it can be <strong>reused</strong> for other models as well, but has a <strong>costly</strong> operation with <code>GetProperties</code>.</p>\n\n<pre><code>private List<string> GetParamsToExecute(object model)\n{\n List<string> paramsToExecute = new List<string>();\n foreach (var p in model.GetType().GetProperties())\n {\n if (p.GetValue(model, null) != null)\n {\n paramsToExecute.Add(p.Name);\n }\n }\n return paramsToExecute;\n}\n</code></pre>\n\n<p>Second, I created a method <code>ExecuteParams</code>, this method is <strong>model specific</strong> and executes all specific <code>.Where</code> clauses for the <code>MultipleParameterSearch</code> model. It covers the special case of <code>strPosi</code> and <code>strLvl</code> in an intial if-statement and covers the rest of the code to execute in a switch case.</p>\n\n<pre><code>private IQueryable<Model> ExecuteParams(IQueryable<Model> source, List<string> paramsToExecute, MultipleParameterSearch multiple)\n{\n if (paramsToExecute.Contains(\"strPosi\") && paramsToExecute.Contains(\"strLvl\"))\n {\n source = source.Where(a => a.Pieza == String.Concat(multiple.strPosi, multiple.strLvl));\n paramsToExecute.Remove(\"strPosi\");\n paramsToExecute.Remove(\"strLvl\");\n }\n\n foreach (var p in paramsToExecute)\n {\n switch (p)\n {\n case \"strCod\":\n source = source.Where(a => a.CodProd == multiple.strCod && a.Stock > 0);\n break;\n case \"strRack\":\n source = source.Where(a => a.Partida == multiple.strRack && a.Stock > 0);\n break;\n case \"strPosi\":\n source = source.Where(a => a.Pieza.Contains(multiple.strPosi) && a.Stock > 0);\n break;\n case \"strLvl\":\n source = source.Where(a => a.Pieza.Substring(1).Contains(multiple.strLvl.ToString()) && a.Stock > 0);\n break;\n case \"intCantMin\":\n source = source.Where(a => a.Stock >= multiple.intCantMin);\n break;\n case \"intCantMax\":\n source = source.Where(a => a.Stock <= multiple.intCantMax);\n break;\n default:\n throw new ArgumentException(string.Format(\n CultureInfo.InvariantCulture,\n \"The parameter {0} was not found.\",\n p));\n }\n }\n\n return source;\n}\n</code></pre>\n\n<p>And lastly the actual <code>MultipleParameterSearch</code>: (EDIT: Added the proper check and return if no parameter is set)</p>\n\n<pre><code>public ActionResult MultipleParameterSearch(MultipleParameterSearch multiple)\n{\n var paramsToExecute = GetParamsToExecute(multiple);\n if(!paramsToExecute.Any()) {\n return Json(multiple, JsonRequestBehavior.AllowGet);\n }\n\n using (ELECTROPEntities db = new ELECTROPEntities())\n {\n try\n {\n var x = ExecuteParams(getData(db), paramsToExecute, multiple).ToList();\n return PartialView(\"multi\", x);\n }\n catch (Exception ex)\n {\n return Json(ex.ToString(), JsonRequestBehavior.AllowGet);\n }\n }\n}\n</code></pre>\n\n<p>It works because whether you execute <code>.Where(ConditionA && ConditionB)</code> or <code>.Where(ConditionA).Where(ConditionB)</code> makes no difference. As my version adds an iterative approach with the the foreach-loop as well as the performance-killer in <code>GetParamsToExecute</code>, it should be less performant than the original. Thus, I'm pretty sure that this is not the optimal solution, but it is easier to maintain then the if cluster before and can be adapted to other models by adding appropriate <code>ExecuteParams</code> methods for these models.</p>\n\n<p>If it is adapted for other models it would be better to have a general <code>ExecuteParams</code> which is called by every action and then chooses the fitting <code>ExecuteParamsForModelX</code> accordingly. This makes your actions uniform and dislocates the execution parts completely.</p>\n\n<pre><code>Action1(ModelType1) {\n ExecuteParams(model);\n}\n\nAction2(ModelType2) {\n ExecuteParams(model2);\n}\n\nExecuteParams(object model) {\n if(model.GetType().Equals(typeof(ModelType1)) \n {\n ExecuteParamsForModelType1(model);\n }\n // or switch-case or whatever ...\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T15:38:51.450",
"Id": "225656",
"ParentId": "225654",
"Score": "3"
}
},
{
"body": "<h2>DRY Principle</h2>\n\n<p>You should write DRY (don't repeat yourself) code. Each of your if-blocks contains the following pattern:</p>\n\n<blockquote>\n<pre><code>using (ELECTROPEntities db = new ELECTROPEntities())\n{\n try\n {\n var x = getData(db)\n .Where(predicate).ToList();\n return PartialView(\"multi\", x);\n }\n catch (Exception ex)\n {\n return Json(ex.ToString(), JsonRequestBehavior.AllowGet);\n }\n}\n</code></pre>\n</blockquote>\n\n<p>where <code>predicate</code> is the only part that is specific to the if-block.</p>\n\n<p>One way to use this pattern is to ask the <code>MultipleParameterSearch</code> parameter to return the <code>predicate</code> for us.</p>\n\n<pre><code>MultipleParameterSearch multiple; // given\nvar predicate = multiple.GetFilter();\n</code></pre>\n\n<p>The filter should return a specific predicate given its state.</p>\n\n<pre><code>public Func<ELECTROPEntity, bool> GetFilter()\n{\n if (strCod != null && strRack == null \n && strPosi == null && strLvl == null \n && intCantMin == null && intCantMax == null)\n {\n return (entity) => entity => entity.CodProd == strCod && entity.Stock > 0;\n }\n // .. and so on\n}\n</code></pre>\n\n<p><code>MultipleParameterSearch</code> can then be implemented with just a couple of lines:</p>\n\n<pre><code>public ActionResult MultipleParameterSearch(MultipleParameterSearch multiple)\n{\n using (var db = new ELECTROPEntities())\n {\n try\n {\n return PartialView(\"multi\", getData(db).Where(multiple.GetFilter()).ToList());\n }\n catch (Exception ex)\n {\n return Json(ex.ToString(), JsonRequestBehavior.AllowGet);\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T11:33:58.413",
"Id": "225715",
"ParentId": "225654",
"Score": "2"
}
},
{
"body": "<p><strong>SOLVED</strong></p>\n\n<p>this is the way I ended up doing it, don't know if it's the best way, but it works</p>\n\n<p>I took this idea from an answer that was posted here but now it's not anymore, \nand Honestly I don't remember who suggested it, I took the foreach loop and adapted to my case, for my point of view the foreach loop is the fasted way, and also I can turn it into a method and dive the code to be reusable as suggested by</p>\n\n<blockquote>\n <p>FeRaac and dfhwze</p>\n</blockquote>\n\n<p>In the case approached by FeRaac about the exception or the difference between <code>strPosi</code> and <code>strLvl</code> with the rest of the params I changed the way I made the linq so to avoid using <code>LIKE</code> in the where clause.</p>\n\n<pre><code>public ActionResult MultipleParameterSearch(MultipleParameterSearch multiple)\n {\n //First I declare an empty string in which I'll store the different params\n string whereClause = string.Empty;\n //Here I create an empty string list where I'll add not null params values\n List<string> values = new List<string>();\n //Like my data base tables don't have the same names as the params I declare and initialise an string dictionary so I can select the data base table name according the param\n Dictionary<string, string> properties = new Dictionary<string, string>()\n {\n {\"strCod\", \"CodProd\" },\n {\"strRack\", \"Rack\" },\n {\"strPosi\", \"Position\"},\n {\"strLvl\", \"Level\" },\n {\"intCantMin\", \"Stock\" },\n {\"intCantMax\", \"Stock\" }\n };\n //get model properties\n var pro = multiple.GetType().GetProperties();\n //keep count of the iterated params\n int count = 0;\n foreach (var p in pro)\n {\n if (p.GetValue(multiple, null) != null)\n {\n //if the param is not null I create a string in which I add the table name and the param value\n string whereForThisP = string.Format(CultureInfo.InvariantCulture, \"{0} \" + (p.Name == \"intCantMin\" ? \">=\" : (p.Name == \"intCantMax\" ? \"<=\" : \"==\")) + \" @\"+count, properties[p.Name]);\n //I add the not null param to the values list\n values.Add(p.GetValue(multiple, null).ToString());\n if (whereClause.Equals(string.Empty))\n {\n //if whereClause is still ampty just add the string\n whereClause = whereForThisP;\n }\n else\n {\n //if not I append a \"AND\" to the clause\n whereClause += \" and \" + whereForThisP;\n }\n count++;\n }\n }\n //if the clause does not contains \"Stock\" by default I add it greater than 0\n if (!whereClause.Contains(\"Stock\"))\n whereClause += \" and Stock > 0\";\n\n try\n {\n //Here just add to the where clause the predicate string , and the values list converted to array\n var x = getData()\n .Where(whereClause, values.ToArray()).ToList();\n return PartialView(\"multi\", x);\n }\n catch (Exception ex)\n {\n return Json(ex.ToString(), JsonRequestBehavior.AllowGet);\n }\n }\n</code></pre>\n\n<p>I documented the code the best I could but in brief I just iterate over the model porperties, evaluate if it's not null, and if that's the case I append to a string variable, the table name, and also append the param value to a list where I store the values to later parse it to an array.</p>\n\n<p>After that sent the string where clause and values array as params to the linq where consult.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T17:52:59.577",
"Id": "438640",
"Score": "1",
"body": "You need to summarise the changes you've made. Otherwise your answer is off-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T17:55:43.677",
"Id": "438642",
"Score": "1",
"body": "@t3chb0t Also, this answer deserves a full review as well :p"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T19:50:52.943",
"Id": "438663",
"Score": "0",
"body": "@t3chb0t I added documentation don't know if it's ok this way"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T19:55:03.500",
"Id": "438665",
"Score": "0",
"body": "What's missing is some information about how and/or why you wrote this code. For instance you can write which suggestions you've implemented or not etc. Maybe you've made some other changes on your own or found anything else that would be interesting to know?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T01:21:59.283",
"Id": "438696",
"Score": "0",
"body": "@t3chb0t changed it, and sorry again I'm new here, didn't know that one's must be very specific, and I'm not use to it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T04:46:15.963",
"Id": "438700",
"Score": "0",
"body": "It looks good now! Thanks ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T09:34:08.600",
"Id": "438931",
"Score": "0",
"body": "Ah, that was my initial approach there. I changed it after I saw your real code though. Glad it helped you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T16:54:16.720",
"Id": "439002",
"Score": "0",
"body": "@FeRaaC it was you, well mate, thanks very much it did help"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T17:48:23.303",
"Id": "225839",
"ParentId": "225654",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T15:05:05.123",
"Id": "225654",
"Score": "5",
"Tags": [
"c#",
"object-oriented",
"entity-framework"
],
"Title": "Collect reporting data for each possible combination of filter properties"
}
|
225654
|
<p>I have some question because in my project I have 4 models, and one of models is parent for other 3 and they are connected to parent by foreign key. Then I have view which is used for automatically fill form of those models and save them in database, this is post function in my view:</p>
<pre><code> def post(self, request, *args, **kwargs):
self.object = None
form_2 = self.form_class_search(self.request.POST)
if form_2.is_valid():
keyword = form_2.cleaned_data['keyword']
books = self.search_for_books(keyword)
if books:
for book in books:
title = self.add_title(book)
published_date = self.add_published_date(book)
pages = self.add_pages(book)
language = self.add_language(book)
form = self.form_class_book(
{'title': title,
'published_date': published_date,
'pages': pages,
'language': language}
)
if form.is_valid() and form.cleaned_data["title"] not in Book.objects.values_list('title', flat=True):
self.object = form.save()
small_thumbnail = self.add_small_thumbnail(book)
thumbnail = self.add_thumbnail(book)
form_thumbnail = self.form_class_thumbnail(
{'small_thumbnail': small_thumbnail,
'thumbnail': thumbnail,
'book': self.object.id}
)
if form_thumbnail.is_valid():
form_thumbnail.save()
if book['volumeInfo'].get('authors'):
for author in book['volumeInfo']['authors']:
author = self.add_author(author)
form_author = self.form_class_author(
{'author': author,
'book': self.object.id}
)
if form_author.is_valid():
form_author.save()
if book['volumeInfo'].get('industryIdentifiers'):
for identifier in book['volumeInfo']['industryIdentifiers']:
identifier_type = self.add_identifier_type(identifier)
identifier = self.add_identifier(identifier)
form_industryidentifier = self.form_class_identifier(
{'type': identifier_type,
'identifier': identifier,
'book': self.object.id}
)
if form_industryidentifier.is_valid():
form_industryidentifier.save()
</code></pre>
<p>Code works exactly how I want and for me is also transparent and easy to understand but its quite long and I'm courious if my current code is good as it is now or maybe there is good way to make it shorter.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T16:50:38.917",
"Id": "225661",
"Score": "2",
"Tags": [
"python",
"django"
],
"Title": "Automatically filled multiple forms in one view"
}
|
225661
|
<p>I currently have a class that I want to serialize/deserialize messages sent to this socket.</p>
<p>My plan was to use <code>Task.WhenAny()</code> to monitor 2 tasks (Either watch something that needs to be written, or read from the stream). If I have a message waiting to be sent, it would write it to the stream, otherwise it would attempt to read from the stream. My result yielded some pretty garbage code (Having to create other methods for read/write), and using a private class for return value, as I can't use <code>Task.WhenAny</code> with one value returning an int, and another returning <code>IPayload</code>.</p>
<p>I'm worried about edge cases, what happens if (albeit unlikely), a read happens right when <code>IPayload</code> happens. For example: if I partially read, and the queue gets a payload.</p>
<p>Trying to find the best approach to do this:</p>
<pre><code>public class GameSocket
{
private readonly string _host;
private readonly int _port;
private readonly ISerializer _serializer;
private readonly ILogger _logger;
private readonly TcpClient _client = new TcpClient();
private readonly AsyncProducerConsumerQueue<IPayload> _outgoingQueue = new AsyncProducerConsumerQueue<IPayload>();
private enum OperationType : byte
{
Read = 0,
Write = 1
}
private class ClientOperation
{
public int ReadLength;
public IPayload ToWrite;
public OperationType Type;
}
public GameSocket([NotNull] string host, int port, [NotNull] ISerializer serializer, ILogger logger = null)
{
_host = host ?? throw new ArgumentNullException(nameof(host));
if (port < 0 || port > 65535) throw new ArgumentOutOfRangeException(nameof(port), "Invalid port provided.");
_port = port;
_serializer = serializer ?? throw new ArgumentNullException(nameof(serializer));
_logger = logger ?? new DebugLogger("GameSocket");
_client = new TcpClient();
}
public GameSocket(IPEndPoint endpoint, ISerializer serializer, ILogger logger = null) : this(endpoint.Address.ToString(), endpoint.Port, serializer, logger)
{
}
public async Task Run(CancellationToken ct)
{
try
{
await _client.ConnectAsync(_host, _port);
using (var stream = _client.GetStream())
{
while (true)
{
var buffer = new byte[_serializer.HeaderSize];
var res = await Task.WhenAny(ReadAsync(stream, buffer, ct), GetPayload(ct));
switch (res.Result.Type)
{
case OperationType.Write:
var sendBytes = _serializer.Serialize(res.Result.ToWrite);
if (_logger.IsEnabled(LogLevel.Trace))
{
_logger.LogTrace($"Writing bytes: {sendBytes}");
}
await stream.WriteAsync(sendBytes, 0, sendBytes.Length, ct);
break;
case OperationType.Read:
var readLength = res.Result.ReadLength;
if (readLength == 0)
{
_logger.LogWarning("Connection Closed. Read Length=0");
return;
}
var deserialized = _serializer.Deserialize(buffer);
//Find handlers
//Dispatch method
break;
}
}
}
}
finally
{
_client.Dispose();
}
}
public Task SendMessage(IPayload payload)
{
return _outgoingQueue.EnqueueAsync(payload);
}
private async Task<ClientOperation> ReadAsync(NetworkStream stream, byte[] buffer, CancellationToken ct)
{
var readLength = await stream.ReadAsync(buffer, 0, buffer.Length, ct);
return new ClientOperation
{
ReadLength = readLength,
Type = OperationType.Read
};
}
private async Task<ClientOperation> GetPayload(CancellationToken ct)
{
var item = await _outgoingQueue.DequeueAsync(ct);
return new ClientOperation
{
ToWrite = item,
Type = OperationType.Write
};
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T17:34:57.057",
"Id": "438224",
"Score": "2",
"body": "Have you tested this code, and can you show it in use? I ask, because there is a lot that looks wrong with it, and it is missing the 'find handlers'/'dispatch method' bit. It is important that you know how the code works and that it is working as expected before soliciting a review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T06:37:49.363",
"Id": "438320",
"Score": "1",
"body": "@dfhwze Better?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T09:41:14.477",
"Id": "438354",
"Score": "1",
"body": "Since no consensus has been formed, I'll expand on my previous comment: the use of `WhenAny` means that whichever of the two tasks completes first (ish) will be observed, and the other will be ignored: it will not be cancelled, the task will wait on. For the read, this means losing whatever was read; for `GetPayload`, this means losing whatever is on top of the queue. This isn't an unlikely event (it will occur every 'cycle' in `Run`), and I doubt it would pass even a cursory testing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T18:15:13.597",
"Id": "438428",
"Score": "1",
"body": "If the actions triggered by the completion of one of the two task don't have to be orchestrated, there is no reason to use \"WhenAny\", you can simply create two separate pipelines with two loops one handling the read and the other handing the payload."
}
] |
[
{
"body": "<h2>Race Condition</h2>\n\n<p>You are starting two tasks concurrently, each blocking on an event to occur.</p>\n\n<blockquote>\n<pre><code>var res = await Task.WhenAny(ReadAsync(stream, buffer, ct), GetPayload(ct));\n</code></pre>\n</blockquote>\n\n<p>By calling <code>WhenAny</code>, once one of tasks is completed, you continue without awaiting completion of the other task. Let's say that <code>ReadAsync</code> completes first, this means the following code rus in a task that is fired and forgotten:</p>\n\n<blockquote>\n<pre><code> var item = await _outgoingQueue.DequeueAsync(ct);\n</code></pre>\n</blockquote>\n\n<p>You immediately go to a next loop of awaiting 2 newly created tasks: <code>ReadAsync</code> and <code>GetPayload</code>. However, since the previous <code>GetPayload</code> was not awaited upon, the new call to it will block until that one is finished (they both want to acquire a lock on the mutex of <code>AsyncProducerConsumerQueue</code>). </p>\n\n<p><strong>And here is the race condition</strong>: the old (forgotten) task completes but no-one would care about it. No handler is called on completion, because you only handle the task that completes first of the pair or newly created tasks.</p>\n\n<p>Frankly, I don't know why you would even consider using this pattern. These are two independant tasks that should have their own scope and loop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T09:01:23.257",
"Id": "438470",
"Score": "0",
"body": "I was considering using this pattern, because I thought you could only have one concurrent reader and writer, and wanted a way to nicely read and write without involving locks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T19:11:37.063",
"Id": "225739",
"ParentId": "225663",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "225739",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T17:11:07.537",
"Id": "225663",
"Score": "1",
"Tags": [
"c#",
"async-await",
"serialization",
"tcp",
"task-parallel-library"
],
"Title": "Async Tcpwriter and Reader"
}
|
225663
|
<p>I built this scraper for work that will take a csv list of firewalls from our network management system and scan a given list of HTTPS ports to see if the firewalls are accepting web requests on the management ports. I originally built this in powershell, but decided to rebuild it in python for the learning experience. </p>
<p>I was able to cut down the scan time substantially using multiprocessing, but I'm wondering if I can further optimize my code to get it faster.</p>
<p>Also, I'm very new to python. So if you have any input on better more efficient ways that I could have used to accomplish these steps would be much appreciated.</p>
<pre><code>import urllib.request
import re
import os
import ssl
import multiprocessing
#imports a csv list of firewalls with both private and public IP addresses
f = open(r'\h.csv',"r")
if f.mode =="r":
cont = f.read()
#regex to remove private ip addresses and then put the remaining public ip addresses in a list
c = re.sub(r"(172)\.(1[6-9]|2[0-9]|3[0-1])(\.(2[0-4][0-9]|25[0-5]|[1][0-9][0-9]|[1-9][0-9]|[0-9])){2}|(192)\.(168)(\.(2[0-4][0-9]|25[0-5]|[1][0-9][0-9]|[1-9][0-9]|[0-9])){2}|(10)(\.(2[0-4][0-4]|25[0-5]|[1][0-9][0-9]|[1-9][0-9]|[0-9])){3}","",cont)
d = re.findall(r"[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}",c)
#uses HTTP requests to check if any of the 8 management ports on the addresses in the list are accepting web requests
def httpScan(list):
iplen = len(list)
ports = [443, 4433, 444, 433, 4343, 4444, 4443, 4434]
portlen = len(ports)
for k in range(iplen):
for i in range(portlen):
context = ssl._create_unverified_context()
try:
fp = urllib.request.urlopen("https://" + str(list[k]) + ":" + str(ports[i]), context=context)
mybytes = fp.read()
mystr = mybytes.decode("utf8")
fp.close()
except:
continue
if "SSLVPN" in mystr:
print(list[k] + " SSLVPN" + ": " + str(ports[i]) + " " + str(k) + " " + str(os.getpid()))
elif "auth1.html" in mystr:
print(list[k] + " MGMT" + ": " + str(ports[i]) + " " + str(k))
#splits the list of IP addresses up based on how many CPU there are and adds each segment to a dictionary
cpu = int(multiprocessing.cpu_count())
sliced = int(len(d)/cpu)
mod = int(len(d))%int(cpu)
num = 1
lists = dict()
for i in range(cpu):
if i != (cpu - 1):
lists[i] = d[(num*sliced) - sliced:num*sliced]
num += 1
else:
lists[i] = d[(num*sliced) - sliced:(num*sliced) + mod]
#starts a process for each unique segment created
t = dict()
if __name__ == "__main__":
for i in range(cpu):
t[i] = multiprocessing.Process(target=httpScan, args=(lists[i],))
t[i].start()
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<h2>Reading File</h2>\n\n<p>Here is a tip, while reading, the <code>r</code> is optional</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>f = open(r'\\h.csv',\"r\")\n</code></pre>\n\n<p>can be written as</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>f = open(r'\\h.csv')\n</code></pre>\n\n<p>Your whole reading block can use context managers (blocks using the with keyword).</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>with open(r'\\h.csv', encoding='utf8') as f:\n cont = f.read()\n</code></pre>\n\n<p>If you are dealing with a huge text file, you might do:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>with open(r'\\h.csv', encoding='utf8') as f:\n for ip in f:\n ip = ip.rstrip('\\n')\n .. verify\n</code></pre>\n\n<h2>String</h2>\n\n<p>Using string formatting i.e. <code>.format()</code> can give a better idea of what's going on. It also eliminates the use of <code>str()</code> each time.\nWe can change this</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(list[k] + \" MGMT\" + \": \" + str(ports[i]) + \" \" + str(k))\n</code></pre>\n\n<p>to that</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(\"{} MGMT: {} {}\".format(list[k], ports[i], k))\n</code></pre>\n\n<p>and as from 3.6+, adding an f</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(f\"{list[k]} MGMT: {ports[i]} {k}\")\n</code></pre>\n\n<h2>Loop Iteration</h2>\n\n<p>In many other languages, you need the index while looping to have the element at this index. Python provides a nice and intuitive way to loop over elements</p>\n\n<p>The current implementation:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>ports = [443, 4433, 444, 433, 4343, 4444, 4443, 4434]\nportlen = len(ports)\nfor i in range(portlen):\n print(ports[i])\n</code></pre>\n\n<p>But the pythonic way is:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>ports = [443, 4433, 444, 433, 4343, 4444, 4443, 4434]\nfor port in ports:\n print(port)\n</code></pre>\n\n<p><code>port</code> here gives you the element directly.\nIf ever you still want the index, you do:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for i, port in enumerate(ports):\n</code></pre>\n\n<p>where <code>i</code> is the index.</p>\n\n<h2>Miscellaneous</h2>\n\n<p>Here:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>cpu = int(multiprocessing.cpu_count())\n</code></pre>\n\n<p>No need to cast to int as <code>multiprocessing.cpu_count()</code> already returns an integer. You can verify for int by <code>type(multiprocessing.cpu_count())</code></p>\n\n<p>Normally with <code>.start()</code>, you must include a <code>.join()</code>, as this allows all child processes to terminate before exiting.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for ...:\n ... .start()\n\nfor ...:\n ... .join()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T19:12:57.940",
"Id": "438252",
"Score": "1",
"body": "Thank you very much, this is exactly what I was looking for!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T19:14:14.003",
"Id": "438253",
"Score": "0",
"body": "You are welcomed!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T18:50:07.563",
"Id": "225673",
"ParentId": "225666",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "225673",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T17:18:24.047",
"Id": "225666",
"Score": "2",
"Tags": [
"python",
"performance",
"python-3.x",
"regex",
"https"
],
"Title": "HTTP scraper efficiency with multiprocessing"
}
|
225666
|
<p>I just want to gather some feedback about this container, in my view it solves the problem of common data containers which don't have fast access and fast deletion. I want to admit that I have not benchmark this, as I don't understand how to do it and to compare with other containers. I tested it and it works, although it might not be the cleanest or safest code.</p>
<p><code>map<></code> has O(log(n)) for access and deletion</p>
<p><code>vector<></code> has O(n) for deletion</p>
<p>As you can see, with usual STL containers, you can't have O(1) performance and low memory footprint everywhere.</p>
<p>I heard about object pool some time ago, where instead of deleting objects, you reuse them, but the problem is that you have to resize the <code>vector<></code>. </p>
<p>Then I've read a suggestion on IRC about swapping the tail of the vector with the item I want to delete. The problem is that the index of the last item is changing.</p>
<p>So I wrote this container with an index mapper.</p>
<p>The index is just two <code>vector<int></code>, a forward and a backward map, with a <code>queue<int></code> for available indexes.</p>
<p>The data is a <code>vector<T></code>.</p>
<p>Each time an item is remove or added, the index is adjusted so that you can still access the item by the same index.</p>
<pre><code>template <typename T>
struct managed_pool {
queue<size_t> avail;
vector<T> data;
vector<int> index, back_index; // forward and backward index
size_t add(T&&val) {
// always add to tail since we "swap-pop":
data.push_back(val);
size_t data_index = data.size() - 1;
size_t index_index;
// if there's no available index
if (avail.empty()) {
// add a new index
index.push_back(data_index);
index_index = index.size()-1;
}
else {
// reuse one
index_index = avail.front();
avail.pop();
}
back_index.push_back(index_index);
index[index_index] = data_index;
msgm(val, index_index);
return index_index;
}
void rem(size_t translate_index_delete) {
auto real_index_backup = data.size() - 1; // you want to keep this
auto real_index_delete = index[translate_index_delete]; // you want to delete this
auto translate_index_backup = back_index[real_index_backup];
index[translate_index_delete] = -1; // invalidate
avail.push(translate_index_delete);
data[real_index_delete] = data[real_index_backup]; // here we "swap-pop". We move the .back() of the vector to the index of the item we want to remove. This ensures contiguity of the vector, at a minimal performance cost
data.pop_back(); // remove it
index[translate_index_backup] = real_index_delete; // we adjust the mapping table to make sure the item is still indexed at the same index.
}
T&operator[](size_t & i) {
if(index[1] != -1)
return data[index[i]];
}
};
</code></pre>
<p>I just want to have your opinion if this is good, and if there are better methods than this. Remember that a heap is not what I want. I want the fastest container and keep a low memory footprint, be simple enough, have fast insertion, fast removal, and fast access. I'm not sure <code>queue<></code> is a good choice.</p>
|
[] |
[
{
"body": "<h1>Define exactly what properties you want your container to have</h1>\n\n<p>You say:</p>\n\n<blockquote>\n <p>As you can see, with usual STL containers, you can't have O(1) performance and low memory footprint everywhere.</p>\n</blockquote>\n\n<p>That's not so much a property of STL, but of container structures in general. You only get O(1) performance if you don't have to search and don't have to shuffle memory around, and if you can't shuffle memory around you can't have a low memory footprint. So you have to make some compromises.</p>\n\n<p>You don't mention what you want to optimize for, or what kind of usage patterns you are expecting. It would be good if you could write down (for yourself) what exact properties you want your container to have, and then verify whether your implementation actually has those properties.</p>\n\n<h1>Your metadata uses storage as well</h1>\n\n<p>Your container has a <code>vector<T></code> with the actual data, which is quite efficient. However, there is also metadata. In particular, there is <code>vector<int> index</code>, which you never shrink. So this means that if you have an access pattern where there is a short spike where a lot of data is stored in the container, then after the spike the data itself doesn't use a lot of space, but the vector of indices is now very large. Especially if <code>T</code> is small, then the overhead of the indices and availability queue might be very significant.</p>\n\n<p>Note that you also never shrink <code>index</code>, even if it is possible to do so (whenever tail indices are unused).</p>\n\n<h1>Adding to a <code>vector<></code> is <em>amortized</em> O(1)</h1>\n\n<p>Adding items to a <code>vector<></code> might cause memory allocations and moves, so the time used for an addition is variable, and does not have an upper bound. Whenever the STL has to reallocate memory for a <code>vector<></code>, it basically doubles the size, so with a constant rate of addition, it needs less and less reallocations. The result is that the amortized cost is O(1). However, be aware that this container might not be suitable for a real-time system.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T20:04:21.357",
"Id": "225682",
"ParentId": "225667",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "225682",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T17:22:23.147",
"Id": "225667",
"Score": "1",
"Tags": [
"c++",
"performance",
"memory-management",
"collections"
],
"Title": "Fast insert, fast removal and fast access object pool C++ container"
}
|
225667
|
<p>Below is a delete job to delete 1M+ records daily and takes 13 hours to complete and sometimes more than that. I need to optimize this.</p>
<blockquote>
<p>The table <em>tblcalldatastore</em> is being inserted 24*7 through a stored
procedure and is supposed to have no records older than 24 hours.</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/8ksfQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8ksfQ.png" alt="enter image description here"></a></p>
<p>Execution plan is below.</p>
<p><a href="https://www.brentozar.com/pastetheplan/?id=ryYi2Sv7B" rel="nofollow noreferrer">https://www.brentozar.com/pastetheplan/?id=ryYi2Sv7B</a></p>
<pre><code>BEGIN
SET NOCOUNT ON;
DECLARE @DELETECOUNT int
DECLARE @DELETEATATIME int
DECLARE @CutOffDate datetime
DECLARE @HourRetained smallint
set @HourRetained = 24
begin Try
set @CutOffDate = getutcdate()
select @DELETECOUNT = count(*) from [tblcalldatastore]
where istestcase=0
and datediff(hour,receiveddate,@CutOffDate)>@HourRetained
SET @DELETEATATIME = 20000
WHILE @DELETECOUNT > 0
BEGIN
DELETE TOP(@DELETEATATIME) FROM tblcalldatastore WITH (ROWLOCK) WHERE IsTestCase=0 and datediff(hour,receiveddate,@CutOffDate)>@HourRetained
SET @DELETECOUNT = @DELETECOUNT - @DELETEATATIME
END
end try
BEGIN CATCH
SELECT 'FAILED - ' + ERROR_MESSAGE() AS ErrorMessage
END CATCH
END
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T18:56:18.360",
"Id": "438242",
"Score": "0",
"body": "Are you retaining more data than you delete, and which is the ratio of retained/deleted?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T18:57:14.390",
"Id": "438244",
"Score": "0",
"body": "I am deleting any record older than 24 hours and the job runs daily."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T18:59:09.550",
"Id": "438245",
"Score": "0",
"body": "Have you tested performance of copying data of a single day to a temporary table, truncating the target table, and re-inserting the copied data back to the target table?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T19:02:35.527",
"Id": "438246",
"Score": "0",
"body": "Yes, it's not taking much time to copy or insert, it is taking time to delete and select. One of the column has huge XML string."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T19:03:45.120",
"Id": "438248",
"Score": "0",
"body": "Execution plan - https://www.brentozar.com/pastetheplan/?id=ryYi2Sv7B"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T19:07:09.003",
"Id": "438249",
"Score": "0",
"body": "Here's a similar problem also experiencing 90+ % on non-clustered index. https://dba.stackexchange.com/questions/189607/delete-millions-of-rows-from-a-sql-table"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T19:07:09.927",
"Id": "438250",
"Score": "2",
"body": "Please ensure that your code is posted with the intended formatting. There seems to be a lot of code here that isn't correctly commented out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T19:07:55.487",
"Id": "438251",
"Score": "3",
"body": "Also tell us more about exactly what this code is designed to accomplish, and what the schema looks like. It's hard to help you without that background information. See [ask]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T19:19:07.707",
"Id": "438255",
"Score": "1",
"body": "@200_success - I have updated the code. The code is designed to delete any record older than 24 hours on daily basis."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T05:42:15.250",
"Id": "438290",
"Score": "0",
"body": "I'm hardly an SQL expert, but this doesn't happen to iterate over every entry on each deletion-cycle (20,000 entries) again, does it? As in, if a cycle is complete, start from the beginning. If it does, stop doing that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T05:44:18.070",
"Id": "438292",
"Score": "1",
"body": "I'd suggest creating a smaller database to test the exact workings of your query on and note the inefficiencies. This will allow you to test alternative implementations a lot easier and faster."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T08:14:22.740",
"Id": "438338",
"Score": "0",
"body": "An obvious improvement would be to set `@CutOffDate` to be now - 24 hours, then simply `delete from table where received < @CutOffDate`. Or am I missing some subtlety of T-SQL that's different to standard SQL?"
}
] |
[
{
"body": "<h2>From Comments</h2>\n\n<p><em>Have you tested performance of copying data of a single day to a temporary table, truncating the target table, and re-inserting the copied data back to the target table?</em></p>\n\n<blockquote>\n <p><em>Yes, it's not taking much time to copy or insert, it is taking time to delete and select. One of the column has huge XML string.</em></p>\n</blockquote>\n\n<h2>Proposed Solution</h2>\n\n<p>Since inserting and copying data does not seem to yield a performance penalty, I would suggest to:</p>\n\n<ul>\n<li>copy to data of today to a staging table</li>\n<li>truncate the existing table (much faster than delete, no transaction logs)</li>\n<li>copy staged data back to existing table</li>\n</ul>\n\n<p>Or alternatively, as Dannnno suggests:</p>\n\n<p><em>Potentially faster than copying the data twice would be to copy data to a staging table, truncate the existing table, then rename them both to swap places. This minimizes latches required for DDL, and also only requires a single copy. Snapshot isolation would also help this be as non-invasive as possible for anyone hitting the database.</em></p>\n\n<h3>Links</h3>\n\n<ul>\n<li><a href=\"https://dba.stackexchange.com/questions/189607/delete-millions-of-rows-from-a-sql-table\">Similar problem: non-clustered index bottleneck on delete</a></li>\n<li><a href=\"https://stackoverflow.com/questions/24213299/how-to-delete-large-data-of-table-in-sql-without-log\">Enlists a couple of possible solutions</a></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T19:44:54.630",
"Id": "438259",
"Score": "1",
"body": "The solution seems perfect to me! All I need is to find out best possible time slot when the Production is not in use."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T14:55:34.547",
"Id": "440510",
"Score": "1",
"body": "Potentially faster than copying the data twice would be to copy data to a staging table, truncate the existing table, then rename them both to swap places. This minimizes latches required for DDL, and also only requires a single copy. Snapshot isolation would also help this be as non-invasive as possible for anyone hitting the database."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T14:56:40.723",
"Id": "440511",
"Score": "0",
"body": "@Dannnno Can I include your suggestion in my answer as an alternative option? Or you want to make an answer yourself?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T15:01:55.003",
"Id": "440515",
"Score": "0",
"body": "Feel free to include it yourself; it doesn't add a whole lot of additional information"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T15:03:49.823",
"Id": "440516",
"Score": "1",
"body": "@Dannnno I added it because comments can get removed, thanks for sharing your views."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T19:37:33.750",
"Id": "225677",
"ParentId": "225674",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "225677",
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T18:51:10.837",
"Id": "225674",
"Score": "3",
"Tags": [
"sql",
"datetime",
"time-limit-exceeded",
"sql-server",
"t-sql"
],
"Title": "Daily SQL job to delete records older than 24 hours"
}
|
225674
|
<p>Given <span class="math-container">\$w, h, \alpha\$</span> for a rectangle centered at origin with width <span class="math-container">\$w\$</span>, height <span class="math-container">\$h\$</span> and itself rotated by <span class="math-container">\$\alpha\$</span> around origin clockwise, I wrote a code to find the intersection area.</p>
<blockquote>
<ol>
<li>First I find all 4 corners of original and rotated rectangle, along with lines joining them.</li>
<li>Then I find intersection with axis-parallel lines using <code>getints</code></li>
<li>Then I take all intersections in a clockwise/anti-clockwise order and find area using the co-ordinates of the polygon thus formed.</li>
</ol>
</blockquote>
<p>Source: <a href="https://codeforces.com/problemset/problem/280/A" rel="nofollow noreferrer">https://codeforces.com/problemset/problem/280/A</a>
<a href="https://i.stack.imgur.com/ib1Px.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ib1Px.png" alt="Image"></a></p>
<pre><code>import Data.Ord
import Data.List
import Control.Monad
main :: IO ()
main = do
[w, h, a] <- map read . words <$> getLine
let a' = (min a (180 - a)) * pi / 180
let pts = [(w/2, h/2), (w/2, -h/2), (-w/2,-h/2), (-w/2,h/2)] :: [(Double, Double)]
let pts' = map (rotate a') pts
let lines = zip pts (tail $ cycle pts)
let lines' = zip pts' (tail $ cycle pts')
let ints = concatMap (getints lines') lines
print . area . uniq $ sortBy (comparing theta) ints
uniq [] = []
uniq [x] = [x]
uniq (x:y:xs)
| x == y = uniq (x:xs)
| otherwise = x : uniq (y:xs)
rotate a (x, y) = (x * cos a - y * sin a, x * sin a + y * cos a)
theta (x, y) = atan2 y x
getints xs y = concatMap (\x -> getints' x y) xs
getints' l'@((x1', y1'), (x2', y2')) l@((x, y), (x', y'))
| x == x' =
let y'' = y1' + (x - x1') / (x2' - x1') * (y2' - y1')
in if min y y' <= y'' && y'' <= max y y' then [(x, y'')] else []
| y == y' = map swap $ getints' (swap' l') (swap' l)
where
swap (a, b) = (b, a)
swap' (p1, p2) = (swap p1, swap p2)
area ps =
let
xs = map fst ps
ys = map snd ps
in
0.5 * abs (sum $ zipWith4 (\x y y' x' -> x * y - y' * x') xs (tail $ cycle ys) ys (tail $ cycle xs))
</code></pre>
|
[] |
[
{
"body": "<p>Not a full rewrite, but some pointers:</p>\n\n<p>Typically, a <code>main</code> function's do-block shouldn't be doing a whole lot of work. Additionally, <code>do-block</code>s should try to avoid having lots of <code>let</code> statements, and instead \"outsource\" that work to helper functions. A function with type <code>Double -> Double -> Double -> [((Double, Double), (Double, Double))]</code> could replace most of the <code>do</code> block (the arguments would be <code>w</code>, <code>h</code>, and <code>a</code>).</p>\n\n<p>Every style guide I've seen recommends putting type signatures on every top-level function. Just reading the code to try and figure out what the above mentioned type should be can be surprisingly difficult. Unfortunately, as the author of a program, it's really easy to forget that you know the types because the ideas for the program were your own.</p>\n\n<p>Primes in function names are typically reserved for one of two things. It could mean a <em>strict</em> variant, such as <code>foldl'</code>. \"Strict\" in this case means that the function evaluates its argument, as opposed to Haskell's default of waiting to evaluate things as long as possible. The other option is that it's a minor variation on the function of the same name (many haskellers would say to avoid doing even this, and to reserve primes on function names for strict varaints alone). <code>getints'</code> is not a minor variation on <code>getints</code>, it is a helper function. A more appropriate name might be <code>getintsHelper</code>. On the other hand <code>swap'</code> is a minor variation on <code>swap</code>, and barring a better name like <code>swapBoth</code>, <code>swap'</code> is a reasonable name for that function.</p>\n\n<p>Your function <code>uniq</code> looks like <code>Data.List.nub</code>. <code>nub</code> is a strange name and <code>uniq</code> honestly makes more sense, but it's better to use library functions that readers are familiar with. It's also fine to define synonyms, like <code>uniq = nub</code>, this way readers can see that in the source. Recognizing that <code>uniq</code> is a complete re-implementation is a bit harder. If you think a function you need is simple or common, check the standard library! Haskell's is quite extensive.</p>\n\n<p>With top-level types added and no other changes, this would be a very strong starting point. I'd label that as good work!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T08:20:49.813",
"Id": "225705",
"ParentId": "225684",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "225705",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T20:15:52.693",
"Id": "225684",
"Score": "2",
"Tags": [
"haskell",
"computational-geometry",
"coordinate-system"
],
"Title": "Find intersection of rectangle with itself rotated"
}
|
225684
|
<p>I'm working on a library that, in essence, splits a string at whitespace, with extra rules:</p>
<ul>
<li>Consecutive whitespace is collapsed, and trimmed at the start and end.</li>
<li>Whitespace wrapped in quotes is not collapsed or split.</li>
<li>Backslash escaping can be used to include a single quote or whitespace character (or any other character after it) as-is, <em>including</em> inside of a pair of quotes.</li>
</ul>
<p>The source code of this project is <a href="https://github.com/emctague/comma/tree/master/src" rel="nofollow noreferrer">on GitHub</a> - though I will outline the parts I am most concerned with here.</p>
<p>The main component users use is the <code>Command</code> struct and its <code>from_str</code> function, which:</p>
<ol>
<li>Prefixes a single space in front of the string, such as to force the <code>WhitespaceBlock</code> to be the first-used "syntax block" (explained later), and ensure at least one empty "token" (split string segment) is present for characters to be placed in.</li>
</ol>
<pre><code> let mut input = String::from(" ");
input.push_str(s);
</code></pre>
<ol start="2">
<li>Iterates over each character and attempts to parse it, providing a list of available "syntax blocks" that might be useful for this character.</li>
</ol>
<pre><code> let mut data = ParserData::new(&input);
while data.not_empty() {
handle_or_push(&mut data, &vec![ &EscapeBlock{}, &QuoteBlock{}, &WhitespaceBlock{} ]);
}
let mut tokens = data.get_result().clone();
</code></pre>
<ol start="3">
<li>Deletes the last token if it is entirely empty (which it will be if either no valid characters were provided, OR if the input string ends with whitespace.)</li>
</ol>
<pre><code> // Prevents whitespace at the end of the command from creating an empty garbage argument.
if tokens.last().unwrap().is_empty() {
tokens.pop();
}
</code></pre>
<ol start="4">
<li>Produces an instance of <code>Command</code> and returns it if it is valid.</li>
</ol>
<p>The concept of a <code>SyntaxBlock</code> is any sort of rule that might come into effect while reading characters from a string. A <code>SyntaxBlock</code>'s <code>consume</code> method checks if the next input character is applicable, and if so, "eat"s (removes) it and continues to "eat" further applicable characters. A <code>consume</code> method can use the <code>handle_or_push</code> method nested within it to allow for nested syntax rules. Because this method is responsible for both <em>checking if it is applicable</em> and then proceeding to consume characters, it will return <code>true</code> if it <em>has</em> consumed characters, and <em>false</em> otherwise (allowing <code>handle_or_push</code> to keep checking other syntax rules before giving up and copying a character verbatim.)</p>
<p>For example, here is <code>QuoteBlock</code>'s behavior:</p>
<pre><code>pub struct QuoteBlock;
impl SyntaxBlock for QuoteBlock {
fn consume(&self, input: &mut ParserData) -> bool {
// If we see a quote, aka the start of a QuoteBlock...
if input.peek().unwrap() == '"' {
// We eat up that quote
input.eat().unwrap();
// We eat up the quoted area's contents and try to handle them.
// The `EscapeBlock` is the only one applicable inside of quotes
// and everything else should just be eaten and pushed.
while input.not_empty() && input.peek().unwrap() != '"' {
handle_or_push(input, &vec![ &EscapeBlock{} ]);
}
// We eat the final quote character - unwrap_or_default ensures
// this doesn't fail if we've actually reached the end of input
// instead of a closing quote.
input.eat().unwrap_or_default();
// Return true because we ate stuff and the next character should
// be interpreted from the start of the ruleset again
true
} else {
// Return false because we didn't see a quote block
false
}
}
}
</code></pre>
<p><code>handle_or_push</code> takes in a list of applicable <code>SyntaxBlock</code>s and checks if the next character applies to any of them, in order. If not, it just <code>eat</code>s the character and pushes it to the output instead.</p>
<pre><code>/// `handle_blocks` iterates over a set of SyntaxBlock objects, attempting to consume data from each
/// one in the given order. If any match, it will stop iterating and return true. If no matches are
/// found, it returns false and does not eat any input.
///
/// This behavior is used to check if any special syntax blocks can be used at the moment.
pub fn handle_blocks(input: &mut ParserData, types: &Vec<&dyn SyntaxBlock>) -> bool {
if input.not_empty() {
for t in types {
if t.consume(input) { return true; }
}
}
false
}
/// `handle_or_push` tests if the given SyntaxBlocks are able to consume available input, in order,
/// stopping when a block successfully eats one or more characters. If no blocks eat characters,
/// `handle_or_push` will instead eat the first available character and push it to the output.
///
/// This behavior is used to handle any nested syntax blocks where plaintext should be pushed.
pub fn handle_or_push(input: &mut ParserData, types: &Vec<&dyn SyntaxBlock>) {
if !handle_blocks(input, types) {
input.eat_and_push().unwrap();
}
}
</code></pre>
<p><code>ParserData</code> stores the input and output, and looks like this:</p>
<pre><code>pub struct ParserData {
input: String,
output: Vec<String>,
offset: usize
}
impl ParserData {
pub fn new(input: &String) -> ParserData {
ParserData { input: input.clone(), output: Vec::new(), offset: 0 }
}
pub fn eat(&mut self) -> Result<char, OutOfInputError> {
let result = self.peek()?;
self.offset += 1;
Ok(result)
}
pub fn eat_and_push(&mut self) -> Result<(), OutOfInputError> {
let result = self.eat();
self.push(result?);
Ok(())
}
pub fn peek(&self) -> Result<char, OutOfInputError> {
self.input.chars().nth(self.offset).ok_or(OutOfInputError)
}
pub fn not_empty(&self) -> bool {
self.offset < self.input.len()
}
pub fn new_token(&mut self) {
self.output.push(String::new());
}
pub fn push(&mut self, c: char) {
self.output.last_mut().unwrap().push(c);
}
pub fn get_result(&self) -> &Vec<String> {
&self.output
}
}
</code></pre>
<p>My main concern in this whole thing is the entry-point and how it has to mess with the input in order for it to be valid, before the actual parsing system takes over. I'm also concerned with the mutable input-output structure I pass around, though I can't think of a better way to do that.</p>
<p>Would you consider this "good code" in rust? I'm new to the language and honestly, some of the things I had to do to make it work for me seem a bit messy. I'm used to separately working with functional and OOP languages but I'm not sure about the way rust is <em>meant</em> to be used, so to speak.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T20:32:03.493",
"Id": "438275",
"Score": "0",
"body": "Whean creating a custom lexer/parser, I strongly advise writing a bunch of unit tests to test each block against all kinds of input. This facilitates writing the parser, but also us reviewing your code :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T20:33:32.873",
"Id": "438276",
"Score": "0",
"body": "@dfhwze Good idea. I excluded quite a few tests from this source, though those tests all provide input to the main component rather than individually testing certain blocks. I should add some block-specific tests."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T20:35:23.813",
"Id": "438277",
"Score": "0",
"body": "And don't be shy to include unit tests in the question :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T20:37:12.943",
"Id": "438278",
"Score": "0",
"body": "@dfhwze Just wanted to avoid jamming a whole bunch of code into the question. I'm not really a big fan of unit testing (I only code for fun for now and most of my stuff is way too simple to warrant it). I'll be sure to include them in further Q's!"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T20:25:06.687",
"Id": "225685",
"Score": "2",
"Tags": [
"strings",
"parsing",
"api",
"rust"
],
"Title": "Command String Parser"
}
|
225685
|
<p>I don't like the way my code is written, but at the moment, I don't see, how I should do it better.</p>
<p>I have a class (let's say MyInvoiceType), which needs to save data to preexisting database. The database is now mapped with SqlAlchemy (initially was just created via SQL interface).</p>
<p>I would have certain Table classes mapped via reflection and for one I need to specify PKs myself, therefore (as I understand) I had to create custom class:</p>
<pre><code>from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine,Table
Base=automap_base()
class Batches(Base):
__tablename__="batches"
__table__ = Table(__tablename__, Base.metadata, autoload=True, autoload_with=engine)
__mapper_args__ = {'primary_key': [__table__.c.composite_pk1,__table__.c.composite_pk2]}
sql_conn='my://db@connection'
engine=create_engine(sql_conn)
Base.prepare(engine, reflect=True)
Clients=Base.classes.clients
Invoices=Base.classes.invoices
InvoiceLines=Base.classes.invoicelines
Session=sessionmaker(bind=engine)
class MyInvoiceType(object):
def __init__(self):
self.session=Session() # actual DB session
# here go functions which read data from pandas dataframe, check it
# and push it out into respective DB tables for invoice data, invoice lines data,
# and batches for each invoice line.
...
</code></pre>
<p>Now, <code>MyInvoiceType</code> is the only place where I use the mapped table classes (Clients,Invoices,InvoiceLines and Batches). What happens is, I get invoice data, check it, and feed it into the 3 invoice data tables, which make up the real invoice.</p>
<p>I feel it is ugly to have so much preparatory things happen outside the class, which would be executed whenever I load this module file, even if I did it by mistake and never instantiated <code>MyInvoiceType</code>. In particular, I don't like <code>sql_conn</code> variable dangling outside any class/function.</p>
<p>Is there a better way to organize this code so that database interaction happens as much as possible only when I try to create a new MyInvoiceType() object? Would it be good or on the contrary, bad? In particular, can (and should I) move all the engine creation and Invoices,etc class creation to inside MyInvoiceType? Can I/Should I do something like <code>self.Clients=Base.classes.clients</code>? What about <code>Batches</code>?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T20:37:45.233",
"Id": "225686",
"Score": "3",
"Tags": [
"python",
"sqlalchemy"
],
"Title": "Code organization: interacting with SQLAlchemy from inside class"
}
|
225686
|
<p>As part of an android app, I've written a simple wrapper that makes requests to an api and fetches stuff. </p>
<pre><code>import android.app.Activity
import android.util.Log
import android.widget.Toast
import com.github.kittinunf.fuel.core.Parameters
import com.github.kittinunf.fuel.httpGet
import com.github.kittinunf.fuel.json.responseJson
import com.github.kittinunf.result.Result
import com.google.gson.Gson
data class Xkcd(val id: Int, val content: String, val link: String, val title: String)
class XkcdClient(private val main: Activity) {
private val API = "https://279fbce3.ngrok.io"
fun search(p: Parameters, callback: (Array<Xkcd>) -> Unit) {
makeRequest("$API/search", p, callback)
}
private inline fun <reified T> makeRequest(url: String, p: Parameters, crossinline callback: (T) -> Unit) {
buildPath(url, p)
.httpGet()
.responseJson { _, _, result ->
when (result) {
is Result.Failure -> {
Log.i("failed", "request failed")
main.runOnUiThread {
Toast.makeText(
main,
"Request Failed!",
Toast.LENGTH_LONG
).show()
}
}
is Result.Success -> {
val json = result.get().obj()
Log.i("json", json.toString())
val res = deserialize<T>(json.get("results").toString())
main.runOnUiThread { callback(res) }
}
}
}
}
}
inline fun <reified T> deserialize(content: String): T {
return Gson().fromJson(content, T::class.java)
}
fun buildPath(url: String, params: Parameters): String {
var url = url
if (params.isNotEmpty()) {
url += "?"
}
for ((p, v) in params) {
url += "$p=$v&"
}
return url.substring(0, url.lastIndex)
}
</code></pre>
<p>It works as I want it to. As such, I'm looking for some advice on how I can make it more idiomatic/elegant. </p>
<hr>
<p>Just FYI: I've written the <code>buildPath</code> myself, as the http library I'm using (<code>kittinuf.fuel</code>) has a bug in its parameter setting method. When it's fixed, I'll be switching to its (hopefully correct) implementation. My method has at least one known bug in it, where if the base url has a trailing slash, it will return a url with double slashes. To avoid getting into all hairy edges cases, I've made sure my hardcoded base url is fine and stripped of a trailing slash. </p>
|
[] |
[
{
"body": "<p>You should look into coroutines.<br>\nCoroutines are the Promises from JavaScript and the CompleteableFutures of Java.<br>\nIt's basically Kotlin handeling the callbacks for you.</p>\n\n<pre><code>suspend fun getString() : String {\n return \"t\"\n}\nsuspend fun main() {\n val t = getString()\n println(t)\n}\n//is roughly the same as:\nfun getString(lamb: (String)->Unit){\n lamb(\"t\")\n}\nfun main() {\n getString{\n println(t)\n }\n}\n</code></pre>\n\n<p>You don't really need to know the implementation, but just some rules:</p>\n\n<p>suspend functions can only be called from suspend-functions (because of the hidden parameter)<br>\nSuspend functions allow you to replace lammbda's with normal code, even try catch blocks!!!</p>\n\n<p>in our case, we can change makeRequest to use suspension functions:</p>\n\n<pre><code>private inline suspend fun <reified T> makeRequest(url: String, p: Parameters) {\n val json = buildPath(url, p)\n .httpGet()\n .awaitObjectResult(jsonDeserializer()).obj()\n Log.i(\"json\", json.toString())\n return deserialize<T>(json.get(\"results\").toString())\n}\n</code></pre>\n\n<p>change the search with:</p>\n\n<pre><code>suspend fun search(p: Parameters) = makeRequest(\"$API/search\", p, callback)\n</code></pre>\n\n<p>then in MainActivity:</p>\n\n<pre><code>class MainActivity : AppCompatActivity(), CoroutineScope by MainScope() {\n override fun onDestroy() {\n cancel() // cancel is extension on CoroutineScope\n }\n\n //you can compare using launch with having a second thread.\n fun showSomeData() = launch { \n try {\n val text = XkcdClient(private val main: Activity).search(..)\n } catch (e : Exception) {\n Log.i(\"failed\", \"request failed\")\n Toast.makeText(\n main,\n \"Request Failed!\",\n Toast.LENGTH_LONG\n ).show()\n }\n }\n}\n</code></pre>\n\n<h1>extra dependencies:</h1>\n\n<ul>\n<li>implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.2'</li>\n<li>implementation 'com.github.kittinunf.fuel:fuel-coroutines:'</li>\n<li>implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.2'</li>\n</ul>\n\n<h1>extra info</h1>\n\n<ul>\n<li><a href=\"https://medium.com/androiddevelopers/coroutines-on-android-part-i-getting-the-background-3e0e54d20bb\" rel=\"nofollow noreferrer\">https://medium.com/androiddevelopers/coroutines-on-android-part-i-getting-the-background-3e0e54d20bb</a></li>\n<li><a href=\"https://kotlinlang.org/docs/reference/coroutines/coroutines-guide.html\" rel=\"nofollow noreferrer\">https://kotlinlang.org/docs/reference/coroutines/coroutines-guide.html</a></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-05T00:21:28.030",
"Id": "230199",
"ParentId": "225688",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T20:58:29.803",
"Id": "225688",
"Score": "1",
"Tags": [
"android",
"json",
"kotlin",
"client"
],
"Title": "Kotlin Android request client"
}
|
225688
|
<p>I am working with a spreadsheet containing a bunch of 'sections', e.g where the 'URL' column is set to 'google.com/search' in A1, and left empty while a bunch of things related to that URL are done in other columns (let's say we extract all of the <p> tags, and list them). As this all applies to the same URL, there's no need to repeat it, so the URL column is left blank until A7, when the URL changes to 'google.com/about'.</p>
<p>I wanted to merge these cells together with the cell containing the URL instead of leaving them empty, but I found myself repeating the same operation a bunch of times:</p>
<ul>
<li>Find a cell with text in it</li>
<li>Drag down until the next cell with text in it</li>
<li>Merge vertically</li>
<li>Repeat.</li>
</ul>
<p>Therefore, I set out to make a macro. For reference, this is my very first experience with Google Apps Script, so while I probably could have done things a lot simpler (please do tell me if so!), I am glad it turned out so long because I learned a lot.</p>
<p>Anyway, here is my code. You simply select a range, and it will apply the aforementioned process to all columns.</p>
<p><em>Disclaimer: All code is my own, except the <code>columnToLetter</code> function, which I <s>stole</s> borrowed from <a href="https://stackoverflow.com/a/21231012/6100832">AdamL's answer</a> on <a href="https://stackoverflow.com/questions/21229180/convert-column-index-into-corresponding-column-letter">this question</a></em></p>
<pre><code>function mergeAtText() {
var spreadsheet = SpreadsheetApp.getActive();
var range = spreadsheet.getActiveRange().getA1Notation();
var toMerge = [];
var toCheck = [];
var axis = range.split(":");
var cols = [];
var rows = [];
// Extract all of the selected rows and columns separately
// This gives us a list of rows (e.g [11, 14, 19, 25]) that
// the selected range notation references (e.g ["A11:B14", "C19:G25"]
// would result in [11, 14, 19, 25]).
// We also do the same with columns, i.e to get ["A", "B", "C", "G"]
for (var i=0;i<axis.length;i++){
var cell = axis[i]
var row = /(\d+)/.exec(cell);
var col = /[a-zA-Z]+/.exec(cell);
if (rows.indexOf(row[0]) < 0){
rows.push(row[0]);
}
if (cols.indexOf(col[0]) < 0){
cols.push(col[0]);
}
}
//Sort the rows
rows = rows.sort();
var rowList = [];
// Loop through from the lowest row number to highest, i.e
// get everything in between: if we have [11, 15], we'd get [11, 12, 13, 14, 15]
for (var i=parseInt(rows[0]);i<parseInt(rows[rows.length-1])+1;i++){
rowList.push(Math.floor(i).toString());
}
rows = rowList;
// Define a helper function...
function getColNum(colName){
return spreadsheet.getRange(colName + ":" + colName).getColumn()-1;
}
function columnToLetter(column){
var temp, letter = '';
while (column > 0){
temp = (column - 1) % 26;
letter = String.fromCharCode(temp + 65) + letter;
column = (column - temp - 1) / 26;
}
return letter;
}
// ... to do the same with columns.
cols = cols.sort();
var colList = [];
for (var i=getColNum(cols[0]);i<getColNum(cols[cols.length-1])+1;i++){
colList.push(columnToLetter(Math.floor(i)+1));
}
cols = colList;
// Now that we have the rows and columns, combine to get all
// of the selected cells in the range individually.
var checker = [];
for (var i=0;i<cols.length;i++){
var toPush = [];
for (var r=0;r<rows.length;r++){
if (checker.indexOf(cols[i]+rows[r]) < 0){
checker.push(cols[i]+rows[r]);
toPush.push(cols[i]+rows[r]);
}
}
toCheck.push(toPush);
}
// For each selected cell...
for (i=0;i<toCheck.length;i++){
var col = toCheck[i];
var inMerge = false;
for (b=0;b<col.length;b++){
var val = spreadsheet.getRange(col[b]).getValue(); // Check if there is some text in it
if (val){ // If there is text
if (inMerge){
toMerge.push([inMerge, col[b-1]]); // Finish any merge ranges we are currently in
}
inMerge = col[b]; // and mark the start of a new merge range
}
}
if (inMerge){
toMerge.push([inMerge, col[col.length-1]]); // At the end, finish off the current merge range
}
}
for (i=0;i<toMerge.length;i++){
spreadsheet.getRange(toMerge[i][0] + ":" + toMerge[i][1]).mergeVertically(); // Simply go through each range, and merge them.
}
};
</code></pre>
<p>Any comments on code quality, conciseness, etc. are appreciated. Also, any suggestions on how to update the population code to work with multiple selection ranges would be appreciated.</p>
<p>Here's a GIF giving an example of the usage (apologies about low resolution):</p>
<p><a href="https://i.stack.imgur.com/2AjUZ.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2AjUZ.gif" alt="GIF"></a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-06T21:02:03.610",
"Id": "225689",
"Score": "3",
"Tags": [
"google-apps-script",
"google-sheets"
],
"Title": "Eliminate all empty cells via vertical merging: Google Sheets"
}
|
225689
|
<p>I am an OOP programmer by trade (Java) who is extremely new to Haskell and the world of purely functional languages. To get my feet wet, I decided to try and write a little musical interval translator/calculator. I am immediately impressed with this language. The power of this allowed me to quickly define an algebra called PitchClass and define a default Isomorphism between many Enumerated types.</p>
<p>With this code I am able to write things like <code>C +: P5</code> and get <code>G</code> (the perfect fifth of C) as an output in the GHCi REPL.</p>
<p>I can write </p>
<pre><code>λ: cycleOfFifths = cycle $ map (iso . (P5*:)) [3 .. 12] :: [NoteName]
λ: take 5 cycleOfFifths
</code></pre>
<p>And it will output 5 notes from the circle of fifths <code>[Gb,Db,Ab,Eb,Bb]</code> (which, by the way, are all root notes in the chord progression of Dave Brubeck's jazz standard named... you guessed it... <code>take 5</code> :D) </p>
<pre><code>class (Enum a) => PitchClass a where
iso :: (PitchClass b) => a -> b
iso = toEnum . fromIntegral . abs . (flip mod 12) . fromIntegral . fromEnum
fiso :: (PitchClass b) => (b -> b) -> a -> a
fiso f = iso . f . iso
(+:) :: (PitchClass b) => a -> b -> a
(+:) x = iso . fiso ((iso x :: Int)+)
(*:) :: (PitchClass b) => a -> b -> a
(*:) x = iso . fiso ((iso x :: Int)*)
(-:) :: (PitchClass b) => a -> b -> a
(-:) x = iso . fiso ((iso x :: Int)-)
instance PitchClass Integer
instance PitchClass Int
data NoteName = A | Bb | B | C | Db | D | Eb | E | F | Gb | G | Ab deriving (Show, Eq, Enum, Bounded);
instance PitchClass NoteName
data Solfege = Do | Di | Re | Ri | Mi | Fa | Fi | Sol | Si | La | Li | Ti deriving (Show, Eq, Enum, Bounded);
instance PitchClass Solfege
data Interval = R | Mi2 | Ma2 | Mi3 | Ma3 | P4 | TT | P5 | Mi6 | Ma6 | Mi7 | Ma7 deriving (Eq, Enum, Show, Bounded);
instance PitchClass Interval
</code></pre>
<p>I am a beginner in Haskell, and I was floored by how elegant this was. So I decided to take it further. I wanted to treat a PitchClass as an actual mathematical ring, and have Haskell treat it as such. From reading the doc, it seems that the Num type class is what I need to accomplish this, so I added the following:</p>
<pre><code>instance Num Solfege where
(+) = (+:)
(*) = (*:)
abs = fiso (abs :: Integer -> Integer)
signum = fiso (signum :: Integer -> Integer)
fromInteger = iso
negate = fiso (negate :: Integer -> Integer)
instance Num Interval where
(+) = (+:)
(*) = (*:)
abs = fiso (abs :: Integer -> Integer)
signum = fiso (signum :: Integer -> Integer)
fromInteger = iso
negate = fiso (negate :: Integer -> Integer)
instance Num NoteName where
(+) = (+:)
(*) = (*:)
abs = fiso (abs :: Integer -> Integer)
signum = fiso (signum :: Integer -> Integer)
fromInteger = iso
negate = fiso (negate :: Integer -> Integer)
</code></pre>
<p>I am looking for any feedback on either of these two parts. Is there anything that can be made more elegant, or more idiomatic for Haskell programmers?</p>
<p>Here are some things that have been bugging me, but keep in mind I am open to any advice to make my code cleaner, easier to read, and more idiomatic (naming conventions, indention, etc.):</p>
<ol>
<li><p>The Num instancing works, but this is far less elegant than my
PitchClass, and there are multiple things that I don't like about
it. First of all, I repeated the same code three times. Is there a
way that I can avoid this duplication? </p></li>
<li><p>Secondly, in this case, it would make sense to instance Num on the
PitchClass, as in the type of (+) should be something like <code>Num PitchClass</code> so that I can write <code>C + P5</code>. I don't think the Type
System allows this, as PitchClass is a type class, not a type (this
took me a lot of fiddling and research for my feeble OOP brain to
grasp). However, I still can't shake the feeling that there is some
design pattern that would allow this. If there isn't, I am assuming
its bad from the perspective of Haskell's philosophy? If so, I'd
love it if an answerer or commenter could explain why.</p></li>
<li><p>Finally, a lot of the things I've tried have given me errors from
the GHC compiler, and many of these Errors have suggested
extensions. I am not used to the concept of "extensions" in
languages. Are there extensions that I could use to make my code
better that are still considered safe/stable/idiomatic?</p></li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T04:27:48.027",
"Id": "438285",
"Score": "0",
"body": "I am planning on making the exact same thing in a different language. I would also like to add intervals to notes. I'm also using a ring. Perhaps you can get some ideas how to use modular arithmetic from this question: https://codereview.stackexchange.com/questions/223697/music-theory-the-basics-a-ring"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T04:34:21.977",
"Id": "438286",
"Score": "0",
"body": "By the way, if you want to able to do something like C+ P5, you can use C# and use operator overloads. _Note c = \"C\"; Note g = c + \"P5\";_"
}
] |
[
{
"body": "<p>The first two points can be answered by <a href=\"https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#extension-DerivingVia\" rel=\"nofollow noreferrer\"><code>DerivingVia</code></a>. It is one of the newer extensions that allows to derive a class instance by delegating to an existing instance for a representationally equivalent type. You can do something like this:</p>\n\n<pre><code>newtype PitchWrapper a = PitchWrapper a\n\ninstance PitchClass a => Num (PitchWrapper a) where\n (PitchWrapper a) + (PitchWrapper b) = a +: b\n ... and do on\n\nderiving via (PitchWrapper NoteName) instance Num NoteName\nderiving via (PitchWrapper Solfege) instance Num Solfege\nderiving via (PitchWrapper Interval) instance Num Interval\n</code></pre>\n\n<hr>\n\n<p>That said, even though this is possible, I must warn you that it is not a good idea. </p>\n\n<p>This is a very common pattern that I see in newcomers (including myself): overload all the things, declare operators for everything, make everything as short as possible. The language makes it possible, so let's run wild with it.</p>\n\n<p>Never works out well in practice. If you follow this pattern, you usually end up with spaghetti code that nobody can understand without looking up every single character.</p>\n\n<p>I would even argue that in this case it doesn't make sense. Look: notes do not actually constitute a ring. You don't add two notes together to get another note. You add intervals to notes, but not notes to each other.</p>\n\n<hr>\n\n<p>Now, about extensions.</p>\n\n<p>Unlike most languages, which simply add new features in every new release, the Haskell designers chose to give the power to the user. When you install a new version of GHC, you don't just get all the new features. You get a choice to opt-in.</p>\n\n<p>This is what most extensions are: merely an opt-in mechanism for new language features.</p>\n\n<p>It is true that there are some problematic extensions, but those are few and far between. In most cases, you'll be just fine turning on everything you see in those error messages.</p>\n\n<p>There are numerous works on the internet describing and/or recommending particular sets of extensions to use. <a href=\"https://limperg.de/ghc-extensions/\" rel=\"nofollow noreferrer\">Here's one example</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T02:02:17.013",
"Id": "225693",
"ParentId": "225691",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "225693",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T00:55:38.193",
"Id": "225691",
"Score": "7",
"Tags": [
"beginner",
"haskell",
"music"
],
"Title": "Haskell PitchClass Algebra, in which notes have various names"
}
|
225691
|
<p>I have many pieces of HTML code that are used in many parts of the website (controlled by javascript), like edit forms and dialogs. Instead of <code>include</code>-ing the html files using php, I made a system for storing these elements in a javascript variable array such that I can choose which files to include in each page and which files will be downloaded via ajax (and cached) only in the case they are needed.</p>
<p>Is this generally a good approach or should this kinda stuff be handled differently?</p>
<h2>javascript file</h2>
<pre><code>var templates = [];
// convenience method for getting a copy of a template
async function copyTemplate(filename){
return await getTemplate(filename, true);
}
// get a template from cache, or if not found download it via ajax
async function getTemplate(filename, returnClone = false){
let template = templates[filename];
if(template == undefined){
template = templates[filename] = await getElementAjax('templates/' + filename);
}
return returnClone ? template.cloneNode(true) : template;
}
// called from code echoed by php to include some
// templates without additional http requests
function saveTemplate(template){
const templateElem = template.content.firstElementChild;
const buttons = templateElem.querySelectorAll('button');
for(let i = 0; i < buttons.length; i++){
preventAutoSubmit(buttons[i]);
}
templates[template.getAttribute('data-file')] = templateElem;
}
// gets an element from a file via ajax, I excluded the
// implementation of functions called by this function for brevity.
async function getElementAjax(url) {
const response = await ajax(url, 'GET', null, 'document');
const mainElem = response.getElementsByTagName('body')[0].firstElementChild;
const buttons = mainElem.querySelectorAll('button');
for(let i = 0; i < buttons.length; i++){
preventAutoSubmit(buttons[i]);
}
return mainElem;
}
</code></pre>
<h2>php file</h2>
<pre><code>function includeTemplates(){
$args = func_get_args();
foreach($args as $url){
$code = file_get_contents('templates/' . $url);
echo "<template data-file='$url'>$code</template>";
}
?>
<script>
{
const templates = document.getElementsByTagName('template');
for(let i = templates.length - 1; i >= 0; i--){
if(templates[i].hasAttribute('data-file')){
saveTemplate(templates[i]);
templates[i].remove();
}
}
}
document.currentScript.remove();
</script>
<?php
}
</code></pre>
<h2>Usage example</h2>
<pre><code><?php includeTemplates('logs/logEntry.html',
'logs/logEntryEditForm.html',
'foo/bar.html'
); ?>
<script>
async function populateLog(){
const logEntries = await getLogEntries();
const logContainer = document.getElementById('logContainer');
for(entry of logEntries){
const entryElem = await copyTemplate('logs/logEntry.html');
//
// ... set textContent and other properties for elements in entryElem ...
//
logContainer.appendChild(entryElem);
}
}
</script>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T06:38:34.613",
"Id": "438321",
"Score": "0",
"body": "So instead of building a webpage on the server, and retrieving it with one call, which is totally possible for the example you give, you use the client's browser to build the page using many calls? I struggle to find a use case for this. I guess that in certain situations it could reduce the amount of bytes transmitted, needed to build a page, but that would be the exception. I also wonder how this would affect the user experience on a slower device."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T10:05:36.407",
"Id": "438361",
"Score": "0",
"body": "@KIKOSoftware in this example it enables loading the rest of the page without having to wait for the time consuming part (`getLogEntries()`) which is loaded via ajax. The template retrieved with `copyTemplate(...)` in this example is downloaded together with the first http request (see the php function `includeTemplates(...)` which is called above the script element to echo the templates and add them to the templates cache)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T10:12:48.237",
"Id": "438362",
"Score": "0",
"body": "Also it does end up reducing the amount of bytes transmitted, having hundreds of log entries would mean sending a copy of the template hundreds of times from the server instead of just once."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T10:17:12.317",
"Id": "438363",
"Score": "0",
"body": "I get the second advantage, which I also mentioned, but the first one is debatable. You say that `getLogEntries()` is slow, and I believe you, but you still use it, so the page will still be slow at showing relevant information. If this function is slow it would be better not to retrieve all log entries, but just show a few, and only when the user scrolls down, or selects to see more entries, you load more."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T10:43:03.903",
"Id": "438368",
"Score": "0",
"body": "You're right @KIKOSoftware , I can load a part of it quickly and then load the rest with ajax. But this slow part is not what my templates system is responsible for, so far I understand that the templates are useful for reducing data transmission as you said, but other than that it's not really different from just `echo`ing the code normally, just saves a few lines of code here and there for `echo`ing and accessing these templates."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T13:01:42.653",
"Id": "438378",
"Score": "0",
"body": "Offtopic maybe? *\"Javascript + php system for reusable HTML templates\"* Talking about reusable HTML templates.. HTML5 supports it [native](https://html.spec.whatwg.org/multipage/scripting.html#the-template-element), browser support is [ok](https://caniuse.com/#search=HTML%20templates)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T01:27:13.230",
"Id": "225692",
"Score": "2",
"Tags": [
"javascript",
"php",
"html",
"template"
],
"Title": "Javascript + php system for reusable HTML templates"
}
|
225692
|
<p>I was recently working on some python where I was working with multiple inheritance and mixins and stuff like that, and I wanted to inherit docstrings for specific functions, from specific parents (particularly in the case of the mixins). Anyways, I came up with this recipe for inheriting docstrings and was hoping for some feedback on the strategy I used. </p>
<pre class="lang-py prettyprint-override"><code>def get_doc(func, class_, check_self=True):
check_self = int(not check_self)
for parent in class_.__mro__[check_self:]:
doc = parent.__dict__.get(func.__name__, None).__doc__
if doc is not None:
return doc
return ""
def prepend(parent, child):
return f"{parent}\n{child}"
def doc_inherit(class_, check_self=True, combine=prepend):
def decorator(func):
doc = get_doc(func, class_, check_self)
func.__doc__ = combine(doc, "" if func.__doc__ is None else func.__doc__
return func
return decorator
</code></pre>
<p>Usage:</p>
<pre class="lang-py prettyprint-override"><code>In [1]: class A:
...: def instance_method(self, *args):
...: "A.instance_method"
...: pass
...:
In [2]: class B(A):
...: @doc_inherit(A)
...: def instance_method(self, *args):
...: "B.instance_method"
...: pass
...:
In [3]: help(B.instance_method)
Help on function instance_method in module __main__:
instance_method(self, *args)
A.instance_method
B.instance_method
In [4]: help(B().instance_method)
Help on method instance_method in module __main__:
instance_method(*args) method of __main__.B instance
A.instance_method
B.instance_method
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T03:05:10.937",
"Id": "225695",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"inheritance",
"reflection",
"meta-programming"
],
"Title": "Inherit docstrings from specified parent"
}
|
225695
|
<p>There are two sorted arrays nums1 and nums2 of size <code>m</code> and <code>n</code> respectively.</p>
<p>Find the median of the two sorted arrays. The overall run time complexity should be <span class="math-container">\$O(log (m+n))\$</span>.</p>
<p>You may assume nums1 and nums2 cannot be both empty. <br/></p>
<blockquote>
<p>nums1 = [1, 3] nums2 = [2]</p>
<p>The median is 2.0</p>
</blockquote>
<pre><code>def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
concat = sorted(nums1 + nums2)
median = concat[len(concat) //2] if len(concat)%2 != 0 else (concat[len(concat) //2] \
+concat[((len(concat))//2)-1])/2
return median
</code></pre>
<p>I want to make this faster.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T05:13:18.230",
"Id": "438288",
"Score": "1",
"body": "That is a \\$O((m+n)\\log (m+n))\\$ solution, not \\$O(\\log (m+n))\\$."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T08:02:39.040",
"Id": "438333",
"Score": "0",
"body": "can you tell me how you calculate that way?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T08:03:02.977",
"Id": "438334",
"Score": "0",
"body": "and if you know the better solution let me know"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T08:04:53.437",
"Id": "438336",
"Score": "1",
"body": "You sort an array with \\$ n+m \\$ elements. – I suggest to have a look at the \"Related” section on the right. There you'll find Q&As about the same problem, with more efficient solutions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T15:29:18.043",
"Id": "438394",
"Score": "0",
"body": "@MartinR due to how python sorts lists, this is actually only `O(m+n)`. Timsort (which python uses) will detect the 2 sorted sub-sequences and merge them in one merge step."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T15:43:42.830",
"Id": "438398",
"Score": "0",
"body": "@OscarSmith: I see, thanks for the information. – But the goal is O(log(m+n)) so that a more sophisticated solution is needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T16:09:50.963",
"Id": "438403",
"Score": "0",
"body": "agreed. Just pointing out that this solution is slightly better than it appears on first glance"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T03:31:59.170",
"Id": "225696",
"Score": "1",
"Tags": [
"python",
"performance",
"python-3.x",
"statistics"
],
"Title": "Find the median of two sorted arrays"
}
|
225696
|
<p>I've written a python program do perform synthetic division on a polynomial. There are a few constraints (listed in the module docstring of the program) on the polynomial, mainly because I haven't had the time to work out all the edge cases. I would like feedback on everything possible, as I plan to use this to solve other polynomials. All feedback is welcome, appreciated, and considered!</p>
<p><strong>Constraints</strong></p>
<ol>
<li><blockquote>
<p>Coefficients must only be one digit, if present</p>
</blockquote></li>
<li><blockquote>
<p>Constant must be one digit, and must be present (even 0)</p>
</blockquote></li>
<li><blockquote>
<p>Constant <em>must</em> be positive</p>
</blockquote></li>
</ol>
<p><strong>synthetic_division.py</strong></p>
<pre><code>"""
SYNTHETIC DIVISION CALCULATOR
This program accepts a polynomial and returns all the
x intercepts.
Program has some constraints:
- Coefficients must only be one digit, if present
- Constant must be one digit, and must be present (even 0)
- Constant must be positive
EX:
Input: x^3 -4x^2 +x +6
Output: X = [3, -1, 2]
"""
from functools import reduce
def get_coefficients(equation):
"""
Returns the coefficients of the passed polynomial. If no coefficent, then 1 is returned.
Only works for single digit coefficents, if present.
:param equation: The equation to be analyzed
"""
parts = equation.split()
coeffs = []
for part in parts:
if part[0] == "x":
coeffs.append(1)
if part[0] == "-":
coeffs.append(int(part[1]) * -1)
if part[0] == "+" and "x" in part:
if len(part) == 2:
coeffs.append(1)
else:
coeffs.append(int(part[1]))
return coeffs
def get_factors(equation):
"""
Returns a list of factors of the constant
:param n: Number to get factors from
"""
constant = int(equation[len(equation) - 1])
###########################################
"""
===========================================
Equation from StackOverflow user @agf
https://stackoverflow.com/a/6800214/8968906
===========================================
"""
factors = list(
set(
reduce(
list.__add__, (
[i, constant//i] for i in range(1, int(constant**0.5) + 1) if constant % i == 0
)
)
)
)
###########################################
#Add negatives
length = len(factors)
for i in range(length):
factors.append(-factors[i])
return factors
def synthetic_division(coefficients, factors):
"""
Performs synthetic division with the passed coefficients and factors
Returns a list of intercepts
:param coefficients: Coefficients to use in the calculation
:param factors: Factors to test
"""
coeffs = coefficients
facs = factors
ints = []
for fac in facs:
current_sum = 0
for coeff in coeffs:
current_sum += coeff
current_sum *= fac
if current_sum == 0:
ints.append(fac)
return ints
def main(equation):
"""
Gathers the coefficients, factors and intercepts from the equation
:param equation: The polynomial to be solved
"""
coefficients = get_coefficients(equation)
constant = int(equation[len(equation) - 1])
coefficients.append(constant)
factors = get_factors(equation)
intercepts = synthetic_division(coefficients, factors)
return intercepts
if __name__ == '__main__':
EQUATION = "x^3 -4x^2 +1x +6"
print(f"X = {main(EQUATION)}")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T06:26:43.723",
"Id": "438314",
"Score": "0",
"body": "Your program prints an empty list for `EQUATION = \"x^2 +0x -1\"` – shouldn't the result be `[-1, 1]` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T06:31:19.777",
"Id": "438317",
"Score": "1",
"body": "@MartinR Currently, one of the constraints is that the constant has to be positive, which explains why your equation didn't work. I will update the question to make it clearer what the constraints are."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T06:46:14.780",
"Id": "438326",
"Score": "0",
"body": "I see. The problem is that your get_coefficients function does not capture the constant coefficient. – Btw, is this really a “synthetic division”? If I understand your code correctly, you determine all factors of the constant coefficient and try each of them if it solves the equation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T08:16:01.590",
"Id": "438339",
"Score": "0",
"body": "@MartinR I append the constant to the end of the list of coefficients in the `main` method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T08:17:09.510",
"Id": "438341",
"Score": "0",
"body": "Yes, that is the part which works only for positive (single-digit) constants."
}
] |
[
{
"body": "<p>Currently some of your code is very specialized to the exact use case you have. For example, the <code>get_factors</code> function takes the unparsed equation and needs to extract the constant itself. It would be a lot better if it just took a number and the parsing happens elsewhere. This way if you improve the parsing (to include multi-digit numbers, etc), you don't need to change the <code>get_factors</code> function.</p>\n\n<p>At the same time, that function is borderline unreadable. It is also not the most efficient. Consider this alternative, which is shorter in lines of code, IMO way easier to read, and about two times faster:</p>\n\n<pre><code>def get_factors_of_constant(equation):\n c = int(equation[-1])\n factors = set()\n for i in range(1, int(c**0.5) + 1):\n if c % i == 0:\n factors.update([i, c // i, -i, -c // i])\n return list(factors)\n</code></pre>\n\n<hr>\n\n<p>For a better parsing, consider the output of the following regex:</p>\n\n<pre><code>import re\n\nequation = 'x^3 -4x^2 +1x +6'\nprint(re.findall(r'\\s?([\\+\\-]?\\s?\\d*)?(x)?\\^?(\\d*)?', equation))\n# [('', 'x', '3'), ('-4', 'x', '2'), ('+1', 'x', ''), ('+6', '', ''), ('', '', '')]\n</code></pre>\n\n<p>It produces tuples of coefficients, whether or not there is an <code>x</code> and exponents. If the coefficient is empty, a <code>1</code> is assumed, if the exponent is empty, it is either a <code>1</code> or a <code>0</code>, depending on if there is an x, and if all three are empty, you can skip it.</p>\n\n<pre><code>def parse(equation):\n coefficients, exponents = [], []\n matches = re.findall(r'\\s?([\\+\\-]?\\s?\\d*)?(x)?\\^?(\\d*)?', equation)\n for coefficient, x, exponent in matches:\n if coefficient == x == exponent == \"\":\n continue\n coefficients.append(coefficient.replace(\" \", \"\") or \"1\")\n exponents.append(exponent or \"1\" if x else \"0\")\n coefficients = list(map(int, coefficients))\n exponents = list(map(int, exponents))\n return coefficients, exponents\n\nprint(parse(equation))\n# ([1, -4, 1, 6], [3, 2, 1, 0])\n</code></pre>\n\n<p>This can also parse multi-digits and deals both with missing parts (since you have the info on the exponent) and additional whitespace between number and sign:</p>\n\n<pre><code>parse(\"x^3 - 10x + 2\")\n# ([1, -10, 2], [3, 1, 0])\nparse(\"x\")\n# ([1], [1])\n</code></pre>\n\n<p>It is also not perfect, for example it fails in this case:</p>\n\n<pre><code>parse(\"-x^2\")\n# ValueError: invalid literal for int() with base 10: '-'\n</code></pre>\n\n<p>You would need to add some special cases to the function for it to cover all edge cases, but it should be a good starting point.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T09:26:57.013",
"Id": "440139",
"Score": "1",
"body": "I'm not sure if `'x'` is legal input (examples are a bit inconsistent with omitting the `1`), but the code doesn't appear to handle it properly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T09:30:18.723",
"Id": "440140",
"Score": "1",
"body": "@JAD I thought I could get away with not checking that `x` is also empty, but apparently I couldn't. Fixed."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T09:16:11.953",
"Id": "225817",
"ParentId": "225699",
"Score": "6"
}
},
{
"body": "<h2>Bugs</h2>\n\n<blockquote>\n<pre><code> if part[0] == \"-\":\n coeffs.append(int(part[1]) * -1)\n</code></pre>\n</blockquote>\n\n<p>Nowhere in the restrictions does it say that <code>-x^2</code> is not a valid monomial. (It's not constant, and it doesn't have more than one digit of coefficient). But it isn't handled correctly.</p>\n\n<hr>\n\n<p><code>x^2 -2x +1</code> gives output <code>[1]</code>. We'd expect the same output for <code>2x^2 -4x +2</code>, but that gives output <code>[]</code>. The coefficients are still single digits, and the constant term is still positive, so again this meets all of the documented restrictions.</p>\n\n<hr>\n\n<h2>Documentation</h2>\n\n<blockquote>\n<pre><code>def get_factors(equation):\n \"\"\"\n Returns a list of factors of the constant\n\n :param n: Number to get factors from\n\n \"\"\"\n</code></pre>\n</blockquote>\n\n<p>There's no parameter <code>n</code>. Now, it would be better to take an integer <code>n</code> and factor that, because that is a very reusable function, whereas a function which takes an equation and factors its constant term has almost no reuse value.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>def synthetic_division(coefficients, factors):\n \"\"\"\n Performs synthetic division with the passed coefficients and factors\n Returns a list of intercepts\n\n :param coefficients: Coefficients to use in the calculation\n :param factors: Factors to test\n\n \"\"\"\n</code></pre>\n</blockquote>\n\n<p>This is a classic example of documentation which tells me virtually nothing that I can't already see in the signature. The only useful line there is the one which tells me what it returns, and even there it's either unspecific or inaccurate: specifically, it returns (or, I assume the intention is that it should return) a list containing <em>all</em> the <em>integer</em> roots.</p>\n\n<p>What I would find more useful from the documentation is</p>\n\n<ol>\n<li>A reference to explain what <em>synthetic division</em> is.</li>\n<li>A statement that the coefficients are coefficients of an integer polynomial, and the endianness.</li>\n<li>An explanation of what <code>factors</code> is. (I would be inclined to rename the variable to <code>candidate_integer_roots</code>).</li>\n</ol>\n\n<p>And having arrived at that level of understanding, the name is an irrelevance: what matters is the effect of the function (filters candidate roots to identify the true ones), not the algorithm employed (which is, in any case, not a division at all: it's polynomial evaluation using Horner's method).</p>\n\n<p>And given that this is Python, which has reasonally good functional programming support baked in, I would think it worthwhile to refactor into a function which tests a single candidate root, and then use a comprehension with that as a filter in <code>main</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T10:27:31.833",
"Id": "225820",
"ParentId": "225699",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "225817",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T06:06:01.407",
"Id": "225699",
"Score": "10",
"Tags": [
"python",
"python-3.x",
"math-expression-eval",
"symbolic-math"
],
"Title": "Synthetic division calculator"
}
|
225699
|
<p>I want to refactor this in Java to reduce my code duplication.</p>
<pre><code>public HashMap<String,String> setupProductsUid() throws Exception {
OutputMessage actual = statusUpdaterTest.getOutputMessageWithUidOfNewProductsNode();
HashMap<String,String> map = new HashMap<>();
map.put("replaceThisProductsUid", actual.getQuery().get(0).getUid());
return map;
}
public HashMap<String,String> setupProductsAndProductUid() throws Exception {
OutputMessage actual = statusUpdaterTest.getOutputMessageWithUidOfNewProductsNode();
HashMap<String,String> map = new HashMap<>();
map.put("replaceThisProductsUid", actual.getQuery().get(0).getUid());
map.put("replaceThisProductUid", actual.getQuery().get(0).getProducts().get(0).getUid());
return map;
}
public HashMap<String,String> setupProductsAndProductAndOptionsUid() throws Exception {
OutputMessage actual = statusUpdaterTest.getOutputMessageWithUidOfNewProductsNode();
HashMap<String,String> map = new HashMap<>();
map.put("replaceThisProductsUid", actual.getQuery().get(0).getUid());
map.put("replaceThisProductUid", actual.getQuery().get(0).getProducts().get(0).getUid());
map.put("replaceThisOptionUid1", actual.getQuery().get(0).getProducts().get(0).getOptions().get(0).getUid());
return map;
}
public HashMap<String,String> setupProductsAndProductAndOptionsMultipleUids() throws Exception {
OutputMessage actual = statusUpdaterTest.getOutputMessageWithUidOfNewProductsNode();
HashMap<String,String> map = new HashMap<>();
map.put("replaceThisProductsUid", actual.getQuery().get(0).getUid());
map.put("replaceThisProductUid", actual.getQuery().get(0).getProducts().get(0).getUid());
map.put("replaceThisOptionUid1", actual.getQuery().get(0).getProducts().get(0).getOptions().get(0).getUid());
map.put("replaceThisOptionUid2", actual.getQuery().get(0).getProducts().get(0).getOptions().get(1).getUid());
map.put("replaceThisOptionUid3", actual.getQuery().get(0).getProducts().get(0).getOptions().get(2).getUid());
return map;
}
</code></pre>
<p><strong>Edit:</strong>
To provide some context, OutputMessage is a deserialized representation of a JSON data response from Dgraph.
The data coming back from Dgraph looks like this:</p>
<pre><code>{
"uid": "0x2938",
"collectionId": 1,
"products": [
{
"uid": "0x345",
"productId": 19610626,
"options": [
{
"uid": "0x45256",
"optionId": 32661491,
"datetime": "2018-10-31T10:19:32.242",
"expected": true
}
]
}
]
}
</code></pre>
<p>I have no way to prevent Dgraph from creating arrays for single-object parent-child relationships. It's just the way they have architected the node-edge structure in their graph.</p>
<p><strong>Edit 2:</strong>
These functions are getting called by a method that substitutes the keys for the values in the map in test JSON data. The reason for the substitution is that I need a way to obtain UIDs from Dgraph (because the IDs are managed by Dgraph, so I need to query Dgraph after creating the Dgraph nodes in order to find out what UIDs Dgraph will give me for the nodes). </p>
<p>Here's the method that replaces placeholders in the JSON data:</p>
<pre><code>public String updateIncomingJsonByReplacingMapValues(HashMap<String, String> map, String incomingJsonWithoutUids) {
for (Entry<String, String> entry : map.entrySet()) {
incomingJsonWithoutUids = incomingJsonWithoutUids.replace(entry.getKey(), entry.getValue());
}
return incomingJsonWithoutUids;
}
</code></pre>
<p>Here's an example of a test method that calls the function that replaces placeholders with test data:</p>
<pre><code>@Test
public void incomingJsonIsEmptyProductsCollectionWithOnlyProductsUid() throws Exception{
HashMap<String,String> map = setupProductsUid();
String incomingJsonWithoutUids = statusUpdaterTest.readTestFile("dgraph_writer_test/02_empty_products_node_in_dgraph.json");
// Update placeholders with Uid's
String updatedJson = updateIncomingJsonByReplacingMapValues(map, incomingJsonWithoutUids);
// Then, write the updated Json to Dgraph and check that the returned UIDs are as expected.
DgraphClient dgraphClient = statusUpdaterTest.createDgraphClient(false);
Map<String, String> uidMap = mutate(dgraphClient, updatedJson);
Assert.assertNotNull(uidMap);
Assert.assertTrue(uidMap.isEmpty());
}
</code></pre>
<p>The file <code>"dgraph_writer_test/02_empty_products_node_in_dgraph.json"</code> contains this data:</p>
<pre><code>{
"uid": "replaceThisProductsUid",
"collectionId": 1,
"products": [
]
}
</code></pre>
<p>Other JSON examples have a lot more data than this one.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T07:01:15.360",
"Id": "438331",
"Score": "1",
"body": "Please provide more information so that we can understand your situation and give you proper advice. What does the code for `statusUpdaterTest` look like? Do these methods really need to return `HashMap`s, or would any `Map<String,String>` suffice?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T13:58:03.420",
"Id": "438385",
"Score": "0",
"body": "You might want to think about looping in the last function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T15:44:14.650",
"Id": "438399",
"Score": "0",
"body": "@200_success any Map<String,String> is fine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T19:08:17.063",
"Id": "438431",
"Score": "0",
"body": "@200_success I added more information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T05:20:03.907",
"Id": "438455",
"Score": "2",
"body": "@devinbost Your question was \"How can I refactor this with functional programming in Java to reduce my duplication?\" Which goes beyond the scope of Code Review. WRT the question, your code did not work. There is no need for you to get defensive. Just move the question to Stack Overflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T04:57:03.270",
"Id": "439179",
"Score": "3",
"body": "@TorbenPutkonen How much more would I need to provide for the code to be considered \"working code\"? The code does not throw exceptions, it completes the desired task, and it runs without errors. The question is how to improve the code, plain and simple."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T07:57:57.530",
"Id": "439214",
"Score": "2",
"body": "@devinbost The \"working code\" needs to be taken in the context of what you are asking for. You were asking about functional programming and your code had no FP. Therefore it could not be considered working. It's correct place would thus have been Stack Overflow. Once you have it implemented using FP, you can come here to ask for review of your FP implementation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T19:28:33.707",
"Id": "439461",
"Score": "1",
"body": "@TorbenPutkonen Is that actually stated in the instructions for codereview.stackexchange.com?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T14:07:28.020",
"Id": "440188",
"Score": "1",
"body": "@TorbenPutkonen I have to agree with the OP devinbost on this. Please see my answer to this related meta question: https://codereview.meta.stackexchange.com/q/9277/31562"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T06:35:43.557",
"Id": "225700",
"Score": "1",
"Tags": [
"java",
"unit-testing",
"functional-programming",
"hash-map"
],
"Title": "Building maps for Dgraph integration tests in Java 8"
}
|
225700
|
<p><strong>Problem</strong>:
<a href="https://leetcode.com/problems/string-to-integer-atoi" rel="nofollow noreferrer">String to integer(leetcode)</a></p>
<blockquote>
<p>Implement <code>atoi</code> which converts a <em>string to an integer</em>.</p>
<p>The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.</p>
<p>The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.</p>
<p>If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.</p>
<p>If no valid conversion could be performed, a zero value is returned.</p>
<p><strong>Note:</strong></p>
<ul>
<li>Only the space character <code>' '</code> is considered as a whitespace character.</li>
<li>Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [-2^31, 2^31-1]. If the numerical value is out of the range of representable values, (2^31-1) or -2^31 is returned.</li>
</ul>
</blockquote>
<p><strong>My solution</strong>:</p>
<p>I have implemented this code below. I have noted down the requirements and implemented the code. It was hard to keep track of all the details. Before acceptance, I got WA 4 times(and it seems like the code I've written is not compact).</p>
<pre><code>class Solution:
def myAtoi(self, s: str) -> int:
l = len(s)
if l==0:
print(1)
return 0
if l==1:
if s==" " or s=="+" or s=="-":
return 0
elif(s.isnumeric()):
return int(s)
else:
return 0
res = ""
i = 0
while(i<l and s[i]==" "):
i+=1
if i==l:
return 0
ispos = False
if(s[i]=="+"):
ispos = True
i+=1
isnegative = False
if(s[i]=='-' and not ispos):
isnegative = True
i+=1
if(i<len(s) and not s[i].isnumeric() and s[i]!='+' and s[i]!='-'):
return 0
while(i<l):
if s[i].isnumeric():
res += s[i]
else:
break
i+=1
if len(res)>0:
x = int(res)
else:
return 0
if isnegative:
if x>=(1<<31):
return -(1<<31)
x *= -1
if x>=((1<<31) - 1):
return (1<<31)-1
return x
</code></pre>
<p>Can anyone write a compact code for this problem?</p>
<hr />
<p>I also like to know if there is an <em>approach to solve this kind of implementation problems</em> so that I can write compact code. Can anyone share any better method to analyze this type of implementation problem? (or, any suggestion to be better in solving this kind of problems where we need to keep track of many things)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T08:43:29.527",
"Id": "438344",
"Score": "3",
"body": "Could you include the problem statement in the question? Links can rot."
}
] |
[
{
"body": "<h2>Styling</h2>\n\n<p>Try to make the code follow the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8 Style Guidelines</a>, this will make your code follow the Python conventions, and also more readable. So do \n<code>if l == 1</code> instead of <code>if l==1</code>, <code>my_atoi</code> instead of <code>myAtoi</code>, etc</p>\n\n<h2>Code structure</h2>\n\n<p>It seems that page requires the code to be inside a class. Leaving the exercise aside for a moment:\nYou don't need that function inside a class, because you are never using anything of the class itself. It makes more sense to define that method outside the class, and without the (unused) <code>self</code> parameter.</p>\n\n<h2>Skiping whitespaces</h2>\n\n<pre class=\"lang-py prettyprint-override\"><code>while(i<l and s[i]==\" \"):\n i+=1\n if i==l:\n return 0\n</code></pre>\n\n<ol>\n<li>You don't need those parenthesis on the <code>while</code> in Python.</li>\n<li>Your code might not detect some whitespace characters like <code>\\t</code> (it seems the exercise accepts that though); use the method <a href=\"https://python-reference.readthedocs.io/en/latest/docs/str/isspace.html\" rel=\"nofollow noreferrer\"><code>isspace()</code></a>. </li>\n<li>Instead of checking <code>i == l</code> on every iteration (when it could only happen in the last one), check it once you are out of the loop. This allows us to remove the special treatment to empty strings: if <code>s</code> is empty, it won't enter the loop and <code>i == l</code>, so it will return 0.</li>\n</ol>\n\n<pre class=\"lang-py prettyprint-override\"><code>while i < l and s[i].isspace():\n i += 1\n\nif i == l:\n return 0\n</code></pre>\n\n<h2>Sign</h2>\n\n<p>Your code to handle the sign is too complicated. Instead of keeping <code>ispos</code> and <code>isnegative</code>, you could just keep a <code>factor</code> that is either 1 or -1. So instead of </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>ispos = False\nif(s[i]==\"+\"):\n ispos = True\n i+=1\nisnegative = False\nif(s[i]=='-' and not ispos):\n isnegative = True\n i+=1\n</code></pre>\n\n<p>you can do</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>factor = -1 if s[i] == '-' else 1\n# Skip the sign character if necessary\nif s[i] == '-' or s[i] == '+':\n i += 1\n</code></pre>\n\n<h2>Reading the number</h2>\n\n<pre class=\"lang-py prettyprint-override\"><code>if(i<len(s) and not s[i].isnumeric() and s[i]!='+' and s[i]!='-'):\n return 0\nwhile(i<l):\n if s[i].isnumeric():\n res += s[i]\n else:\n break\n i+=1\n</code></pre>\n\n<ol>\n<li><p>If we have already parsed the sign, why accept another sign again? </p></li>\n<li><p>Be careful, <a href=\"https://www.programiz.com/python-programming/methods/string/isnumeric\" rel=\"nofollow noreferrer\"><code>isnumeric()</code></a> accepts things like <code>½</code>, which you probably don't want; use <code>isdigit()</code> instead.\nEDIT: As noted in the comments, <code>isdigit()</code> will accept things like \"¹\". So it's probably better to just do <code>s[i] in '0123456789'</code></p></li>\n<li><p>It's good practice (and helps avoid unexpected bugs) to declare variables the closest possible to where they are used. You declare <code>res = \"\"</code> at the beginning of your function, but haven't used it until now.</p></li>\n<li><p>The while and if can be condensed into a single, more compact loop:</p></li>\n</ol>\n\n<pre class=\"lang-py prettyprint-override\"><code>res = \"\"\nwhile i < l and s[i].isdigit():\n res += s[i]\n i += 1\n\n# You can check if an string is empty doing this:\nif not res:\n return 0\n</code></pre>\n\n<p>Arrived to this point, if the function hasn't returned, we know <code>res</code> contains a number. The way you handle the valid range, before applying the sign, is not very intuitive; it's better if you first apply the sign.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>x = factor * int(res)\nif x > (1 << 31):\n return (1<<31)\nelif x < -((1 << 31) - 1):\n return (1 << 31) - 1\nelse:\n return x\n</code></pre>\n\n<p>Or it might be even better to clamp your number using <code>min</code> and <code>max</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>return max(-(1 << 31) + 1, min(1 << 31, factor * int(res)))\n</code></pre>\n\n<h2>Final code</h2>\n\n<p>I have removed the special case of <code>l == 1</code> because it is already handled by the rest of the code. This is my final code (untested):</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def my_atoi(s: str) -> int:\n l = len(s)\n\n while i < l and s[i].isspace():\n i += 1\n\n if i == l:\n return 0\n\n factor = -1 if s[i] == '-' else 1\n # Skip the sign character if necessary\n if s[i] == '-' or s[i] == '+':\n i += 1\n\n res = \"\"\n while i < l and s[i].isdigit():\n res += s[i]\n i += 1\n\n if not res:\n return 0\n\n return max(-(1 << 31) + 1, min(1 << 31, factor * int(res)))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T08:54:33.223",
"Id": "438347",
"Score": "0",
"body": "If the requirement really is to make the code \"more compact\", then perhaps it's reasonable to throw PEP-8 out of the window. But it does make us ask, \"_why_ is that a goal??\"...."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T09:10:47.913",
"Id": "438350",
"Score": "0",
"body": "I thought he meant compact in less lines or less code. I cannot see any benefit of removing whitespaces when they make the code more readable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T09:15:51.157",
"Id": "438351",
"Score": "0",
"body": "Oh, absolutely - I was just having a little fun with the words!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T13:59:09.817",
"Id": "438386",
"Score": "0",
"body": "Thanks for your time :) Can I get any suggestion about analyzing and noting down all requirements for this kind of problems?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T14:01:40.723",
"Id": "438388",
"Score": "2",
"body": "Beware, though, even `isdigit` has its flaws. `\"¹\".isdigit()` returns `True`. The only way to be really sure I know of is to test `x in set(string.digits)` or similar."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T16:10:48.663",
"Id": "438404",
"Score": "0",
"body": "@Graipher Thanks for mentioning. Is it `\"1\".isdigit()`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T16:16:00.293",
"Id": "438406",
"Score": "1",
"body": "@taritgoswami No, it is a unicode symbol, a `1` that is raised, to be used as an exponent,. It still counts as a digit to `str,isdigit`, but `int(\"¹\")` fails with a `ValueError`. So using `str.isdigit` is not sufficient to reject values that are not parseable by `int`. Your only options are explicitly whitelisting only the ASCII digits (which is what `string.digits` contains), or by trying to parse a digit with `int` and skipping it if an exception is raised."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T17:10:34.320",
"Id": "438415",
"Score": "5",
"body": "Would you also suggest a variable other than \"l\", given how similar it looks to \"1\" (`if i == l`, etc)?"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T08:36:27.573",
"Id": "225706",
"ParentId": "225701",
"Score": "11"
}
},
{
"body": "<p>You can also use strip() to remove whitespaces in strings.\nstrip() will copy your string and remove both leading and trailing whitespaces.</p>\n\n<pre><code>foo_string = ' So much space for activities! '\n>>> foo_string.strip()\n'So much space for activities!'\n</code></pre>\n\n<p>You can also use this to only remove leading whitespaces or trailing, using lstrip() and rstrip(), respectively.</p>\n\n<p>You can then shorten your checks for valid operators by creating a string of valid operators and checking the first character.\nYou can then check for operators in it.</p>\n\n<pre><code>>>> test_string = '-354'\n>>> valid_operators = '+-'\n>>> test_string[0] in valid_operators\nTrue\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T14:48:35.007",
"Id": "225721",
"ParentId": "225701",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "225706",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T07:43:05.123",
"Id": "225701",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"strings"
],
"Title": "Can this code, to convert string to integer, be made more compact?"
}
|
225701
|
<p>I have to print the number of stars that increases on each line from the minimum number until it reaches the maximum number, and then decreases until it goes back to the minimum number. After printing out the lines of stars, it should also print the total number of stars printed.</p>
<p>I have tried using shell scripting and worked. But is there any other simplified and generic way to achieve this. Or to be precise any better code to achieve this</p>
<pre><code>echo "enter the mininum number of stars"
read min
echo "enter the maximum number of stars"
read max
for (( i=$min;i<=$max;i++))
do
for (( j=$max;j>=i;j-- ))
do
echo -n " "
done
for (( c=1;c<=i;c++ ))
do
echo -n " *"
sum=`expr $sum + 1`
done
echo ""
done
d_max=`expr $max - 1`
for (( i=$d_max;i>=$min;i--))
do
for (( j=i;j<=$d_max;j++ ))
do
if [ $j -eq $d_max ]
then
echo -n " "
fi
echo -n " "
done
for (( c=1;c<=i;c++ ))
do
echo -n " *"
sum=`expr $sum + 1`
done
echo ""
done
echo "Total No. of stars : " $sum
</code></pre>
<p>Output: </p>
<pre><code> *
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
</code></pre>
|
[] |
[
{
"body": "<p>Shell programs should start with a shebang, so that when executed, the OS can select the correct interpreter:</p>\n\n<pre><code>#!/bin/bash\n</code></pre>\n\n<p>With Bash, we can read prompted input using <code>read -p</code>:</p>\n\n<pre><code>read -p \"Enter the mininum number of stars: \" min\n</code></pre>\n\n<p>We should check that we have a valid positive integer before using <code>$min</code>.</p>\n\n<p>The same comments also apply to <code>$max</code>. For both variables, consider accepting arguments instead of prompting for interactive input.</p>\n\n<p>Prefer <code>printf</code> to <code>echo -n</code> - that's a good practice for portable scripting.</p>\n\n<p>Most of those <code>for</code> loops can be eliminated with suitable <code>printf</code> formatting. We can produce <code>n</code> stars with <code>printf '%.${n}s' '' | tr ' ' '*'</code>, and we can put that into a space that's <code>m</code> wide, with <code>printf '%${m}s' \"$(printf '%.$ns' '' | tr ' ' '*')\"</code>. If we did keep the loops, we don't need <code>$</code> for variable expansion within the arithmetic context <code>(( ))</code>.</p>\n\n<p>It seems strange to use arithmetic evaluation but also to invoke <code>expr</code> to increment <code>$sum</code> - it's more consistent to simply write <code>((++sum))</code>.</p>\n\n<p>The <code>echo</code> command with a single empty argument is equivalent to <code>echo</code> with no arguments, so no need to write <code>\"\"</code> there.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T13:58:56.387",
"Id": "225719",
"ParentId": "225708",
"Score": "4"
}
},
{
"body": "<p>My Bash complains about <code>sum=`expr $sum + 1`</code>, and it ain't pretty:</p>\n\n<blockquote>\n<pre><code> *expr: syntax error\n</code></pre>\n</blockquote>\n\n<p>What to make of that? Good ol' Bash won't treat you nicely if you don't treat it nicely! If I use <code>set -u</code>, things become clearer:</p>\n\n<blockquote>\n<pre><code> *script.sh: line 13: sum: unbound variable\n</code></pre>\n</blockquote>\n\n<p>Aha! Don't forget to initialize variables, <code>sum=0</code> in this case.</p>\n\n<hr>\n\n<p>Speaking of <code>sum=`...`</code>, use <code>sum=$(...)</code> in the future, it's better in every way.</p>\n\n<hr>\n\n<p>In arithmetic context you don't always need to use <code>$</code> for variables.\nInstead of this:</p>\n\n<blockquote>\n<pre><code>for (( i=$min;i<=$max;i++))\n</code></pre>\n</blockquote>\n\n<p>You could write:</p>\n\n<pre><code>for ((i = min; i <= max; i++))\n</code></pre>\n\n<p>Notice that I adjusted the spacing around operators, to follow common conventions of many languages.</p>\n\n<p>Also, I suggest to indent the loop body between <code>do</code> and <code>done</code> always, to make it easier to see the commands that are part of the loop. And it's common practice to indent by 4 spaces, not by 3.</p>\n\n<hr>\n\n<p>Instead of printing fragments of a line of text, it would be better to build the content of each line in a variable, and then <code>echo</code> the line. For example like this:</p>\n\n<pre><code>for ((i = min; i <= max; i++)); do\n line=\n for ((j = i; j <= max; j++)); do\n line+=' '\n done\n for ((j = 1; j <= i; j++)); do\n line+=' *'\n ((sum++))\n done\n echo \"$line\"\ndone\n</code></pre>\n\n<hr>\n\n<p>Btw, all this is a really silly use of Bash :-)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T18:45:17.000",
"Id": "225787",
"ParentId": "225708",
"Score": "3"
}
},
{
"body": "<p>First I will propose only some simple changes to make the code more readable.<br>\n1. add <code>#!/bin/bash</code> as first line then it is guaranteed that bash is used<br>\n2. use consistent indentation<br>\n3. when you do arithmetic evaluation you don't need the <code>$</code> character to evaluate the variables,<br>\n4. use consistent spacing to structure expressions, e.g. <code>(( j=max; j>=i; j-- ))</code><br>\n5. instead of <code>expr</code> use <code>$((...))</code><br>\n this is more readable but has <a href=\"https://unix.stackexchange.com/a/534631/17485\">other advantages</a>, too.<br>\n6. <code>echo \"\"</code> hase the same effect as <code>echo</code>, so use the latter, it is more clear<br>\n7. <code>echo \"Total No. of stars :\" $sum</code> is the same as <code>echo \"Total No. of stars : $sum\"</code>, but the latter is more clear, so use the latter.<br>\n8. Initialize variables. They may be set outside the script to a wrong value.</p>\n\n<pre><code>#!/bin/bash\necho \"enter the mininum number of stars\"\nread min\necho \"enter the maximum number of stars\"\nread max\nsum=0\nfor (( i=min; i<=max; i++ )); do\n for (( j=max; j>=i; j-- )); do\n echo -n \" \"\n done\n for (( c=1; c<=i; c++ )); do\n echo -n \" *\"\n sum=$(( sum+1 ))\n done\n echo\n done\nd_max=$(( max-1 ))\nfor (( i=d_max; i>=min; i-- )); do\n for (( j=i; j<=d_max; j++ )); do\n if (( j==d_max )); then\n echo -n \" \"\n fi\n echo -n \" \"\n done\n for (( c=1; c<=i; c++ )); do\n echo -n \" *\"\n sum=$(( sum+1 ))\n done\n echo \n done\necho \"Total No. of stars : $sum\"\n</code></pre>\n\n<p>This loop is executed d_max-i+1 mal, and d_max-i+2 times \" \" is printed.</p>\n\n<pre><code>for (( j=i; j<=d_max; j++ )); do\n if (( j==d_max )); then\n echo -n \" \"\n fi\n echo -n \" \"\n done\n</code></pre>\n\n<p>So use the simpler loop to print d_max-i+2 times \" \".</p>\n\n<pre><code>for (( j=i; j<=d_max+1; j++ )); do\n echo -n \" \"\n done\n</code></pre>\n\n<p>Instead of</p>\n\n<pre><code>for (( c=1; c<=i; c++ )); do\n echo -n \" *\"\n sum=$(( sum+1 ))\n done\n</code></pre>\n\n<p>use the simpler</p>\n\n<pre><code>for (( c=1; c<=i; c++ )); do\n echo -n \" *\"\n done\nsum=$(( sum+i ))\n</code></pre>\n\n<p>You have 4 times a similar block of code. Is it possible to replace it by a function? Yes!</p>\n\n<pre><code>print_from_to(){\n str=$1\n from=$2\n to=$3\n for (( t=$from; t<=$to; t++ )); do\n echo -n $str\n done\n} \n</code></pre>\n\n<p>So we have the following code now</p>\n\n<pre><code>#!/bin/bash\n\nprint_from_to(){\n str=$1\n from=$2\n to=$3\n for (( t=$from; t<=$to; t++ )); do\n echo -n $str\n done\n} \n\necho \"enter the mininum number of stars\"\nread min\necho \"enter the maximum number of stars\"\nread max\nsum=0\nfor (( i=min; i<=max; i++ )); do\n print_from_to \" \" $i $max\n print_from_to \" *\" 1 $i \n sum=$(( sum+i ))\n echo\n done\nd_max=$(( max-1 ))\nfor (( i=d_max; i>=min; i-- )); do\n print_from_to \" \" $i $((d_max+1))\n print_from_to \" *\" 1 $i \n sum=$(( sum+i ))\n echo \n done\necho \"Total No. of stars : $sum\"\n</code></pre>\n\n<p>All in all you do a lot of <code>echo</code> commands, I think </p>\n\n<p><span class=\"math-container\">$$2\\cdot max\\cdot (max-min+1).$$</span></p>\n\n<p>You can simplify your program. Note that for the first half of your lines the next line to be print can be constructed out of the previous line by removing <code>' '</code> from the beginning and adding <code>' *'</code> at the end.</p>\n\n<pre><code>line=${line# } # remove leading blank\nline=\"$line *\" # add blank and asterisk at the end\n</code></pre>\n\n<p>The second half of the lines can be constructed by adding a <code>' '</code> at the beginning and removing <code>' *'</code> from the end. </p>\n\n<pre><code>line=\" $line\" # add blank at the beginning\nline=${line% *} # remove trailing blank and asterisk \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T22:34:08.623",
"Id": "225801",
"ParentId": "225708",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T08:46:59.430",
"Id": "225708",
"Score": "5",
"Tags": [
"bash",
"ascii-art"
],
"Title": "To print asterisks based on inputs"
}
|
225708
|
<p>I have two methods in my code which are using the majority of the CPU time that convert between binary and hex strings and the reverse. I use a static lookup map to convert the individual characters but it's still slow given the amount of data I'm working with. </p>
<pre><code>public static String hexToBin(String s)
{
StringBuilder binaryString = new StringBuilder();
for(int i = 0; i < s.length(); i++)
{
// This string loop can be quite long sometimes > 3000 chars
binaryString.append(binMap.get(s.charAt(i)));
}
return binaryString.toString();
}
public static String binToHex(String s)
{
if (s.length() % 4 != 0)
{
s = Utils.leftPad4(s, (int)(4 * Math.ceil((double) s.length() / 4.0))); // Pad out any single bit values
}
StringBuilder hexString = new StringBuilder();
StringBuilder chars = new StringBuilder();
for (int i = 0; i < s.length(); i += 4)
{
chars.append(s.charAt(i));
chars.append(s.charAt(i + 1));
chars.append(s.charAt(i + 2));
chars.append(s.charAt(i + 3));
hexString.append(hexMap.get(chars.toString()));
chars.delete(0, chars.length());
}
return hexString.toString();
}
/* The lookup tables */
private static Map<Character, String> binMap = new HashMap<>();
private static Map<String, Character> hexMap = new HashMap<>();
public Types()
{
binMap.put('0', "0000"); binMap.put('1', "0001"); binMap.put('2', "0010");
binMap.put('3', "0011"); binMap.put('4', "0100"); binMap.put('5', "0101");
binMap.put('6', "0110"); binMap.put('7', "0111"); binMap.put('8', "1000");
binMap.put('9', "1001"); binMap.put('A', "1010"); binMap.put('B', "1011");
binMap.put('C', "1100"); binMap.put('D', "1101"); binMap.put('E', "1110");
binMap.put('F', "1111");
for (Character k : binMap.keySet())
{
hexMap.put(binMap.get(k), k);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T16:26:14.950",
"Id": "438407",
"Score": "0",
"body": "Hello, just to clarify my doubts before suggest what I would do to try to improve you code, you cannot use Integer class methods or you tried them and they are slower than your implementation?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T21:31:23.713",
"Id": "438441",
"Score": "0",
"body": "@dariosicily I'd prefer to keep things as strings the performance isn't *that* bad to warrant moving it to something else yet"
}
] |
[
{
"body": "<p>There are several things that hinder the performance of your code:</p>\n\n<ol>\n<li>You are using a map to convert from hex digits to binary strings. However map lookups are slow, compared to simple array indexing or a switch statement . What you need to do, instead of using a map, just use a switch statement, when converting from hex to bin:</li>\n</ol>\n\n<pre><code> switch (s.charAt(i))\n { \n case '0':\n binaryString.append(\"0000\");\n break;\n ...\n case 'F':\n binaryString.append(\"1111\");\n break;\n }\n</code></pre>\n\n<p>However, this approach probably will not be as efficent when converting from bin to hex.</p>\n\n<ol start=\"2\">\n<li><p>Because it is easy to calculate the length of a bin string from the length of a hex string, you can easily preallocate StringBuilder's with the calculated size. This will save you time, because the will be no memory reallocations.</p></li>\n<li><p>If you code is not multithreaded, you could preallocate the StringBuilder's themselves and store them in some private fields of your class. This way you'd avoid spending time for unnecessary creation of the object, that would almost immediately be destroyed.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T05:27:36.837",
"Id": "438457",
"Score": "0",
"body": "That third bullet has no measurable effect on performance. It is better to not go for ugly hacks in such cases."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T22:19:56.043",
"Id": "225744",
"ParentId": "225716",
"Score": "4"
}
},
{
"body": "<p>Ilkhd made good points about performance within the context of the task. I'll concentrate on a couple of generic issues.</p>\n\n<p><strong>Naming</strong></p>\n\n<pre><code>public static String hexToBin(String s) \npublic static String binToHex(String s)\n</code></pre>\n\n<p>The String parameter in the above method signatures is a hexadecimal string or binary string so they should be named <code>hexString</code> and <code>binaryString</code>, like is done with the local variables.</p>\n\n<pre><code>Utils.leftPad4(String, int)\n</code></pre>\n\n<p>The code for this mehtod is missing, but I assume it left-pads the String with the number of zeroes given in the int parameter. The 4 in the name seems unnecessary and confusing. The method doesn't seem to be very reusable either. It should be made into a generic left pad method: <code>Utils.leftPad(String target, char padChar, int count)</code>. Although I'm fairly sure such a method already exists in one of the common utility libraries (Apache Commons, etc).</p>\n\n<pre><code>private static Map<Character, String> binMap = new HashMap<>();\nprivate static Map<String, Character> hexMap = new HashMap<>();\n</code></pre>\n\n<p>If possible, the name of a map should describe the key and the value. These should thus be <code>hexToBinMap</code> and <code>binToHexMap</code>. They even managed to confuse me, since the first one does not map binary to anything. It maps hexadecimal characters to binary, so the naming was completely backwards. They have also been documented as lookup tables when they are actually lookup maps.</p>\n\n<p><strong>Performance</strong></p>\n\n<pre><code>StringBuilder chars = new StringBuilder();\n...\nhexString.append(hexMap.get(chars.toString()));\n</code></pre>\n\n<p>This fills a StringBuilder with consecutive characters from a String and immediately converts it to another String. It should use <a href=\"https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int,%20int)\" rel=\"nofollow noreferrer\">String.substring(int startIndex, int endIndex)</a> instead. This removes the unnecessary char array allocation done in StringBuilder.toString.</p>\n\n<p>If you're concerned about performance, you should use an IDE, like Eclipse or Idea. They allows you to easily dig into the code in the JRE, like the StringBuilder.toString and examine yourself what it does. Knowing what the libraries you use is essential to performance optimization.</p>\n\n<p><strong>Error checking</strong></p>\n\n<pre><code>binaryString.append(binMap.get(s.charAt(i)));\n</code></pre>\n\n<p>If the input string isn't a valid hexadecimal string, this will just append the string \"null\" to the binary string. There needs to be a check that the value returned from <code>binMap.get(...)</code> (or hexToBinMap as it should be) is not null. There is also no checking or documentation for upper vs lower case characters.</p>\n\n<p><strong>Finally</strong></p>\n\n<pre><code>public static String hexToBin(String s) \n{ \n StringBuilder binaryString = new StringBuilder();\n</code></pre>\n\n<p>Whenever a piece of code declares a variable that is not intended to be changed, it should be declared final. This applies to method parameters, local variables and class members variables. This reduces the cognitive load of the maintainer as it removes the need to figure out if the variable is ever manipulated. The code above should thus become: </p>\n\n<pre><code>public static String hexToBin(final String s) \n{ \n final StringBuilder binaryString = new StringBuilder();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T05:51:38.833",
"Id": "225749",
"ParentId": "225716",
"Score": "3"
}
},
{
"body": "<p>Ok, here my suggestions about your code, I noticed that you used <code>s.length()</code> in your code (two loops and leftpad function), better to store it in a variable and use this variable in your code rewriting loops and leftpad function.</p>\n\n<pre><code>int length = s.length()\n</code></pre>\n\n<p>Instead of using <code>s.charAt(i)</code> inside the loops, you can use the String method <code>toCharArray()</code> and memorize the String s into a char array, iterating over it inside the loops. You can rewrite the first loop in this way and the second one with some modifies to the code above avoid consecutive calls of the s <code>charAt(i)</code> method:</p>\n\n<pre><code>char[] arr =s.toCharArray();\nint length = s.length();\nfor (int i = 0; i < length; ++i) {\n binaryString.append(binMap.get(arr[i]));\n}\n</code></pre>\n\n<p>My concern is about the second parameter you are passing to it because you are doing a division between double numbers and after you cast the result to int, if you already know the result of <code>s.length() % 4</code> you know that you have to pad your string with <code>4 - s.length() % 4</code> 0 chars if I correctly interpreted the method you posted, so you would avoid the double division and the ceil method too.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T08:37:32.337",
"Id": "225753",
"ParentId": "225716",
"Score": "1"
}
},
{
"body": "<blockquote>\n<pre><code>public static String hexToBin(String s) \n{ \n StringBuilder binaryString = new StringBuilder();\n</code></pre>\n</blockquote>\n\n<p>You can improve efficiency here by telling the <code>StringBuilder</code> how long it will need to be. </p>\n\n<pre><code>public static final int BINARY_SIZE_OF_HEX = 4;\n\npublic static String hexToBin(String s) \n{ \n StringBuilder binaryString = new StringBuilder(BINARY_SIZE_OF_HEX * s.length());\n</code></pre>\n\n<p>Without this, it will allocate memory for a relatively small string, e.g. sixteen characters. Then it will reallocate memory for progressively longer strings. If the block of memory isn't long enough for expansion, it will copy the whole string to a new block of memory. </p>\n\n<p>This way, it will allocate memory once and just enter the binary representation of the string thereafter. </p>\n\n<p>This works because the translation between a hexadecimal representation and binary is straightforward. There are exactly four binary digits to every hexadecimal digit with the exception of the first. That may range from one to four digits. But your original version can be off by up to fifteen characters in length. Being off at most three is an improvement. </p>\n\n<p>I also replaced the magic number 4 with a descriptively named constant. </p>\n\n<blockquote>\n<pre><code> s = Utils.leftPad4(s, (int)(4 * Math.ceil((double) s.length() / 4.0))); // Pad out any single bit values\n</code></pre>\n</blockquote>\n\n<p>You could write this more simply as </p>\n\n<pre><code> int distanceFromBoundary = s.length() % BINARY_SIZE_OF_HEX;\n if (distanceFromBoundary != 0)\n {\n // Pad out any single bit values\n s = Utils.leftPad4(s, s.length() + BINARY_SIZE_OF_HEX - distanceFromBoundary);\n</code></pre>\n\n<p>This saves a conversion to <code>double</code>, a floating point division, a ceiling operation, and a conversion to <code>int</code> at the cost of an integer addition, a subtraction, and a variable declaration. The variable will probably get compiled out into just a register use. </p>\n\n<p>You also might consider if it would be better to handle the first digit separately rather than pad. Padding probably copies the whole string. But you don't need another copy of the string. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T15:01:56.363",
"Id": "225767",
"ParentId": "225716",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T12:33:07.760",
"Id": "225716",
"Score": "5",
"Tags": [
"java",
"performance",
"number-systems"
],
"Title": "Java code to convert between hex & binary strings"
}
|
225716
|
<p>The problem of 3sum is described as:</p>
<blockquote>
<p>Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.</p>
</blockquote>
<p>Here is my code, am I right to say its complexity is O(N<sup>2</sup>), and how can I further optimize my code? Here I am using HashTable:</p>
<pre><code>class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
dct = {}
trip = {}
triplet = []
nums_len = len(nums)
for i in range(nums_len - 1):
for j in range(i + 1, nums_len):
key = nums[i] + nums[j]
if key in dct:
if (i in dct[key]):
continue
dct[key] = dct[key] + [i, j] # If exists, append more in a bucket
else:
dct[key] = [i, j]
for k in range(nums_len):
supplement = -1*nums[k] # nums[k] = - (nums[i] + num[j])
if supplement in dct:
entry = dct[supplement] #look on the dict
entry_len = len(entry)
entry_num = entry_len//2
for m in range(entry_num):
pair = [entry[m*2], entry[m*2+1]]
if (k not in pair):
candidate = [nums[entry[m*2]], nums[entry[m*2+1]], nums[k]]
candidate.sort()
key = str(candidate[0]) + str(candidate[1]) + str(candidate[2])
if (key not in trip):
trip[key] = True
triplet.append(candidate)
return triplet
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T13:15:05.137",
"Id": "438380",
"Score": "2",
"body": "Welcome to Code Review. Please add a language tag."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T13:25:34.570",
"Id": "438381",
"Score": "0",
"body": "You might get some inspiration from https://codereview.stackexchange.com/q/213328/35991."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T13:53:24.617",
"Id": "438384",
"Score": "1",
"body": "It is very difficult to optimize when we don't know what language the code is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T17:36:45.983",
"Id": "438421",
"Score": "0",
"body": "Is `nums` a unique list?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T01:41:30.857",
"Id": "438450",
"Score": "0",
"body": "I am so sorry, the code is Python2, and nums is not a unique list. Should I write some more comments in code to clarify my idea?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T15:53:18.457",
"Id": "438748",
"Score": "0",
"body": "Someone helps me out? I think its O(N^2) but this code can not pass all test cases on leetcode"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T12:54:14.610",
"Id": "225717",
"Score": "2",
"Tags": [
"python",
"programming-challenge",
"hash-map",
"k-sum"
],
"Title": "Solution to 3Sum problem on Leetcode using HashTable"
}
|
225717
|
<p>I have a query I am writing where I want output if a person has some service provided, then I want all the services they had provided after that and I don't want the individual returned if that is the only service they had (the criteria service)</p>
<p>I have some example data:
<a href="https://i.stack.imgur.com/qBMKx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qBMKx.png" alt="sample_data"></a></p>
<p>In this instance above I would not want the last row.</p>
<p>The code I have, I feel is verbose at best. I am confident it works but I think it could be written better.</p>
<p>This will get some sample data</p>
<pre class="lang-sql prettyprint-override"><code>declare @bmh_plm_ptacct_v as table (
med_rec_no varchar(10)
, ptno_num varchar(10)
, adm_date date
, dsch_date date
, hosp_svc varchar(5)
)
insert into @bmh_plm_ptacct_v
values('123456','123456748','2017-12-18','2018-01-12','PSY'),
('123456','123456789','2018-01-17','2018-01-18','EME'),
('123456','123456889','2018-01-19','2018-01-21','EME'),
('123456','123478978','2018-01-25','2018-01-25','EME'),
('123456','123457979','2018-05-21','2018-05-21','EME'),
('123456','123458988','2018-06-03','2018-06-04','EME'),
('123456','123458989','2018-07-27','2018-08-14','PSY'),
('123456','123458990','2018-09-23','2018-09-24','EME'),
('123456','123459999','2018-09-25','2018-09-30','PSY')
declare @vReadmits as table (
[index] varchar(10)
, interim int
, [readmit] varchar(10)
)
insert into @vReadmits
values('123458990','25','123459999')
declare @hosp_svc_dim_v as table (
hosp_svc varchar(50)
, hosp_svc_name varchar(100)
, orgz_cd varchar(10)
)
insert into @hosp_svc_dim_v
values('PSY','Pyschiatry','s0x0'),
('EME','Emergency Department','s0x0')
</code></pre>
<pre class="lang-sql prettyprint-override"><code>SELECT Med_Rec_No
, PtNo_Num
, Adm_Date
, Dsch_Date
, hosp_svc
, CASE
WHEN B.READMIT IS NULL
THEN 'No'
ELSE 'Yes'
END AS [Readmit Status]
, [Event_Num] = ROW_NUMBER() over(partition by med_rec_no order by ADM_date)
, [PSY_Flag] = CASE WHEN hosp_svc = 'PSY' THEN '1' ELSE '0' END
INTO #TEMPA
FROM smsdss.bmh_plm_ptacct_v AS A
LEFT OUTER JOIN smsdss.vReadmits AS B
ON A.PtNo_Num = b.[INDEX]
AND B.INTERIM < 31
WHERE Dsch_Date >= '01-01-2018'
AND dsch_date < '12-31-2018'
ORDER BY Med_Rec_No, A.Adm_Date
;
SELECT A.*
INTO #TEMPB
FROM #TEMPA AS A
WHERE A.hosp_svc = 'PSY'
;
SELECT B.*
INTO #TEMPC
FROM #TEMPA AS B
WHERE B.hosp_svc != 'PSY'
AND B.Med_Rec_No IN (
SELECT DISTINCT Med_Rec_No
FROM #TEMPB
)
;
SELECT Med_Rec_No
, PtNo_Num
, Adm_Date
, Dsch_Date
, hosp_svc
, [Readmit Status]
, Event_Num
, PSY_Flag
, [Keep_Flag] = ROW_NUMBER() OVER(PARTITION BY MED_REC_NO ORDER BY ADM_DATE)
INTO #TEMPD
FROM (
SELECT B.*
FROM #TEMPB AS B
UNION ALL
SELECT C.*
FROM #TEMPC AS C
WHERE C.Med_Rec_No IN (
SELECT ZZZ.Med_Rec_No
FROM #TEMPB AS ZZZ
WHERE ZZZ.Med_Rec_No = C.Med_Rec_No
AND C.Event_Num > ZZZ.Event_Num
)
) AS A
ORDER BY MED_REC_NO, Event_Num
;
SELECT A.Med_Rec_No
, A.PtNo_Num
, CAST(A.ADM_DATE AS DATE) AS [Adm_Date]
, CAST(A.Dsch_Date AS DATE) AS [Dsch_Date]
, A.hosp_svc
, HS.hosp_svc_name
, A.[Readmit Status]
, A.Event_Num
, A.Keep_Flag
FROM #TEMPD AS A
LEFT OUTER JOIN SMSDSS.hosp_svc_dim_v AS HS
ON A.hosp_svc = HS.hosp_svc
AND HS.orgz_cd = 'S0X0'
WHERE A.Med_Rec_No IN (
SELECT DISTINCT ZZZ.MED_REC_NO
FROM #TEMPD AS ZZZ
WHERE Keep_Flag > 1
)
DROP TABLE #TEMPA;
DROP TABLE #TEMPB;
DROP TABLE #TEMPC;
DROP TABLE #TEMPD;
</code></pre>
|
[] |
[
{
"body": "<h2>Review</h2>\n\n<p>Your temporary table names don't say much about what they present. This makes it hard to figure out what they mean. Consider using better, more meaningful names.</p>\n\n<blockquote>\n<pre><code>DROP TABLE #TEMPA;\nDROP TABLE #TEMPB;\nDROP TABLE #TEMPC;\nDROP TABLE #TEMPD;\n</code></pre>\n</blockquote>\n\n<p>It gets worse by aliasing these temporary tables with different letters:</p>\n\n<blockquote>\n<pre><code>FROM #TEMPA AS A -- Fair enough\n\nFROM #TEMPA AS B -- Mamma mia!\n</code></pre>\n</blockquote>\n\n<p>There is only a need for an <code>order by</code> in the resulting query and the analytical functions (<code>row over</code>), not in the temporary tables.</p>\n\n<p>There is no need for the temporary tables, you could use CTE's instead.</p>\n\n<hr>\n\n<h2>Refactored Query</h2>\n\n<p><a href=\"https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=1596ba88293e9e9855b216abd2b0e109\" rel=\"nofollow noreferrer\">Fiddle containing OP + Refactored Query</a></p>\n\n<p><em>This only refactors the query for readability. I am sure a more compact and optimized query could be found.</em></p>\n\n<pre><code>with ACC as (\n SELECT Med_Rec_No\n , PtNo_Num\n , Adm_Date\n , Dsch_Date\n , hosp_svc\n , CASE WHEN B.READMIT IS NULL THEN 'No' ELSE 'Yes' END AS [Readmit Status]\n , [Event_Num] = ROW_NUMBER() over(partition by med_rec_no order by ADM_date)\n , [PSY_Flag] = CASE WHEN hosp_svc = 'PSY' THEN '1' ELSE '0' END\n FROM bmh_plm_ptacct_v AS A\n LEFT OUTER JOIN vReadmits AS B\n ON A.PtNo_Num = b.[INDEX] AND B.INTERIM < 31\n WHERE Dsch_Date >= '01-01-2018'\n AND dsch_date < '12-31-2018'\n)\n, EMERG as (\n SELECT ACC.* FROM ACC WHERE hosp_svc = 'PSY'\n)\n, PSY as (\n SELECT ACC.*\n FROM ACC\n WHERE hosp_svc != 'PSY'\n AND Med_Rec_No IN (SELECT DISTINCT Med_Rec_No FROM EMERG)\n)\n, ACC_REL as (\n SELECT Med_Rec_No\n , PtNo_Num\n , Adm_Date\n , Dsch_Date\n , hosp_svc\n , [Readmit Status]\n , Event_Num\n , PSY_Flag\n , [Keep_Flag] = ROW_NUMBER() OVER(PARTITION BY MED_REC_NO ORDER BY ADM_DATE)\n FROM (\n SELECT * FROM EMERG\n UNION ALL\n SELECT * FROM PSY\n WHERE PSY.Med_Rec_No IN (\n SELECT e.Med_Rec_No\n FROM EMERG AS e\n WHERE e.Med_Rec_No = PSY.Med_Rec_No\n AND PSY.Event_Num > e.Event_Num\n )\n ) AS A\n)\nSELECT A.Med_Rec_No\n , A.PtNo_Num\n , CAST(A.ADM_DATE AS DATE) AS [Adm_Date]\n , CAST(A.Dsch_Date AS DATE) AS [Dsch_Date]\n , A.hosp_svc\n , HS.hosp_svc_name\n , A.[Readmit Status]\n , A.Event_Num\n , A.Keep_Flag\nFROM ACC_REL AS A\nLEFT OUTER JOIN hosp_svc_dim_v AS HS\nON A.hosp_svc = HS.hosp_svc AND HS.orgz_cd = 'S0X0'\nWHERE A.Med_Rec_No IN (\n SELECT DISTINCT rel.MED_REC_NO\n FROM ACC_REL AS rel\n WHERE Keep_Flag > 1\n)\nORDER BY Med_Rec_No, Adm_Date\n;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T18:24:04.467",
"Id": "225735",
"ParentId": "225722",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "225735",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T15:18:21.193",
"Id": "225722",
"Score": "1",
"Tags": [
"sql",
"sql-server",
"t-sql"
],
"Title": "T-SQL Getting Sequential events with first even criteria"
}
|
225722
|
<p>I'm learning Rust at the moment, I've read <a href="https://doc.rust-lang.org/book/" rel="nofollow noreferrer">the book</a> and been just playing around with the language. I wrote this simple <a href="https://en.wikipedia.org/wiki/Brainfuck" rel="nofollow noreferrer">Brainfuck</a> interpreter, because I think that it's always a fun exercise. The interpreter uses a tape size of 30000 and cell size of one byte. Decrementing a cell's value under 0 will wrap it to 255 and vice versa.</p>
<p>The program consists of three files: <code>main.rs</code>, <code>tape.rs</code>, and <code>errors.rs</code> and has no dependencies outside the standard library. It expects a relative path to a Brainfuck source file as a command line argument, and can be run with the command (I'm using Rust 1.41.0):</p>
<pre><code>$ cargo run --release bf/mandelbrot.bf
</code></pre>
<p>Would be great to get some feedback on this. <strong>Especially looking for ways to write some parts more idiomatically, using some of Rust's nicer features I've missed.</strong></p>
<p><code>main.rs</code>:</p>
<pre class="lang-rust prettyprint-override"><code>use std::env;
use std::error::Error;
use std::fs;
use std::io;
use std::process;
use crate::errors::{BraceError, TapeError};
use crate::tape::Tape;
mod errors;
mod tape;
const TAPE_LENGTH: i32 = 30000;
fn main() -> Result<(), Box<dyn Error>> {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
eprintln!(
"{}{}",
"Expected a brainfuck source file as a command line argument.\n",
"Terminating the program."
);
process::exit(1);
}
let tokens = read_file_to_tokens(&args[1])?;
let tokens = remove_comments(tokens);
let tokens = pair_braces(tokens)?;
interpret(tokens)?;
Ok(())
}
#[derive(PartialEq)]
enum Token {
Add,
Sub,
Right,
Left,
Dot,
Comma,
LeftBrace(Option<usize>),
RightBrace(Option<usize>),
Comment,
}
/// This will ignore all the comment chars in the file.
fn read_file_to_tokens(file_path: &str) -> Result<Vec<Token>, io::Error> {
Ok(fs::read_to_string(file_path)?
.chars()
.map(|c| match c {
'+' => Token::Add,
'-' => Token::Sub,
'>' => Token::Right,
'<' => Token::Left,
'.' => Token::Dot,
',' => Token::Comma,
'[' => Token::LeftBrace(None),
']' => Token::RightBrace(None),
_ => Token::Comment,
})
.collect())
}
/// Remove all the comment chars from the tokens, this removes all chars
/// which have no meaning in brainfuck, so everything except: `+-<>.,[]`.
fn remove_comments(tokens: Vec<Token>) -> Vec<Token> {
tokens
.into_iter()
.filter(|t| t != &Token::Comment)
.collect()
}
/// Pair the braces into the LeftBrace and RightBrace tokens.
/// The index of the matching brace will be inside the Some variant of the token value.
fn pair_braces(mut tokens: Vec<Token>) -> Result<Vec<Token>, BraceError> {
// Form all the (i, j) index pairs that correspond to a matching brace pair.
let mut pairs = Vec::new();
for (i, tok) in tokens.iter().enumerate() {
if *tok == Token::LeftBrace(None) {
let mut j = i;
let mut brace_count = 1;
while tokens[j] != Token::RightBrace(None) || brace_count != 0 {
if j == tokens.len() - 1 {
return Err(BraceError { brace_index: i });
}
j += 1;
match tokens[j] {
Token::LeftBrace(None) => brace_count += 1,
Token::RightBrace(None) => brace_count -= 1,
_ => (),
}
}
pairs.push((i, j));
}
}
// Do the actual pairing of the braces in the tokens.
for (i, j) in pairs {
tokens[i] = Token::LeftBrace(Some(j));
tokens[j] = Token::RightBrace(Some(i));
}
// Final check that all the braces got paired correctly.
// This will return an error when for example the source had
// only a single right brace in it.
for (i, tok) in tokens.iter().enumerate() {
if *tok == Token::LeftBrace(None) || *tok == Token::RightBrace(None) {
return Err(BraceError { brace_index: i });
}
}
Ok(tokens)
}
/// The actual interpreter. Goes through the source char by char and
/// acts according to Brainfuck's rules.
fn interpret(tokens: Vec<Token>) -> Result<(), TapeError> {
let mut tape = Tape::new(TAPE_LENGTH);
let mut i = 0usize;
while i < tokens.len() {
match tokens[i] {
Token::Add => tape.incr_cell(),
Token::Sub => tape.decr_cell(),
Token::Right => tape.incr_head()?,
Token::Left => tape.decr_head()?,
Token::Dot => tape.print_current(),
Token::Comma => tape.read_to_current(),
Token::LeftBrace(Some(n)) if tape.get_current() == 0 => i = n,
Token::RightBrace(Some(n)) if tape.get_current() != 0 => i = n,
_ => (),
}
i += 1;
}
Ok(())
}
</code></pre>
<p><code>tape.rs</code>:</p>
<pre class="lang-rust prettyprint-override"><code>use std::fmt::{self, Display, Formatter};
use std::io::{self, Read, Write};
use std::num::Wrapping;
use crate::errors::TapeError;
/// The memory tape of the program.
pub struct Tape {
size: i32,
head: i32,
tape: Vec<Wrapping<u8>>,
}
impl Tape {
pub fn new(size: i32) -> Tape {
Tape {
size,
head: 0,
tape: vec![Wrapping(0u8); size as usize],
}
}
pub fn incr_cell(&mut self) {
self.tape[self.head as usize] += Wrapping(1);
}
pub fn decr_cell(&mut self) {
self.tape[self.head as usize] -= Wrapping(1);
}
pub fn incr_head(&mut self) -> Result<(), TapeError> {
self.head += 1;
self.err_if_not_in_bounds()
}
pub fn decr_head(&mut self) -> Result<(), TapeError> {
self.head -= 1;
self.err_if_not_in_bounds()
}
pub fn print_current(&self) {
print!("{}", self.tape[self.head as usize].0 as char);
io::stdout().flush().unwrap();
}
pub fn read_to_current(&mut self) {
self.tape[self.head as usize].0 = io::stdin()
.bytes()
.next()
.and_then(|result| result.ok())
.map(|byte| byte as u8)
.unwrap();
}
pub fn get_current(&self) -> u8 {
self.tape[self.head as usize].0
}
fn err_if_not_in_bounds(&self) -> Result<(), TapeError> {
if self.head < 0 || self.head >= self.size {
Err(TapeError {
tape_index: self.head,
})
} else {
Ok(())
}
}
}
impl Display for Tape {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let sample = 40;
let mut s = String::with_capacity(4 * sample);
for cell in self.tape.iter().take(sample) {
s.push_str(format!("[{}] ", cell.0).as_str());
}
write!(f, "{}", s)
}
}
</code></pre>
<p><code>errors.rs</code>:</p>
<pre class="lang-rust prettyprint-override"><code>use std::error::Error;
use std::fmt::{self, Debug, Display, Formatter};
pub struct BraceError {
pub brace_index: usize,
}
impl Error for BraceError {}
impl Display for BraceError {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(
f,
"Mismatched braces in the source file, no pair for the brace at position: {}",
self.brace_index + 1
)
}
}
impl Debug for BraceError {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
return Display::fmt(&self, f);
}
}
pub struct TapeError {
pub tape_index: i32,
}
impl Error for TapeError {}
impl Display for TapeError {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(
f,
"Tape head over tape bounds at index: {}",
self.tape_index
)
}
}
impl Debug for TapeError {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
return Display::fmt(&self, f);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>The main thing I notice is that <code>pair_braces</code> looks clumsy. For every left brace, it goes off to find the matching right brace, tracking nested braces along the way. This is very inefficient (N^2 if your input consists only of perfectly nested braces, e.g. <code>[[[[[[]]]]]]</code>). It also simply doesn't feel right.</p>\n\n<p>A better way is to keep a stack of left brace positions. As you go through the tokens, you push the position for each left brace on the stack. For each right brace, you pop the most recent position off the stack and add it, together with the current position, to the pair vector. If the stack is empty when you try to pop, you have an unmatched right brace. If the stack is not empty when you're done, you have an unmatched left brace.</p>\n\n<p>For code organization, my personal preference would be to not have an errors module, but instead put the errors with the module they belong to: TapeError goes into tape.rs, BraceError goes into parser.rs (where you also put the other tokenizer/parser functions).</p>\n\n<p>Another thing: if you're just going to discard comment tokens, why have them in the first place? You could just skip them in the initial step.</p>\n\n<p>I really like that you're using the <code>Wrapping</code> wrapper.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-16T11:13:24.880",
"Id": "237369",
"ParentId": "225727",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T16:03:19.847",
"Id": "225727",
"Score": "7",
"Tags": [
"rust",
"interpreter",
"brainfuck"
],
"Title": "Brainfuck interpreter utilizing idiomatic Rust"
}
|
225727
|
<p>This code aims to make very easy to train new models in SageMaker and quickly decide whether a new feature should be introduced in our model or not, getting metrics (recall, accuracy and so on) for a model with and without certain variable, or simply make quick experiments. My specific case is a fraud detection model. </p>
<p>Almost half of the code are docstrings (the def of the functions needs one level more of indentation and the content a level less, I know, but it has been pasted this way and I don't know a way to easily change it. In my notebook it is correct anyway):</p>
<pre><code>import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction import FeatureHasher
import boto3
import sagemaker
from sagemaker.amazon.amazon_estimator import get_image_uri
from sagemaker import get_execution_role
from sagemaker.predictor import csv_serializer, json_deserializer
from io import StringIO
import warnings
import logging
import gc
class HoldOutSample:
def __init__(self):
logging.basicConfig(level=logging.DEBUG)
def load_data(self, data_file_name, bucket='sagemaker', prefix = 'tests', **kwargs):
"""This function load the data that will be used in the rest of the script
Args:
data_file_name (str): name of the file with the data.
bucket (str): the bucket in which is located the data and where will be stored the model and so
on (in following functions). It should not be changed unless a good reason,
for the correct order maintainability.
prefix (str): folder in the bucket that has the data. Same as above, it is recommended to keep the
default value.
Returns:
raw_data (dataframe): the loaded data as dataframe. It includes label and features
"""
self.bucket = bucket
self.prefix = prefix
self.sagemaker_session = sagemaker.Session()
self.role = get_execution_role()
data_location = f's3://{self.bucket}/{self.prefix}/{data_file_name}'
raw_data = pd.read_csv(data_location)
if raw_data.shape[0]<300000: #providing the rows of the dataset are less than 300k, it shows a warning
warnings.warn("Your dataset seems small. Maybe you should consider to use CrossValidation notebook instead.")
logging.info('Data loaded with success')
return raw_data
def preprocess(self, raw_data, feature_hashing_big=10, feature_hashing_small=3,
columns_to_transform_big=['variable_1',
'variable_2'],
columns_to_transform_small=['a',
'b',
'c'],
features_to_drop_after_transformation=['variable_1',
'b',
'c']
,**kwargs):
"""It will split the data between features(dropping unnecesary variables that are contained in the raw_data)
and label (fraud or no fraud), make the feature hashing for the columns needed, fill the nulls
with 0 for security reasons and format it as float32 for XGBoost compatibility.
Args:
raw_data(DataFrame): data to be processed.
feature_hashing_big (int): in how many features will be splitted the variables that are going to
be featured hashed. The big is because the variable has a big variability and hence there are
needed several hashed features to catch all the possible values of the original variable.
feature_hashing_small (int): same as above but for the small variability variables (i.e variables
that just can take 5 o 6 different values).
columns_to_transform_big (list): variables that will be feature hashed with the big number.
columns_to_transform_small (list): variables that will be transformed into the small number.
features_to_drop_after_transformation (list): those original variables which are going to be
dropped after the transformation, for avoiding duplicities.
Returns:
processed_data (DataFrame): data with all the transformations needed to create the XGBoost model
"""
features = raw_data.drop(['order_id','domain','product_id','date'], axis=1)
label = features.pop('fraud')
hasher_big = FeatureHasher(n_features=feature_hashing_big, input_type="string")
hasher_small = FeatureHasher(n_features=feature_hashing_small, input_type="string")
d = {}
columns_to_transform_10 = columns_to_transform_big
columns_to_transform_3 = columns_to_transform_small
for column in columns_to_transform_big:
d[column] = pd.DataFrame(hasher_big.transform(features[column].astype(str)).toarray())
d[column].columns = [column + f'_{i}' for i in range(feature_hashing_big)]
for column in columns_to_transform_small:
d[column] = pd.DataFrame(hasher_small.transform(features[column].astype(str)).toarray())
d[column].columns = [column + f'_{i}' for i in range(feature_hashing_small)]
transformed_features = pd.concat(d,axis=1)
transformed_features.columns = transformed_features.columns.droplevel(0)
features = features.drop(features_to_drop_after_transformation, axis=1)
concatenated_data = pd.concat([label,features,transformed_features], axis=1)
#The format float32 is necessary for XGBoost models
processed_data = concatenated_data.fillna(0).astype('float32')
logging.info('Data preprocessed correctly')
return processed_data
def split_data(self, data, test_size=0.2, validation_size = 0.25, **kwargs):
"""First, the data will be splitted in two datasets: train/validation and test. After, the first one will
be splitted in train and validation.
Args:
data(DataFrame): self-explanatory
test_size (float): percentage of data that is kept for the second dataset that is returned.
"""
self.train_and_validation_data, self.test_data = train_test_split(data, test_size = test_size)
self.train_data, self.validation_data = train_test_split(self.train_and_validation_data,
test_size = validation_size)
def save_data_in_S3_for_XGB(self, train_route='train.csv', validation_route='validation.csv', **kwargs):
"""XGBoost takes the data from S3 in a special way, and this function will save the train and validation
in that way in S3.
Args:
train_route (str): name of the train dataset csv file that will be saved in S3.
validation_route (str): same as above but for validation dataset.
"""
csv_buffer = StringIO()
self.train_data.to_csv(csv_buffer, header = False, index = False)
s3_resource = boto3.resource('s3')
s3_resource.Object(self.bucket, f'{self.prefix}/{train_route}').put(Body=csv_buffer.getvalue())
csv_buffer = StringIO()
self.validation_data.to_csv(csv_buffer, header = False, index = False)
s3_resource.Object(self.bucket, f'{self.prefix}/{validation_route}').put(Body=csv_buffer.getvalue())
self.xgb_s3_input_validation = sagemaker.s3_input(s3_data=f's3://{self.bucket}/{self.prefix}/validation.csv',
content_type = 'csv')
self.container = get_image_uri(boto3.Session().region_name, 'xgboost')
self.xgb_s3_input_train = sagemaker.s3_input(s3_data=f's3://{self.bucket}/{self.prefix}/train.csv',
content_type = 'csv')
def train(self, objective='binary:logistic', num_round=400, eval_metric='error@0.1', scale_pos_weight=10,
train_instance_count=1, train_instance_type='ml.m4.2xlarge', output_path='outputs', **kwargs):
"""This function makes the three steeps necessaries for training the model: creating the estimator,
set hyperparameters and fit the model.
Args:
objective (str): the default value is the one needed for binary classification. Don't change.
num_round (int): number of rounds (iterations) for the training of the model. It has been proved
that somewhere between 300 and 450 rounds (depending on the size of the dataset) the algorithm does
not get bette, but until that cipher is reached, there are sligthly improvements.
eval_metric (str): in each round, the model is trained using the train dataset and evaluated against
the validation dataset. This is the metric that takes place in the process.
scale_pos_weight (int): this is useful for umbalanced datasets (as our) and gives the less frequent label
an extra importance. It has been proven that using the recommended calculation for this gives bad results.
train_instance_count (str): Number of instances that will execute the train job.
train_instance_type (str): the type of the instance that will execute the train job. The more powerful
it is, the more it costs and the less it takes to train the model. The most powerful ones (x24large)
are not totally worth it because the time is not exactly the half of the previous ones (x12large) so we
get charged for more money. Anyway that difference is not that much and if we need it to be trained fast
is a total feasible option.
output_path (str): folder inside the bucket and prefix in where the model artifact will be saved.
"""
self.xgb = sagemaker.estimator.Estimator(self.container,
self.role,
train_instance_count = train_instance_count,
train_instance_type = train_instance_type,
output_path = f's3://{self.bucket}/{self.prefix}/{output_path}',
sagemaker_session=sagemaker.Session())
self.xgb.set_hyperparameters(objective = objective,
num_round = num_round,
eval_metric = eval_metric,
scale_pos_weight = scale_pos_weight
)
self.xgb.fit({'train': self.xgb_s3_input_train,
'validation':self.xgb_s3_input_validation})
def batch_predict(self, data, rows=500, **kwargs):
"""Batch prediction for the data using the recent created inference endpoint. This function is used
in the next one for actually getting the predictions.
Args:
rows (int): number of rows per batch. Probably it is pointless to change the default value.
data
Returns:
predictions in a numpy data structure separated by a comma
"""
split_array = np.array_split(data, int(data.shape[0] / float(rows) + 1))
predictions = ''
for array in split_array:
predictions = ','.join([predictions, self.xgb_predictor.predict(array).decode('utf-8')])
logging.info('Predictions made')
return np.fromstring(predictions[1:], sep=',')
def get_predictions(self, delete_endpoint='Yes', instance_type='ml.t2.medium', **kwargs):
"""This deploys an endpoint and makes the predictions on the test data.
Args:
delete_endpoint (str): whether to delete the endpoint after getting the predictions or not.
instance_type (str): instance type for the inference endpoint.
"""
self.xgb_predictor = self.xgb.deploy(initial_instance_count=1, instance_type=instance_type)
logging.info('Endpoint deployed')
self.xgb_predictor.content_type = 'text/csv' #This three lines are necessary for the endpoint
self.xgb_predictor.serializer = csv_serializer #to read the data
self.xgb_predictor.deserializer = None
predictions = self.batch_predict(self.test_data_features.as_matrix()) #it gets the scores for each datum
if delete_endpoint == 'Yes':
sagemaker.Session().delete_endpoint(self.xgb_predictor.endpoint)
logging.info('Endpoint deleted')
self.predictions = pd.DataFrame(predictions,columns=['score'])
def calculate_metrics(self, score = 0.1, **kwargs):
"""It calculates the following metrics for evaluating the performance of the model:
recall,precision,accuracy,f1_score,FP_rate,perdidas_eviatadas,fraudes y revisados.
For that, the function needs to calculate first the true negatives, false positives,
true positives and false negatives. Those variables are not accessible though. The calculation
is saved in the dictionary previously created with the function 'create_metrics_variables'
Args:
score (float): the treshold to calculate the metrics.
"""
#The indexes have to be reseted. Otherwise the concats (1 and 2) will be wrong.
test_data_features_reset_index = self.test_data_features.reset_index(inplace=False,drop=True)
test_data_label_reset_index = self.test_data_label.reset_index(inplace=False,drop=True)
self.score_and_test_label = pd.concat([self.predictions, #concat 1
test_data_label_reset_index],
axis = 1)
self.si_fraude = self.score_and_test_label[self.score_and_test_label['fraud']==1]
self.no_fraude = self.score_and_test_label[self.score_and_test_label['fraud']==0]
tn = self.no_fraude[self.no_fraude['score']<score]['fraud'].count()
fp = self.no_fraude[self.no_fraude['score']>=score]['fraud'].count()
tp = self.si_fraude[self.si_fraude['score']>=score]['fraud'].count()
fn = self.si_fraude[self.si_fraude['score']<score]['fraud'].count()
self.metrics_dict['Recall'].append(tp / (tp + fn))
self.metrics_dict['Precision'].append(tp / (tp + fp))
self.metrics_dict['Accuracy'].append((tp + tn) / (tp + fp + tn + fn))
#the F1 score is calculated this way because the way recall and precision are stored in lists makes it
#pointless to implement a solution with those 2 metrics (since they are stored in a list, so you will have
#to add a counter variable to know if you have to access to the value [0] or [1] of the list)
self.metrics_dict['F1_score'].append(2 * (((tp/(tp+fp))*(tp/(tp+fn)))/((tp/(tp+fp))+(tp/(tp+fn)))))
self.metrics_dict['FP_rate'].append(fp/(fp+tn))
self.pred = pd.concat([self.predictions, #concat 2
test_data_features_reset_index,
test_data_label_reset_index],
axis=1)
#the termination .item() in the next line is to convert np.float32 to native python float
self.metrics_dict['Perdidas_evitadas'].append(self.pred[(self.pred['score']>=score) & (self.pred['fraud']==1)]['mt_perdida_potencial_nr'].sum().item())
self.metrics_dict['Fraudes'].append(self.pred[(self.pred['score']>=score) & (self.pred['fraud']==1)]['mt_perdida_potencial_nr'].count())
self.metrics_dict['Revisados'].append(self.pred[(self.pred['score']>=score)]['score'].count())
logging.info('Metrics got successfully')
def create_metrics_variables(self, **kwargs):
"""It creates a dictionary that contains a list for each metric that is going to be calculated."""
self.metrics_dict = {}
self.metrics_list = ['Recall','Precision','Accuracy','F1_score','FP_rate', 'Perdidas_evitadas',
'Fraudes','Revisados']
for metric in self.metrics_list:
self.metrics_dict[metric] = []
def process(self, **kwargs):
"""The whole process that is make right after preprocessing the data until the metrics are obtained.
"""
gc.collect() #it frees RAM
self.save_data_in_S3_for_XGB(**kwargs)
self.train(**kwargs)
self.test_data_label = self.test_data.loc[:,'fraud']
self.test_data_label.columns = ['fraud']
self.test_data_features = self.test_data.drop(columns =['fraud'], axis=1)
self.get_predictions(**kwargs)
self.calculate_metrics(**kwargs)
def feature_hashing_changed(self, **kwargs):
"""Function for complying with DRY (Don't repeat yourself) principle in the below function"""
self.changed_preprocess_train_data = self.preprocess(self.raw_train_data, **kwargs)
self.changed_preprocess_validation_data = self.preprocess(self.raw_validation_data, **kwargs)
self.changed_preprocess_test_data = self.preprocess(self.raw_test_data, **kwargs)
def test_feature_hashing(self, data_file_name, variable_to_change, new_variable_value, **kwargs):
"""It runs the entire process to test different configurations in the feature hashing. First,
it has to split the raw data and save it, so that you can access whenever you want to the data
before being processed. The preprocessing is made in the three datasets (train,validation and test)
to assure consistency across both models. Then, it get the metrics for the a model with the default
preprocessing. After that, a second model with a different value for one chosen variable for the
feature hashing is trained and the new metrics are obtained and saved for comparison."""
raw_data = self.load_data(data_file_name)
self.create_metrics_variables()
self.split_data(raw_data)
self.raw_train_data = self.train_data
self.raw_validation_data = self.validation_data
self.raw_test_data = self.test_data
original_preprocess_train_data = self.preprocess(self.raw_train_data)
original_preprocess_validation_data = self.preprocess(self.raw_validation_data)
original_preprocess_test_data = self.preprocess(self.raw_test_data)
#the next 3 following variables are used in the training and prediction of the model
self.train_data = original_preprocess_train_data
self.validation_data = original_preprocess_validation_data
self.test_data = original_preprocess_test_data
self.process(**kwargs)
if variable_to_change == 'feature_hashing_big':
self.feature_hashing_changed(feature_hashing_big = new_variable_value)
elif variable_to_change == 'feature_hashing_small':
self.feature_hashing_changed(feature_hashing_small = new_variable_value)
elif variable_to_change == 'columns_to_transform_big':
self.feature_hashing_changed(columns_to_transform_big = new_variable_value)
elif variable_to_change == 'columns_to_transform_small':
self.feature_hashing_changed(columns_to_transform_small = new_variable_value)
elif variable_to_change == 'features_to_drop_after_transformation':
self.feature_hashing_changed(features_to_drop_after_transformation = new_variable_value)
self.train_data = self.changed_preprocess_train_data
self.validation_data = self.changed_preprocess_validation_data
self.test_data = self.changed_preprocess_test_data
self.process(**kwargs)
self.results = pd.DataFrame.from_dict(self.metrics_dict,
orient = 'index',
columns = ['1st test','2nd test'])
def test_new_variable(self, data_file_name, variable_to_delete, **kwargs):
"""Gathering function that execute the entire process needed to decide whether to preserve a variable or not.
Args:
data_file_name (str): pretty self explanatory
variable_to_delete (str): same as above
"""
raw_data = self.load_data(data_file_name)
original_data_preprocessed = self.preprocess(raw_data)
self.split_data(original_data_preprocessed)
self.create_metrics_variables(**kwargs)
self.process(**kwargs)
#To maintain the same data for both models (and hence avoid changes due to randomness)
#we need to make the modifications in the same datasets
self.train_data = self.train_data.drop(columns=[variable_to_delete], axis=1)
self.validation_data = self.validation_data.drop(columns=[variable_to_delete], axis=1)
self.test_data = self.test_data.drop(columns=[variable_to_delete], axis=1)
self.process(**kwargs)
self.results = pd.DataFrame.from_dict(self.metrics_dict,
orient = 'index',
columns = ['1st test','2nd test'])
def single_test(self, data_file_name, **kwargs):
"""For the cases when you just want to run a single test(prototyping or whatever).
"""
raw_data = self.load_data(data_file_name)
processed_data = self.preprocess(raw_data)
self.split_data(processed_data)
self.create_metrics_variables()
self.process(**kwargs)
self.results = pd.DataFrame.from_dict(self.metrics_dict,
orient = 'index',
columns = ['1st test'])
</code></pre>
<p>So let's say I want to test whether the variable 'pax' would improve my model; I just need to code this:</p>
<pre><code>a = HoldOutSample()
a.test_new_variable(data_file_name = 'data1.csv', variable_to_delete = 'pax')
a.results
</code></pre>
<p>And I will get this:</p>
<p><a href="https://i.stack.imgur.com/zaz8Z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zaz8Z.png" alt="enter image description here"></a></p>
<p>I have omitted the maximum length of 79 established by PEP8 because I am going to use this code just in Jupyter Notebook and I have sticked to the width of notebook. However, there are a few lines that are very large and I don't know how to split them without breaking the code (or if that is important at all). </p>
<p>This is the first time I use OOP, so I guess there's plenty of room for improvements. Also, I was wondering if the way I store and present the data is the better. Even I have doubts concerning if this is an appropriate case to use OOP instead of functional programming. Any help is appreciated.</p>
<p>Thank you very much</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T16:27:31.737",
"Id": "225728",
"Score": "3",
"Tags": [
"python",
"object-oriented",
"machine-learning"
],
"Title": "Automated machine learning training and evaluation in Sagemaker with XGBoost"
}
|
225728
|
<p>My C++ code accomplishes the following:</p>
<p>It consists of a class called <code>ParticleGenerator</code> which has three important configuration options: <code>spatialGeneratorType</code>, <code>angularGeneratorType</code> and <code>energyGeneratorType</code>. The user would choose a value for each of these options from the possible values.</p>
<p>I am trying to make my code as tidy as possible and to handle as best as possible a user entering a bad value for any of these parameters. There are some setter methods to assign these values and these methods must support string arguments.</p>
<p>I am using a <code>enum</code> for each option which lists the possible values then I use a <code>map</code> to map a <code>enum</code> value to a string (human readable value).</p>
<p>My approach works as intended but I feel it has too much repeated code. I tried to minimize it introducing some auxiliary functions but still there are too many "if/else" statements. I tried using templates but could not make it tidier that's why I chose to use "if/else".</p>
<p>I have some experience writing complex code in Python but I have never written very complex projects in C++ (only scripts) I would appreciate any feedback.</p>
<p>Thanks.</p>
<p>My code:</p>
<pre><code>
#include <iostream>
#include <map>
#include <set>
using namespace std;
using namespace ParticleGeneratorConfig;
class ParticleGenerator {
private:
std::map<string, spatialGeneratorTypes> spatialGeneratorTypesMap = {
{"OPTION1", spatialGeneratorTypes::OPTION1},
};
std::map<string, angularGeneratorTypes> angularGeneratorTypesMap = {
{"OPTION1", angularGeneratorTypes::OPTION1},
};
map<string, energyGeneratorTypes> energyGeneratorTypesMap = {
{"OPTION1", energyGeneratorTypes::OPTION1},
};
spatialGeneratorTypes spatialGeneratorType;
angularGeneratorTypes angularGeneratorType;
energyGeneratorTypes energyGeneratorType;
template <class generatorTypes>
string GeneratorEnumToString(generatorTypes type) {
// type is in either 'spatialGeneratorTypes', 'angularGeneratorTypes' or 'energyGeneratorTypes'
if (typeid(generatorTypes) == typeid(spatialGeneratorTypes)) {
for (auto const& pair : spatialGeneratorTypesMap) {
if (pair.second == spatialGeneratorType) {
return pair.first;
}
}
} else if (typeid(generatorTypes) == typeid(angularGeneratorTypes)) {
for (auto const& pair : angularGeneratorTypesMap) {
if (pair.second == angularGeneratorType) {
return pair.first;
}
}
} else if (typeid(generatorTypes) == typeid(energyGeneratorTypes)) {
for (auto const& pair : energyGeneratorTypesMap) {
if (pair.second == energyGeneratorType) {
return pair.first;
}
}
} else {
// error
return "ERROR!";
}
return "NONE! (error)";
}
inline string NormalizeTypeString(string type) {
std::transform(type.begin(), type.end(), type.begin(), ::tolower);
// remove '_'
string string_to_remove = "_";
while (type.find(string_to_remove) != string::npos) {
type.replace(type.find("_"), string_to_remove.length(), "");
}
return type;
}
inline void SetGeneratorTypeFromStringAndCategory(string type, string generator_category) {
// generator_category must be one of the following: 'spatial', 'angular', 'energy'
if (generator_category == "spatial") {
for (auto const& pair : spatialGeneratorTypesMap) {
if (NormalizeTypeString(pair.first) == NormalizeTypeString(type)) {
spatialGeneratorType = pair.second;
return;
}
}
} else if (generator_category == "angular") {
for (auto const& pair : angularGeneratorTypesMap) {
if (NormalizeTypeString(pair.first) == NormalizeTypeString(type)) {
angularGeneratorType = pair.second;
return;
}
}
} else if (generator_category == "energy") {
for (auto const& pair : energyGeneratorTypesMap) {
if (NormalizeTypeString(pair.first) == NormalizeTypeString(type)) {
energyGeneratorType = pair.second;
return;
}
}
} else {
// generator_category not valid
cout << "ERROR: category " << generator_category << " not valid. nothing is set";
return;
}
cout << "ERROR when setting " << generator_category << " generator type to: " << type << endl;
cout << "Valid values are: ";
string to_print = "";
if (generator_category == "spatial") {
for (auto const& pair : spatialGeneratorTypesMap) {
to_print += pair.first;
to_print += ", ";
}
} else if (generator_category == "angular") {
for (auto const& pair : angularGeneratorTypesMap) {
to_print += pair.first;
to_print += ", ";
}
} else if (generator_category == "energy") {
for (auto const& pair : energyGeneratorTypesMap) {
to_print += pair.first;
to_print += ", ";
}
}
// remove the last ", "
if (to_print.size() > 0) to_print.resize(to_print.size() - 2); // '2' is the size of ", "
cout << to_print << endl;
}
public:
inline string GetSpatialGeneratorType() { return GeneratorEnumToString(spatialGeneratorType); }
inline string GetAngularGeneratorType() { return GeneratorEnumToString(angularGeneratorType); }
inline string GetEnergyGeneratorType() { return GeneratorEnumToString(energyGeneratorType); }
inline void SetSpatialGeneratorType(spatialGeneratorTypes type) { spatialGeneratorType = type; }
inline void SetSpatialGeneratorType(string type) {
SetGeneratorTypeFromStringAndCategory(type, "spatial");
}
inline void SetAngularGeneratorType(angularGeneratorTypes type) { angularGeneratorType = type; }
inline void SetAngularGeneratorType(string type) {
SetGeneratorTypeFromStringAndCategory(type, "angular");
}
inline void SetEnergyGeneratorType(energyGeneratorTypes type) { energyGeneratorType = type; }
inline void SetEnergyGeneratorType(string type) { SetGeneratorTypeFromStringAndCategory(type, "energy"); }
ParticleGenerator();
};
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T12:58:49.137",
"Id": "438495",
"Score": "0",
"body": "We could provide much better reviews if you include some test code that showed how this class is used."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T16:35:03.430",
"Id": "225729",
"Score": "2",
"Tags": [
"c++",
"beginner"
],
"Title": "Code to configure \"particle generator\" from valid configurations options"
}
|
225729
|
<p>I'm working on a webapp and I'm using js/php (php and jquery latest versions).</p>
<p>Is there anything I should do to improve security?</p>
<p><em>I'm not super worried about safety as the current users are using a very buggy (pretty much every exploit works) and outdated (php 4) platform and never attempted anything.</em></p>
<p>But better be safe than sorry and learn in the process.</p>
<p><strong>IN JS SIDE I HAVE THIS:</strong></p>
<p>a function to insert data</p>
<pre><code>function insertItem() {
</code></pre>
<p>First i do some js validation for empty fields (will check again in php side)</p>
<pre><code> var valErrors = 0;
if (!$('#addName_input').val()) {
$('#addName_input').addClass("inputError");
valErrors++;
}
if (valErrors>0) {
new Noty({
type: 'error',
layout: 'topCenter',
timeout: '2000',
progressBar: 'true',
overlay: 'true',
text: 'The name is empty'
}).show();
return false;
}
</code></pre>
<p>I also use a js regex plugin to help me limit what users can type on inputs that have important data. That way i can prevent from inserting letters in input designed for numbers, etc (but i also check that later on php side)</p>
<p>Then i serialize the form data</p>
<pre><code>var data = $("#newForm").serialize();
</code></pre>
<p>i send it using ajax:</p>
<pre><code>$.ajax({
type: 'POST',
url: 'modules/' + moduleFolder + '/funcs/insert.php',
data: data,
dataType: 'json',
success: function(response) {
</code></pre>
<p><strong>now on the PHP side (insert.php)</strong></p>
<p>if the request method is not post i redirect</p>
<pre><code>if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
header("HTTP/1.1 301 Moved Permanently");
header("Location: ../../../.");
exit();
}
</code></pre>
<p>then i fetch the request data:</p>
<pre><code>$name = isset($_POST['addName_input']) ? $_POST['addName_input'] : '' ;
</code></pre>
<p>then i do some validations</p>
<pre><code>if (empty($name)) { }
</code></pre>
<p>and check with a validation class if the string "hasSomething()" i dont want:</p>
<pre><code>if (hasNumbers($name) || hasSpecialChars($name))
</code></pre>
<p>then i filter_sanitize all the vars</p>
<pre><code>$name = filter_var($name, FILTER_SANITIZE_STRING);
</code></pre>
<p>and finally use a database class (with prepared statements) to insert the data</p>
<pre><code>$insert = $db->query('INSERT INTO zapp_list_tablename (id,name) VALUES (?,?,?)', NULL, $name);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-10T04:57:12.640",
"Id": "443514",
"Score": "0",
"body": "You're inserting one variable as three values into two fields?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-12T22:05:11.840",
"Id": "444942",
"Score": "1",
"body": "did you truncate the Javascript? I would guess so, given that `valErrors` is set to `true` in the first conditional block and then immediately checked in the next condition... but I could be wrong... also, could you paste more of the PHP? The lines above aren't exactly stub code but it helps to have more context with how the lines are used... [the limit for code on this site has been increased to 65535 characters](https://codereview.meta.stackexchange.com/a/7163/120114)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T16:45:48.490",
"Id": "225730",
"Score": "2",
"Tags": [
"javascript",
"php",
"jquery"
],
"Title": "JS PHP insert data in database - is it secure enough?"
}
|
225730
|
<p>I have a Feather M0 basic paired with a OLED FeatherWing. I am making an instructions page but the code is quite repetitive. How can I make my code shorter?</p>
<pre><code>import board
from busio import I2C
from adafruit_ssd1306 import SSD1306_I2C
from time import sleep
from digitalio import DigitalInOut, Direction, Pull
i2c = I2C(board.SCL, board.SDA)
oled = SSD1306_I2C(128, 32, i2c)
button_A = DigitalInOut(board.D9)
button_B = DigitalInOut(board.D6)
button_C = DigitalInOut(board.D5)
button_A.direction = Direction.INPUT
button_B.direction = Direction.INPUT
button_C.direction = Direction.INPUT
button_A.pull = Pull.UP
button_B.pull = Pull.UP
button_C.pull = Pull.UP
def check_buttons():
if button_A.value is False:
return 'A'
elif button_B.value is False:
return'B'
elif button_C.value is False:
return 'C'
else:
return None
def wait_for_A():
sleep(0.5)
while check_buttons() is not 'A':
pass
oled.fill(0)
oled.text('Adafruit Feather', 0, 0, 1)
oled.text('Program selector', 0, 8, 1)
oled.text('Press A to continue', 0, 24, 1)
oled.show()
wait_for_A()
oled.fill(0)
oled.text('Instructions:', 0, 0, 1)
oled.text('Use A and C to move', 0, 8, 1)
oled.text('up and down.', 0, 16, 1)
oled.text('Press A to continue', 0, 24, 1)
oled.show()
wait_for_A()
oled.fill(0)
oled.text('Instructions (cont.):', 0, 0, 1)
oled.text('Press B to select a', 0, 8, 1)
oled.text('program.', 0, 16, 1)
oled.text('Press A to continue', 0, 24, 1)
oled.show()
wait_for_A()
oled.fill(0)
oled.text('Instructions (cont.):', 0, 0, 1)
oled.text('At anytime you can', 0, 8, 1)
oled.text('press reset to go...', 0, 16, 1)
oled.text('Press A to continue', 0, 24, 1)
oled.show()
wait_for_A()
oled.fill(0)
oled.text('Instructions (cont.):', 0, 0, 1)
oled.text('... back to the main', 0, 8, 1)
oled.text('screen.', 0, 16, 1)
oled.text('Press A to continue', 0, 24, 1)
oled.show()
wait_for_A()
oled.fill(0)
oled.text('Instructions (cont.):', 0, 0, 1)
oled.text('The programs will', 0, 8, 1)
oled.text('have there own...', 0, 16, 1)
oled.text('Press A to continue', 0, 24, 1)
oled.show()
wait_for_A()
oled.fill(0)
oled.text('Instructions (cont.):', 0, 0, 1)
oled.text('... instructions.', 0, 8, 1)
oled.text('Press A to continue', 0, 16, 1)
oled.text('to menu', 0, 24, 1)
oled.show()
wait_for_A()
oled.fill(0)
oled.show()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T18:29:02.497",
"Id": "438429",
"Score": "1",
"body": "What is circuit-python and why do you think it deserves it's own tag? Can you tell us more about what your code is supposed to accomplish and whether it succesfully does so?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T18:30:11.803",
"Id": "438430",
"Score": "0",
"body": "With the Feather M0 you mean the protoboard with ATSAMD21 Cortex M0 microcontroller?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T23:43:55.810",
"Id": "438694",
"Score": "0",
"body": "The Feather M0 does use the ATSAMD21, it's the same as the Arduino Zero"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T23:47:15.680",
"Id": "438695",
"Score": "0",
"body": "@Mast, circuitpython is a subset of micropython maintained by Adafruit Industries."
}
] |
[
{
"body": "<p>I think here a small class would help to keep track of all things related to a <code>Button</code>:</p>\n\n<pre><code>class Button(DigitalInOut):\n def __init__(self, name, pin, direction=Direction.INPUT, pull=Pull.UP):\n self.name = name\n super().__init__(pin)\n self.direction = direction\n self.pull = pull\n\n def wait_for_press(self):\n while self.value:\n pass\n</code></pre>\n\n<p>(Untested, since I obviously don't have your hardware lying around.) </p>\n\n<p>With your initialization code can be shortened a bit:</p>\n\n<pre><code>names = [\"A\", \"B\", \"C\"]\npins = [board.D9, board.D6, board.D5]\nbuttons = {name: Button(name, pin) for name, pin in zip(names, pins)}\n</code></pre>\n\n<p>As for your printing to the oled, they always follow the same format, so just define a function for that:</p>\n\n<pre><code>def print_page(oled, strings):\n oled.fill(0)\n for i, s in enumerate(strings):\n oled.text(s, 0, i * 8, 1)\n oled.show()\n</code></pre>\n\n<p>After which your main code becomes:</p>\n\n<pre><code>messages = [\n\"\"\"\nAdafruit Feather\nProgram selector\n\nPress A to continue\n\"\"\",\n\"\"\"\nInstructions:\nUse A and C to move\nup and down\nPress A to continue\n\"\"\",\n\"\"\"\nInstructions (cont.):\nPress B to select a\nprogram.\nPress A to continue\n\"\"\",\n...\n]\n\nfor message in messages:\n print_page(oled, message.splitlines()[1:])\n buttons[\"A\"].wait_for_press()\noled.fill(0)\noled.show()\n</code></pre>\n\n<p>Note that I used <a href=\"https://docs.python.org/3/tutorial/introduction.html#strings\" rel=\"nofollow noreferrer\">triple-quoted strings</a> so you can just write your message in plaintext, line-breaks included. You might want to outsource that part to another file and just load / import from that.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T17:39:33.437",
"Id": "225782",
"ParentId": "225734",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "225782",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T17:55:53.873",
"Id": "225734",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"embedded",
"circuit-python"
],
"Title": "OLED FeatherWing instruction page"
}
|
225734
|
<p>A hashmap is a data structure that implements an associative array abstract data type using keys and values and has a hash function to compute an index into an array, from which the desired value can be set and get <a href="https://en.wikipedia.org/wiki/Hash_table" rel="nofollow noreferrer">[reference]</a>.</p>
<hr>
<p>Based on some tutorial, I wrote this hashmap class:</p>
<pre><code>class HashMap():
def __init__(self):
self.hahsmap_size = 32
self.hashmap_data = [None] * self.hahsmap_size
def __get_hash_mod_size(self, key):
hash_key_var = hash(key+str(self.hahsmap_size*0.01))
return hash_key_var % self.hahsmap_size
def set_key_value(self, key, value):
key_var = self.__get_hash_mod_size(key)
key_value_list = [key, value]
if self.hashmap_data[key_var] is None:
self.hashmap_data[key_var] = list([key_value_list])
return True
else:
for pair in self.hashmap_data[key_var]:
print(pair)
if pair[0] == key:
pair[1] = value
return True
self.hashmap_data[key_var].append(key_value_list)
return True
def get_key(self, key):
key_var = self.__get_hash_mod_size(key)
if self.hashmap_data[key_var] is not None:
for pair in self.hashmap_data[key_var]:
if pair[0] == key:
return pair[1]
return None
def remove_key(self, key):
key_var = self.__get_hash_mod_size(key)
if self.hashmap_data[key_var] is not None:
return False
for i in range(len(self.hashmap_data[key_var])):
if self.hashmap_data[key_var][i][0] == key:
self.hashmap_data[key_var].pop(i)
return True
def print_hashmap(self):
for item in self.hashmap_data:
if item is not None:
print(item)
hm = HashMap()
hm.set_key_value('A', '1')
hm.set_key_value('A', '2')
hm.set_key_value('B', '1')
hm.set_key_value('A', '3')
hm.set_key_value('A', '4')
hm.set_key_value('C', '1')
hm.set_key_value('D', '1')
hm.set_key_value('E', '1')
hm.set_key_value('E', '2')
hm.remove_key('A')
hm.remove_key('B')
hm.remove_key('B')
hm.print_hashmap()
</code></pre>
<p>If you had time, I'd appreciate a review. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-16T16:04:07.763",
"Id": "530718",
"Score": "0",
"body": "I am not seeing it in this code, but how do you handle collisions and how do you get your hash value?"
}
] |
[
{
"body": "<p>The first thing that stands out here to me is that you should be using <code>__get_item__</code> and <code>__set_item__</code>, and <code>__repr__</code> instead of <code>get-key</code>, <code>set-key-value</code> and <code>print_hashmap</code>. This will opt you into the syntax of collections in python where you use <code>d[key]</code> to get a key, <code>d[key] = val</code> to set a value, and <code>print(d)</code> to print it. This may seem trivial, but the fact that python lets containers you have written to feel as nice as base ones is a large part of why Python is such a natural feeling language as opposed to something like Java, where this style would be considered correct.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T19:15:10.490",
"Id": "438433",
"Score": "0",
"body": "Acuatlly Python dictionaries serve as hash maps but the challenge i think is deriving it!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T19:18:18.627",
"Id": "438436",
"Score": "1",
"body": "huh? None of what I said is keeping op from deriving it, I'm just showing how op can derive it such that it is nice to use after."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T19:20:05.017",
"Id": "438437",
"Score": "0",
"body": "Costs nothing to actually write some illustrative codes in your answer ^^_"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T19:23:04.390",
"Id": "438438",
"Score": "2",
"body": "my point with this answer is that simply changing the names of the methods op has implemented would be a significant improvement. No other new code needed."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T18:43:58.873",
"Id": "225737",
"ParentId": "225736",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "225737",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T18:30:22.573",
"Id": "225736",
"Score": "4",
"Tags": [
"python",
"beginner",
"algorithm",
"object-oriented",
"hash-map"
],
"Title": "A Basic HashMap (Python)"
}
|
225736
|
<blockquote>
<p>The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)</p>
<pre><code>P A H N
A P L S I I G
Y I R
</code></pre>
<p>And then read line by line: "PAHNAPLSIIGYIR"</p>
<p>Write the code that will take a string and make this conversion given a number of rows:</p>
<pre><code>string convert(string s, int numRows);
</code></pre>
</blockquote>
<ul>
<li><p>I used a helper function approach after realizing that the "Grid" needs to be updated in the same manner over and over again</p>
</li>
<li><p>I have received feedback that storing a grid may take too much memory</p>
</li>
<li><p>Would a "mathematical" approach actually be more readable? And would it be something that can be though of within 20ish minutes (interview time)</p>
</li>
<li><p>I have many if statements that are used to exit out of loops to avoid array index errors</p>
</li>
</ul>
<p>Any feedback or criticism is appreciated - nitpick on anything that seems off</p>
<ul>
<li>glaring issue is that this doesn't handle edge cases well. For example: "A 2"</li>
</ul>
<p><a href="https://leetcode.com/problems/zigzag-conversion/" rel="nofollow noreferrer">https://leetcode.com/problems/zigzag-conversion/</a></p>
<pre><code>class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
row = [''] * (len(s) // 2)
self.s = s
self.numRows = numRows
self.final_grid = []
for i in range(numRows):
self.final_grid.append(list(row))
self.addElements(0, 0)
return "".join(map("".join, self.final_grid))
def addElements(self, count, column):
print(column, "beg")
for i in range(self.numRows):
if count > len(self.s) - 1:
break
self.final_grid[i][column] = self.s[count]
count += 1
for i in range(1, self.numRows - 1):
if count > len(self.s) - 1:
break
self.final_grid[self.numRows - i - 1][column + i] = self.s[count]
count += 1
print(column, "end")
print(column + self.numRows - 1)
if count < len(self.s) - 1:
self.addElements(count, (column + self.numRows - 1))
</code></pre>
|
[] |
[
{
"body": "<p>As you pointed out, you don't actually need to lay the characters out into a grid. It would be more efficient to use arithmetic to figure out the indexes of the characters in each row.</p>\n\n<p>For example, if <code>num_rows</code> is 3, then each down-up cycle will consist of 4 characters. (<code>zigzag_size = 2 * num_rows - 2</code>). Then we also know that the top of each zigzag will consist of indexes 0, 4, 8, 12, … of the string (<code>for z in range(0, len(s), zigzag_size)</code>).</p>\n\n<p>The middle row will consist of indexes <code>z+1</code> and <code>z+3</code>. The bottom row will consist of indexes <code>z+2</code>. The <code>zigzag_indexes()</code> generator generalizes those calculations for any <code>numRows</code>.</p>\n\n<pre><code>import math\n\ndef zigzag_indexes(num_rows):\n yield (0, math.inf) # Top of each zigzag\n yield from zip(\n range(1, num_rows), # Downward\n range(2 * num_rows - 3, num_rows - 1, -1) # Upward\n )\n yield (num_rows - 1, math.inf) # Bottom of each zigzag\n\ndef convert(s, num_rows):\n if num_rows == 1:\n return s\n zigzag_size = 2 * num_rows - 2\n return ''.join(\n (s[z+a] if z+a < len(s) else '') + (s[z+b] if z+b < len(s) else '')\n for a, b in zigzag_indexes(num_rows)\n for z in range(0, len(s), zigzag_size)\n )\n\nprint(convert('PAYPALISHIRING', 3))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T07:42:04.447",
"Id": "225809",
"ParentId": "225740",
"Score": "3"
}
},
{
"body": "<p>Please don't get me wrong. The code works. Working code is a good thing. Working code that <em>might</em> break is not broken code.</p>\n\n<h3>Fundamentals</h3>\n\n<ul>\n<li><p>Starting a Python module (or file in any language) with a comment describing what problem the code solves is helpful. It helps reviewers and future users understand what the programmer is trying to do. More importantly, it helps the programmer themselves understand what they are trying to do. Describing the problem first usually leads to better solutions.</p></li>\n<li><p>Starting Python functions with docstrings (or documenting functions/methods in other languages).</p></li>\n<li><p>Meaningful names. <code>convert</code> and <code>addElement</code> could be part of an alchemist's cookbook. Convert from what to what? Add what sort of element to what sort of aggregate?</p></li>\n<li><p>Language idioms: in Python, compound names use string_case not camelCase.</p></li>\n</ul>\n\n<h3>Leetcode</h3>\n\n<p>At a high level, Leetcode puzzles are designed as computer science challenges. The questions go beyond FizzBuzz's basic for loops and modulo application. Unlike FizzBuzz, good Leetcode answers are 'clever'...at least in the sense that they reflect application of computer science, experience, insight, etc.</p>\n\n<p>Computer science, experience, insight, etc. help produce code that scales with about as much effort as writing brute force code. Brute force solutions are fine for FizzBuzz. They are not great solutions to Leetcode's puzzles.</p>\n\n<p>The upside is that better solutions to Leetcode puzzles are easier to find with study and practice. Experience and knowledge help a programmer analyze its puzzles and provide insight into the problem at a <em>high</em> level. </p>\n\n<p>What works for strings of length 1000 might sputter and stall at length ten billion...at least until the new hardware shows up or the AWS budget grows.</p>\n\n<h2>This problem</h2>\n\n<ul>\n<li><p>The function signature is <code>convert(String string_one) -> String string_two</code> and <code>string_one</code> and <code>string_two</code> are the same <a href=\"https://en.wikipedia.org/wiki/Multiset\" rel=\"nofollow noreferrer\">multiset</a>. That looks a bit like sorting. Many sorting algorithms that scale well <em>on random data</em> have space = O(n) and time = O(n log n).</p></li>\n<li><p>The <strong>grid solution</strong> in the question has <code>space = O(mn)</code> where <code>m</code> is the number of rows. That's worse than <code>space = O(n)</code>, so we know we can do better...<strong>but</strong> only if we solve the right problem. One issue with the <strong>grid solution</strong> it solves a harder problem in order to solve the actual problem. The harder problem is <a href=\"https://en.wikipedia.org/wiki/Prettyprint\" rel=\"nofollow noreferrer\">pretty printing</a> with all the spaces.</p></li>\n<li><p>The format of the question on Leetcode suggests the pretty printing solution. And pretty printing ultimately uses <code>space = O(mn)</code> because it has to include all the spaces and <code>time = O(mn)</code> because all those spaces get printed). </p></li>\n<li><p>Is <code>time = O(mn)</code> better or worse than <code>time = O(n log n)</code>? It <a href=\"https://cs.stackexchange.com/questions/9523/is-omn-considered-linear-or-quadratic-growth\">depends</a>. Here it is probably better because <code>convert (my_string, 1) -> my_string</code> and because <code>convert(my_string, length(my_string) -> my_string</code>. It looks like this is a case where <code>time = O(mn)</code> is linear. Which means it might not be a sorting problem.</p></li>\n</ul>\n\n<h3>A space improvement to the grid solution</h3>\n\n<p>One way to improve the space requirements is to only record the grid coordinates of the letters and ignore the spaces. For example <code>\"PAYPALISHIRING\", numRows = 3</code> has an intermediate data structure <code>[(1,1, \"P\"), (2,1,\"A\"}, (3,1,\"Y\")...(2,7,\"G\")]</code>...a one-indexed list of tuples (row, column, string). </p>\n\n<p>The high level solution (in psuedo-code) might be something like:</p>\n\n<pre><code># Program A\ntemp_array = make_array(input length)\nfor i in input\n temp_array[i] = get_row_and_column(input[i])\nend for\nreturn sort_into_rows(temp_array)\n</code></pre>\n\n<h2>Sorting isn't free</h2>\n\n<p>As a starting point we should expect <code>time = O(n log n)</code> but pretty printing is probably linear <code>time = O(mn)</code>. Smells like just recording grid coordinates has traded less space for more time. Another code smell is that we are generating a new value and sorting solely on that value. The original string doesn't play a role. Yoda's <code>\"HIRIINGISPAYPAL\", numRows=3</code> produces a list tuples with identical row and column values.</p>\n\n<p>This is why we have the intuition that a 'mathematical' solution is possible. We know that strings of the same length pretty print the same number of rows into congruent patterns. </p>\n\n<h3>I spent some time stuck on sorting.</h3>\n\n<p>I came to <code>Program A</code> not long after reading this question a few times and thinking about how to answer it. Thinking about sorting the grid got me worried about <a href=\"https://en.wikipedia.org/wiki/Sorting_algorithm#Stability\" rel=\"nofollow noreferrer\">stable sorting</a> even though it's ultimately not an issue because <code>row, column</code> is a unique value.</p>\n\n<p><strong>But</strong> the reason I was worried about sort stability was if I looked at a rows within the grid row<sub>1</sub> contains a character that is earlier in the message than row<sub>2</sub>. Within a row, earlier values in the message are earlier values within a row. It's also true for columns, but it turns out rows are enough.</p>\n\n<h3>Improving on the grid and the sort</h3>\n\n<p>I spent a while thinking about the algorithm in terms of sorting and rows. Thinking lexographically. None of it was obvious. Eventually, it dawned on me.</p>\n\n<pre><code>output = row_1 + row_2 + ... row_n\n</code></pre>\n\n<p>for example</p>\n\n<pre><code>\"PAYPALISHIRING\", numRows = 4\" -> \"PIN\" + \"ALSIG\" + \"YAHR\" + \"PI\"\n</code></pre>\n\n<p>and an O(n) solution might be</p>\n\n<pre><code>make a linked list for each row\nfor each character in the input\n determine its row\n place it at the end of the corresponding list\nend for\nconcatenate the linked lists\noutput the concatenation\n</code></pre>\n\n<p>In terms of space, there are no empty nodes with linked lists. \"PAYPALISHIRING\", numRows = 4\" produces rows 3,5,4,2. Using four arrays of size 5 would utilize 70% of the capacity...with array's it's still the grid.</p>\n\n<h3>Still stuck in sorting</h3>\n\n<p>Thinking in terms of rows changes a generalized sort into a [bucket sort(<a href=\"https://en.wikipedia.org/wiki/Bucket_sort\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Bucket_sort</a>). I knew I was in O(n) space but bucket sorting has a worst case of O(n<sup>2</sup> and that's worse than general sorting at O(n log n) <strong>even though intuition says it will be faster</strong>.</p>\n\n<h2>Making the problem simpler</h2>\n\n<p>Eventually it dawned on me. There's bucketing but no sorting. It's like dealing cards. An (honest) dealer deals round the table without considering the values of the cards. It's the same procedure when a hand is three cards as when a hand is five cards or seven. There is a cycle.</p>\n\n<p>When the <code>ZigZag</code> is over three rows, row placement cycles (1,2,3,2). With four rows the cycle is (1,2,3,4,3,2). With five rows its (1,2,3,4,5,4,3,2). <strong>There is no conditional logic.</strong></p>\n\n<h2>Some computer science</h2>\n\n<p>The length of the cycle is <code>(2*numRows)-2</code>. An algorithm for <code>space = O(m+n)</code> and <code>time = O(m+n)</code>:</p>\n\n<pre><code>generate the cycle based on numRows\n\nfor each character in input\n put character at current row in cycle \n next row in cycle\n</code></pre>\n\n<ul>\n<li><p>There are tradeoffs regarding how the cycle is stored. One option is to use an array or list and keep track of where we are in the list and reset to the head of the list whenever we reach its end. Another alternative is to use a generator and call it each time we need another value. For example we might use <a href=\"https://docs.python.org/2.7/library/itertools.html#itertools.cycle\" rel=\"nofollow noreferrer\"><code>itertools.cycle</code></a> in Python. In the end, Python's <code>itertools.cycle</code> is probably going to be better than the code I am likely to write. YMMV.</p></li>\n<li><p>Is a one step solution better? Writing each character to the correct row and then merging the rows after all characters have been processed requires two reads and two writes for each character. Mathematically it is possible to allocate an output array and then write each character to it's appropriate place in a single step. This requires only one read and one write for each character.</p></li>\n<li><p>A difference between engineering and mathematics is that the one step solution assumes that input, output, and the program all fit in available memory. When they don't, the second reads and writes of the two step solution wind up happening implicitly. </p></li>\n<li><p>Many interesting data processing problems don't fit all into memory at once. The two step <a href=\"https://en.wikipedia.org/wiki/Divide-and-conquer_algorithm\" rel=\"nofollow noreferrer\">divide and conquer</a> approach has the additional advantage of simpler logic than the pointer tracking required for a one step solution...fewer <code>i</code>'s and <code>j</code>'s is a good thing.</p></li>\n</ul>\n\n<h2>20 minutes to solve</h2>\n\n<p>If it's not obvious already, I spent more than 20 minutes thinking about the problem. </p>\n\n<h3>Leetcode revisited</h3>\n\n<p>Any problem I can solve in less than twenty minutes has to be a problem I can solve in twenty hours. Getting to good solutions quickly means having ideas about good and bad solutions in the context of Leetcode.</p>\n\n<p>So there are two kinds of practice Leetcode offers. Practice at working through problems quickly and practice working through problems deeply. It's the depth makes Leetcode's puzzles interesting. It's the range of possible approaches that make it useful for bucket sorting programmers when programmers need to be bucket sorted.</p>\n\n<p>Both kinds of practice matter. This answer went deeper than was ultimately necessary. But that depth might help us recognize when a question is simpler than first thought.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T17:27:57.783",
"Id": "225837",
"ParentId": "225740",
"Score": "1"
}
},
{
"body": "<p>Earlier today I was driving home and came across this question, and thought of a method to do this in seconds.</p>\n\n<ol>\n<li><p>Each message has a 'chunk' depending on the amount of rows.</p>\n\n<p>In the example, this is the first chunk:</p>\n\n<pre><code>P\nA P\nY\n</code></pre></li>\n<li><p>Each chunk uses the same indexes from the rest of the message. And so you can do a simple slice, <code>message[start::chunk_size]</code>.</p></li>\n<li>The size of the chunk is easy to calculate, as it increases by 2 for each row. Starting with 1, 2, 4 ...</li>\n<li><p>You can determine the row the slice is on by:</p>\n\n<ol>\n<li>By going in order for the first <code>row</code> slices; and</li>\n<li>By going backward for the last <code>row-2</code> slices starting from the second to last row.</li>\n</ol>\n\n<p>Take:</p>\n\n<pre><code>1\n2 6\n3 5\n4\n</code></pre>\n\n<p>At first I thought of this in a slightly different way, in which it was:</p>\n\n<pre><code>1\n2 6\n3 5\n 4\n</code></pre></li>\n<li><p>From this you just intertwine the rows in those indexes. Which <a href=\"https://codegolf.stackexchange.com/a/188995\">was a recent Code Golf HNQ</a>.</p></li>\n</ol>\n\n<p>This can be achieved using the following code in under 20 minutes. Where the hardest part is (4).</p>\n\n<pre><code>import functools\nimport itertools\nimport operator\n\n\ndef intertwine(*lists):\n return functools.reduce(operator.add, itertools.zip_longest(*lists, fillvalue=''))\n\n\ndef change(text, rows):\n chunk_size = max((rows-1) * 2, 1)\n slices = [text[start::chunk_size] for start in range(chunk_size)]\n backward_rows = max(rows - 2, 0)\n rows = zip(slices[:rows], [''] + slices[:backward_rows + 1:-1] + [''])\n return ''.join([\n ''.join(intertwine(first, second))\n for first, second in rows\n ])\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T22:09:03.397",
"Id": "225860",
"ParentId": "225740",
"Score": "1"
}
},
{
"body": "<p>Although you already accepted an answer, here is my two cents.</p>\n\n<h3>The code:</h3>\n\n<p>Although recursive functions can lead to elegant solutions for some problems, in <code>addElement()</code> I think the recursive call complicates things. So I changed that to an iterative solution, and kept track of the column index. The function is also complicated by terminating the loops when you run out of letters in the string. This can be handled by iterating over the string and using a <code>try ... except StopIteration</code> construct to catch when the letters are exhausted. Note, we don't need to pass in count or column any longer.</p>\n\n<pre><code>def addElements(self):\n letter = iter(self.s)\n column = 0\n\n try:\n while True:\n # fill in down a column\n for row in range(self.numRows):\n self.final_grid[row][column] = next(letter)\n\n # fill in up a diagonal\n column += 1 \n for row in range(self.numRows - 2, 0, -1):\n self.final_grid[row][column] = next(letter)\n column += 1 \n\n except StopIteration:\n # ran out of letters\n pass\n</code></pre>\n\n<p>I think this is simple enough to move it into the <code>convert()</code> function:</p>\n\n<pre><code>class Solution:\n def convert(s, numRows):\n grid = [['']*(len(s)//2) for _ in range(numRows)]\n\n letter = iter(s)\n column = 0\n\n try:\n while True:\n # fill in down a column\n for row in range(numRows):\n grid[row][column] = next(letter)\n\n # fill in up a diagonal\n column += 1 \n for row in range(numRows - 2, 0, -1):\n grid[row][column] = next(letter)\n column += 1 \n\n except StopIteration:\n # ran out of letters\n pass\n\n return \"\".join(map(\"\".join, grid))\n</code></pre>\n\n<h3>Getting rid of the grid</h3>\n\n<p>At the end, the final string is read out of the grid row by row, skipping the empty cells. Notice that within a row, the column just serves to keep the letters \nin the same order as in the original string. But this can be done by keeping a string for each row. Then iterate over the string adding the letters to the end of the appropriate row.</p>\n\n<pre><code> def convert(s, numRows):\n rows = [''] * numRows\n\n letter = iter(s)\n column = 0\n\n try:\n while True:\n # fill in down a column\n for row in range(numRows):\n rows[row] += next(letter) # << append letter to the row\n\n # fill in up a diagonal\n column += 1 \n for row in range(numRows - 2, 0, -1):\n rows[row] += next(letter) # << append letter to the row\n column += 1 \n\n except StopIteration:\n # ran out of letters\n pass\n\n return \"\".join(rows)\n</code></pre>\n\n<h3>Direct calculation</h3>\n\n<p>The row number for a letter cycles through the pattern 0, 1, ..., numRows-2, numRows-1, numRows-2, ... 1, 0, 1, .... The length of the cycle is numRows + (numRows - 2) = 2*numRows - 2. So the position in a cycle can be found by <code>index % cycle_length</code>. With a little algebra, that can be converted to the row:</p>\n\n<pre><code> def convert(s, numRows):\n rows = [''] * numRows\n cycle_length = 2*numRows - 2\n\n for i,c in enumerate(s):\n row = numRows - 1 - abs(numRows - 1 - i % cycle_length)\n rows[row] += c\n\n return \"\".join(rows)\n</code></pre>\n\n<h3>Look ma, no math</h3>\n\n<p>Observe, that the row index starts at 0 and steps upward until it gets to the last row. Then it reverses direction and counts back down to 0, where it starts counting up again. Here is another take on a solution:</p>\n\n<pre><code>def convert(s, numRows):\n row = [''] * numRows\n\n index = 0\n step = 1\n\n for c in s:\n row[index] += c\n index += step\n\n # reverse step direction when hit the top or bottom row\n if index in (0, numRows-1):\n step = -step\n\n return ''.join(row)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T23:46:49.220",
"Id": "225865",
"ParentId": "225740",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "225809",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T19:52:01.893",
"Id": "225740",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"interview-questions"
],
"Title": "LeetCode ZigZag helper function code"
}
|
225740
|
<p>I'm trying to write a constructor function that generates instances of a user. One of the properties of the <code>user</code> class is an array of the user's hobbies. I'd like my constructor to have a method that generates a string representation of the array of hobbies provided to the constructor function. The goal is to create a grammatically correct sentence containing the hobbies of the <code>Person</code> instance, so if <code>interests = ['hiking', 'biking', 'skiing']</code> the <code>Person.bio()</code> method will alert something like: <code>This person's interests are: hiking, biking and skiing.</code> I am trying to account for an array of unknown length being passed to the constructor.</p>
<p>I haven't used <code>.reduce()</code> much but from the little bit of testing I've done, this seems to do what I want it to do. I'm just looking for any critiques on how to make things more readable or performant!</p>
<p>Below is a stripped down version of the constructor function (missing things like name, age, etc. for clarity). </p>
<pre class="lang-js prettyprint-override"><code>function Person(interests = []) {
this.interests = interests;
this.hobbiesSentence = interests.reduce((hobbyString, hobby, index, interests) => {
switch(index) {
case (interests.length - 1):
return hobbyString += `${hobby}.`
case (interests.length - 2):
return hobbyString += `${hobby} and `
default:
return hobbyString += `${hobby}, `
}
}, '');
this.bio = function () {
alert(`This person's interests are: ${this.hobbiesSentence}`)
};
}
</code></pre>
<p>As I'm writing this, I could see a case for making the function exist but not necessarily creating/storing the sentence unless the <code>bio()</code> method is called. Any other ideas? Thanks in advance.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T00:14:50.203",
"Id": "438449",
"Score": "2",
"body": "The word \"implementation\" is misleading; it made me think this was a reinventing-the-wheel question. Perhaps \"usage\" would make more sense here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T02:26:40.603",
"Id": "438451",
"Score": "1",
"body": "This question is pretty borderline. In the future, please don't simplify your code for the sake of posting on Code Review. See [ask]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T20:45:10.480",
"Id": "438557",
"Score": "1",
"body": "@200_success reviewed for future reference, thanks."
}
] |
[
{
"body": "<h3>Performance</h3>\n\n<p>Strings are immutable, so using <code>accumulator += stuffToAppend</code> in a loop can traditionally impact performance. The problem is that we're creating a new string every iteration, leading to quadratic time complexity for an operation that should be linear. It turns out that modern browsers optimize this heavily using an internal array to represent string parts and make it quite fast over using an explicit array, so this post is focused on style rather than performance.</p>\n\n<h3>Design</h3>\n\n<p>On first thought, <code>reduce</code> seems like the right function from a semantic standpoint since we want to boil the array of interests down to one string. However, since avoiding string concatenation requires an intermediate array in <code>reduce</code>, we might as well just skip the intermediate array and use <code>map</code> and <code>join</code>. It's pretty common that <code>reduce</code> can be replaced with <code>map</code> or <code>filter</code>, which are more specific and succinct.</p>\n\n<p>Switch statements are also generally not used much in JS (but often used in C...). You can replace many switch statements in JS with an object (particularly if you're choosing between a number of similar functions), or at least an <code>if</code> statement. Either way, the nature of the commas and \"and\" in this example makes it a bit awkward, so there doesn't seem to be any clear-cut win.</p>\n\n<p>Additionally, this routine of \"prettifying\" a list is generic and can be moved to a separate function to keep <code>Person</code> clean.</p>\n\n<p>As an aside, instead of switching between \"interests\", \"hobbies\" and \"bio\", it seems best to pick one term and stick with it throughout. </p>\n\n<p>Here's my attempt. This might seem a bit abstract, but it's typical in JS to avoid conditional/switch stuff as much as it is to avoid loops (which is the idea with <code>reduce</code>). If you prefer a more traditional approach, replace the <code>joins</code> array and indexing with an <code>if</code> statement and I'd still endorse it.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const prettyList = (a, sep=\", \", endSep=[\" and \", \".\"]) => \n a.map((e, i) => e + (endSep[endSep.length-a.length+i] || sep)).join(\"\")\n;\n\nconst Person = function (interests=[]) {\n this.interests = interests;\n this.interestsSentence = prettyList(interests);\n\n this.interestsStr = () => \n \"This person's interests are: \" + this.interestsSentence\n ;\n};\n\nconst interests = [\"foo\", \"bar\", \"baz\", \"quux\"];\n\nfor (let i = 1; i <= 4; i++) {\n console.log(new Person(interests.slice(0, i)).interestsStr());\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Now the function is reusable and we can change its behavior without much effort at all:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const prettyList = (a, sep=\", \", endSep=[\" and \", \".\"]) => \n a.map((e, i) => e + (endSep[endSep.length-a.length+i] || sep)).join(\"\")\n;\n\nconst activities = [\"biking\", \"running\", \"walking\", \"skipping\", \"driving\"];\nconsole.log(\"I love\", prettyList(activities, \"; \", [\", sometimes \", \" but not \", \"!\"]));\nconsole.log(\"I love\", prettyList(activities, \" and \", [\" while \", \" :-o\"]));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T20:38:52.800",
"Id": "438553",
"Score": "1",
"body": "Thanks for taking the time to give some real feedback. As you might expect, I'm pretty green at coding and I posted here looking for constructive ways to write more \"real world\" JS. OOP is new to me as well, so I wrote this with the idea that everything necessary to modify the \"person\" instances would be contained on the constructor object. I'll dig through your reply to make sure I understand the nuances."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T01:11:02.067",
"Id": "438898",
"Score": "0",
"body": "To me it seems that the string concatenation in your map is the same as it would be in a reduce (or just `+`). Also, what do you mean by \"intermediate array\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T01:20:50.607",
"Id": "438899",
"Score": "0",
"body": "The difference is taking an accumulator string and `resultStr += elem` versus building an array of `elem + someExtraStuff`, then joining it for the result. Traditionally, string concatenation is much slower because a totally new string is built on every iteration. Looking into it, it turns out that browsers have optimized it considerably, so it's probably not a major issue as it might be elsewhere. By \"intermediate array\", I mean that if we want to avoid string concats, we pass `[]` as the initial accumulator for `.reduce` and append each element--but wait, that's exactly what `map` does!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T02:00:37.043",
"Id": "438901",
"Score": "1",
"body": "Somehow, in my mind I thought: \"What is `join` if not string concatenation\", but I don't actually know what happens \"under the hood\". Also I was thinking giving an empty string as the initial value for the reducer (no need to assign to the accumulator there BTW, since the return value will be passed to the next invocation). But anyway, I agree that the `reduce` is a bit unwieldy here. I played around with this a little and actually ended up using a `switch` myself :D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T03:51:26.653",
"Id": "438905",
"Score": "0",
"body": "_It turns out that modern browsers optimize this heavily using an internal array_ it seems we no longer need expert developers in this world. Bad code gets optimized anyway :p"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T01:10:53.423",
"Id": "225747",
"ParentId": "225743",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "225747",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T21:21:55.310",
"Id": "225743",
"Score": "2",
"Tags": [
"javascript",
"object-oriented",
"functional-programming",
"formatting",
"constructor"
],
"Title": "Constructor function for persons with hobbies"
}
|
225743
|
<p>I had the need to prefix the price for certain product categories on only the shop page (because the price can be higher depending on extras that the customer might want).</p>
<p>These were my requirements for this code:</p>
<ul>
<li>Add the prefix only on the shop page, not on the product page;</li>
<li>Only add the prefix to certain (hardcoded) product categories.</li>
</ul>
<p>I'd like some advice on possible improvements and certainly about possible security risks, if there are any.</p>
<p>Along with that, I've heard that globals are considered bad practise, but I see them a lot in Wordpress. What are the alternatives, if there's any.</p>
<p>This is the code:</p>
<pre><code>add_filter('woocommerce_get_price_html', 'change_product_price_html');
function change_product_price_html($price){
// Check if we're on the shop page
// Don't want the prefix on the product pages.
if( is_shop() ) {
global $product;
// ID of categories to add the prefix to
$categories = ["17"];
// Loop through all the category ID's if they equal one of the values
// in the array, add the prefix.
foreach( $product->get_category_ids() as $id ) {
if( in_array($id, $categories) ) {
// Add prefix
$prefixedPrice = "<span class='woocommerce-Price-amount amount'>Starting at </span>";
$prefixedPrice .= $price;
return $prefixedPrice;
}
}
// Nothing matched in the loop,
// return the price without the prefix.
return $price;
}
// We're not on the shop page so
// return the price without the prefix.
return $price;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T03:11:14.793",
"Id": "438453",
"Score": "0",
"body": "If `categories` becomes an array of two elements, your code will break due to the early return in your foreach loop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T10:05:51.120",
"Id": "438477",
"Score": "0",
"body": "And is that purely because I'm returning something in the loop? Because a product can have multiple categories, but as soon as 1 of them matches, I want to add the prefix. They don't all have to match."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T10:25:08.263",
"Id": "438478",
"Score": "0",
"body": "Okay, I didn't understand that logic in your script. If that early return on the first qualifying occurrence is desired then no problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T10:26:40.450",
"Id": "438479",
"Score": "0",
"body": "Yeah my bad for not adding it to the post, thanks! Any advice about the usage of `global $product;` ?"
}
] |
[
{
"body": "<p>You could reduce your script to this: (untested)</p>\n<pre><code>add_filter('woocommerce_get_price_html', 'change_product_price_html');\nfunction change_product_price_html($product, $price) {\n $categories = ["17"];\n if (!is_shop() || !array_intersect_key(array_flip($product->get_category_ids()), array_flip($categories))) {\n return $price;\n }\n return "<span class=\\"woocommerce-Price-amount amount\\">Starting at </span>{$price}";\n}\n</code></pre>\n<ul>\n<li><p>pass the <code>$product</code> into the custom function's scope as an argument to avoid the global declaration.</p>\n</li>\n<li><p>merge the un-prefixed return conditions into a single expression.</p>\n</li>\n<li><p>while only a benchmark executed on your system will tell the real truth, I am employing a key-based comparison between two arrays. The downside is that it may do more work than it needs to (by finding multiple matches). The good news is, it is not going to perform multiple full array scans like a looped <code>in_array()</code> technique might. I'm not going to be too pushy about how to best compare the two category arrays -- I just wanted to show an alternative.</p>\n</li>\n</ul>\n<p>Alternatively, this will be an easier array-to-array comparison to read:</p>\n<pre><code>if (!is_shop() || !array_intersect($product->get_category_ids(), $categories)) {\n return $price;\n}\n</code></pre>\n<p>I assume you were calling your posted function like <code>change_product_price_html($price);</code>.</p>\n<p>To add the <code>$product</code> variable as the first expected argument, call my custom function like this:</p>\n<pre><code>change_product_price_html($product, $price);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T17:50:42.807",
"Id": "438768",
"Score": "0",
"body": "Thanks, looks clean! How do I pass `$product` into the function? I added it to the custom function as an argument (website doesn't load), but that doesn't work. I assume I have to declare it somewhere, but where?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T21:41:48.333",
"Id": "438793",
"Score": "0",
"body": "Updated my answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T11:02:28.063",
"Id": "225758",
"ParentId": "225745",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T22:52:55.247",
"Id": "225745",
"Score": "2",
"Tags": [
"php",
"wordpress"
],
"Title": "Prefixing prices of certain product categories with text in Woocommerce"
}
|
225745
|
<p>I have an Android project that queries the BART train API. I was curious if updating the UI inside the Retrofit onResponse method is correct or if there is a better way. Below is my code. Also, here is the GitHub <a href="https://github.com/jmcs811/BartApp/tree/dev?files=1" rel="nofollow noreferrer">link</a> if you want to look at a different file. If there are any other issues you see please let me know. I welcome any and all feedback.</p>
<pre><code>ublic class StationListFragment extends Fragment {
private StationList testList;
private RecyclerView recyclerView;
private StationListAdapter adapter;
public StationListFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View v = inflater.inflate(R.layout.fragment_station_list, container, false);
// Set up RecyclerView
recyclerView = v.findViewById(R.id.station_list_recycler);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setHasFixedSize(true);
recyclerView.addItemDecoration(new DividerItemDecoration(recyclerView.getContext(), DividerItemDecoration.VERTICAL));
// Make API call with retrofit
ApiInterface service = RetrofitClient.getClient().create(ApiInterface.class);
Call<StationList> call = service.getStations();
call.enqueue(new Callback<StationList>() {
@Override
public void onResponse(Call<StationList> call, Response<StationList> response) {
// populate recycler view with the list of stations.
if (response.isSuccessful()) {
testList = response.body();
adapter = new StationListAdapter(getContext(), testList.getRoot().getStations().getStation());
recyclerView.setAdapter(adapter);
Log.d("TAG: RESPONSE", new GsonBuilder().setPrettyPrinting().create().toJson(response));
} else {
int statusCode = response.code();
Log.d("TAG: STATUSCODE", Integer.toString(statusCode));
}
}
@Override
public void onFailure(Call<StationList> call, Throwable t) {
Log.d("TAG: FAILURE", t.getMessage());
}
});
return v;
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T23:41:55.350",
"Id": "225746",
"Score": "2",
"Tags": [
"java",
"android",
"json"
],
"Title": "Updating UI in Retrofit onResponse"
}
|
225746
|
<p>I've written a small program that calculates Arithmetic and Geometric Partial Sums. I'd like feedback on anything possible, since I intend on writing a cheatsheet that encapsulates all PreCalculus equations.</p>
<p><strong>partial_sum.py</strong></p>
<pre><code>"""
This is a program that calculates arithmetic and geometric
partial sums
"""
from fractions import Fraction
def find_an(parsed_series):
"""
Finds an in the passed parsed arithmetic series
:param parsed_series: The series to be analyzed
"""
for i, _ in enumerate(parsed_series):
if parsed_series[i] == ".":
return int(parsed_series[i + 1])
return None
def arithmetic_partial_sum(series):
"""
Returns the partial sum of an arithmetic series
Formula:
S = n( (a1 + an) / 2 )
Find an:
an = a1 + (n - 1)d
Find n:
n = 1 + ( (an - a1) / d )
:param series: Arithmetic series to solve
"""
series = series.split("+")
a1 = int(series[0])
d = int(series[1]) - a1
an = find_an(series)
n = 1 + ((an - a1) / d)
S = n * ((a1 + an) / 2)
return S
def geometric_partial_sum(series):
"""
Returns the partial sum of the geometric series
:param series: Geometric series to solve
Formula:
S = (a1 * (1 - (r ** n))) / (1 - r)
"""
series = series.split("+")
a1 = int(series[0])
r = int(series[1]) / a1
n = len(series)
S = (a1 * (1 - (r ** n))) / (1 - r)
return str(Fraction(S).limit_denominator())
if __name__ == '__main__':
A_SERIES = "3+7+11+15+.+99"
G_SERIES = f"3+1+{1/3}+{1/9}+{1/27}+{1/81}"
print(arithmetic_partial_sum(A_SERIES))
print(geometric_partial_sum(G_SERIES))
</code></pre>
|
[] |
[
{
"body": "<p><code>find_an()</code> looks like an internal function, used by <code>arithmetic_partial_sum()</code>. If it is not for external use, it should be named with a leading underscore, to suggest it is private.</p>\n\n<hr>\n\n<p><code>arithmetic_partial_sum()</code> appears to handle only integer values, yet it return a floating-point value (<code>1275.0</code> in the built-in example). It should return an integer, since it is adding up integers. Use the Python3.x integer-division operator: <code>//</code>.</p>\n\n<pre><code> n = 1 + (an - a1) // d\n S = n * (a1 + an) // 2\n</code></pre>\n\n<p>Or, not assume the terms are integer, and use <code>float(...)</code> instead.</p>\n\n<hr>\n\n<p><code>geometric_partial_sum()</code> fails if the first 2 values are not <code>int</code> values:</p>\n\n<pre><code>>>> geometric_partial_sum(f\"1+{1/3}+{1/9}+{1/27}+{1/81}\")\nTraceback (most recent call last):\n File \"<pyshell#1>\", line 1, in <module>\n geometric_partial_sum(f\"1+{1/3}+{1/9}+{1/27}+{1/81}\")\n File \"...\\partial_sum.py\", line 63, in geometric_partial_sum\n r = int(series[1]) / a1\nValueError: invalid literal for int() with base 10: '0.3333333333333333'\n</code></pre>\n\n<p>You should convert the terms to floating-point values, not integers:</p>\n\n<pre><code> a1 = float(series[0])\n r = float(series[1]) / a1\n</code></pre>\n\n<hr>\n\n<p><code>find_an()</code> assumes <span class=\"math-container\">\\$a_n\\$</span> is immediately after the <code>'.'</code> term, so will fail with:</p>\n\n<pre><code>arithmetic_partial_sum(\"3+7+11+15+.+95+99\")\narithmetic_partial_sum(\"3+7+11+15+19\")\n</code></pre>\n\n<p>Why not just retrieve the last term?</p>\n\n<pre><code>def find_an(parsed_series):\n return int(parsed_series[-1])\n</code></pre>\n\n<p>Now the following all succeed and return the correct values</p>\n\n<pre><code>arithmetic_partial_sum(\"3+7+11+15+.+95+99\")\narithmetic_partial_sum(\"3+7+11+15+...+95+99\")\narithmetic_partial_sum(\"3+7+11+15+19\")\n</code></pre>\n\n<hr>\n\n<p>The <code>\"\"\"docstrings\"\"\"</code> for <code>arithmetic_partial_sum()</code> and <code>geometric_partial_sum()</code> appear unhelpful. For example:</p>\n\n<pre><code>>>> help(arithmetic_partial_sum)\nHelp on function arithmetic_partial_sum in module __main__:\n\narithmetic_partial_sum(series)\n Returns the partial sum of an arithmetic series\n\n Formula:\n S = n( (a1 + an) / 2 )\n\n Find an:\n an = a1 + (n - 1)d\n\n Find n:\n n = 1 + ( (an - a1) / d )\n\n :param series: Arithmetic series to solve\n</code></pre>\n\n<p>The function is not returning <code>an</code> or <code>n</code>. Even the formula is not particularly helpful. <code>\"\"\"docstrings\"\"\"</code> should tell a user how to use the function. For example (adding Python 3.6 type hints as well):</p>\n\n<pre><code>def arithmetic_partial_sum(series:str) -> int:\n \"\"\"\n Returns the sum of an arithmetic series\n\n Example:\n s = arithmetic_partial_sum(\"1+3+5+.+99\") # returns 2500\n\n :param series: A string representing the arithmetic series to solve\n \"\"\"\n</code></pre>\n\n<p>Now type <code>help(arithmetic_partial_sum)</code>:</p>\n\n<pre><code>>>> help(arithmetic_partial_sum)\nHelp on function arithmetic_partial_sum in module __main__:\n\narithmetic_partial_sum(series: str) -> int\n Returns the sum of an arithmetic series\n\n Example:\n s = arithmetic_partial_sum(\"1+3+5+.+99\") # returns 2500\n\n :param series: A string representing the arithmetic series to solve\n</code></pre>\n\n<p>The user is told the function takes a string and returns an integer. The format of the string should be clear from the example.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T22:25:14.877",
"Id": "225799",
"ParentId": "225748",
"Score": "4"
}
},
{
"body": "<p>One thing to also include is the fact that it also doesn't support series in which each term alternates between positive and negative as the <code>series = series.split(\"+\")</code></p>\n\n<p>For example in an arithmetic series like <code>5+3+1-1-3</code> with a common difference of -2, \nthe way the <code>series = series.split(\"+\")</code> is set up, will make it detect <code>1-1-3</code> as a single term.</p>\n\n<p>And in geometric terms, for example: <code>9-3+1-(1/3)+(1/9)</code>, it will again fail to detect the <code>-</code> and mistake <code>9-3</code> and <code>1-(1/3)</code> as complete terms.</p>\n\n<p>A viable solution is to separate every term whether negative or not by a <code>+</code>.\nUsing the two examples above:</p>\n\n<ul>\n<li>Arithmetic: <code>\"5+3+1+-1+-3\"</code></li>\n<li>Geometric: <code>f\"9+-3+1+-{1/3}+{1/9}\"</code></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T18:14:55.827",
"Id": "238054",
"ParentId": "225748",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "225799",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T05:21:42.113",
"Id": "225748",
"Score": "8",
"Tags": [
"python",
"python-3.x",
"math-expression-eval"
],
"Title": "Arithmetic/Geometric series calculator"
}
|
225748
|
<p>I have implemented selection sort in java using arraylist. This selection sort is only for integers . Please have a look and give feedback. can we improve it ?</p>
<pre><code>package selectionSort;
import java.util.ArrayList;
import java.util.Scanner;
public class SelectionSort {
private ArrayList<Integer> num_sort=new ArrayList<>();
public SelectionSort(ArrayList<Integer> userlist) {
this.num_sort=userlist;
sort_select();
}
public void sort_select() {
//outer for loop to pick one element at a time
//e.g if list is 20,12,3,4,5,6,98----this loop will first pick 20
for(int i=0;i<this.num_sort.size();i++) {
//assign that element as minimum
//in our e.g 20 will be assigned min in first iteration
int min=this.num_sort.get(i);
int min_index=i;
//go over the rest of the list and compare minimum by rest of list. if number smaller than min is found, then it is assigned as new min
//so go over list starting from 12 and comparing 20 with each of them and finding the new min, in this case it will be 3
for(int j=i+1;j<this.num_sort.size();j++) {
if(this.num_sort.get(j)<min) {
min=this.num_sort.get(j);
min_index=j;
}
}
if(i!=min_index) {
exchange(i,min_index);
}
}
System.out.println("Sorted entered are : ");
for(int x:this.num_sort) {
System.out.print(x+" ");
}
}
// exchange the element at ith position with min
public void exchange(int current_elem,int new_min) {
int temp=this.num_sort.get(current_elem);
this.num_sort.set(current_elem, this.num_sort.get(new_min));
this.num_sort.set(new_min, temp);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter how many numbers you want to sort");
Scanner in=new Scanner(System.in);
int num_count=in.nextInt();
System.out.println("Enter the numbers you want to sort");
ArrayList<Integer> userlist=new ArrayList<>();
for(int i=0;i<num_count;i++) {
userlist.add(in.nextInt());
}
SelectionSort s=new SelectionSort(userlist);
}
</code></pre>
<p>}</p>
|
[] |
[
{
"body": "<h2>Style</h2>\n\n<ol>\n<li>Use proper styling. You should use more whitespaces, this will make your code more readable. Instead of <code>num_sort=new</code> use <code>num_sort = new</code>, insead of <code>i!=min_index</code> use <code>i != min_index</code>, etc</li>\n<li>Follow the Java naming conventions: variable and function names should use <em>camelCase</em>, not <em>snake_case</em>. </li>\n<li>You should include documentation that explains the user how the class is used. For example, without looking at the code I would not expect that creating a new instance of the class automatically sorts the list, so it is something you must make clear in the documentation.</li>\n</ol>\n\n<h2>Comments</h2>\n\n<p>Commenting the code is good, but too many comments can make a simple function look complicated. The general rule is that <strong>code tells you how, comments tell you why</strong>.</p>\n\n<p>For example, I think <code>int min = this.num_sort.get(i);</code> does not need to be commented; it's pretty clear that you are getting the <em>i-th</em> item of the list.</p>\n\n<p>Also, leave a whitespace between <code>//</code> and the text, it's more readable.</p>\n\n<h2>Code structure</h2>\n\n<p>It does not make sense to have this in a class; <code>new SelectionSort(userlist)</code> is not the way someone would expect to sort a list. I am going to make some recommendations that for the class design, but for the rest of the review I will restructurate the code so that it is more conventional.</p>\n\n<p>As a user I expect <code>select_sort</code> to sort the list and that's all; I decide whether I want to print the list or not (what if I want to print it differently to you?). So you should move the printing code to the <code>main</code> function.</p>\n\n<h3>Class design</h3>\n\n<p>If you were to continue with the current class design, there must be some changes:</p>\n\n<ol>\n<li>Do not sort the list in the construction. It is not the expected behaviour. Let the user call <code>sortSelect()</code>. Actually, I think <code>selectionSort()</code> would be a better name.</li>\n<li>Is <code>exchange</code> a method that is meant to be used by the user? I don't think so, so make it <code>private</code> instead of <code>public</code> so only the class code can use it.</li>\n<li><code>num_sort</code> does not seem like an intuitive name; I had to look at the code to know what it is. Just calling it <code>list</code> would be better.</li>\n<li>You don't care how the list is internally implemented, you only care that it is a list. So use the more generic <code>List</code> interface instead of <code>ArrayList</code>.</li>\n<li>You are assigning your list twice: on <code>num_sort=new ArrayList<>()</code> and on <code>this.num_sort=userlist;</code>. The first one is not necessary, because it will always be replaced in the constructor. Furthermore, since you never reassign the list again, you should declare it <code>final</code>.</li>\n</ol>\n\n<pre class=\"lang-java prettyprint-override\"><code>private final List<Integer> list;\n\npublic SelectionSort(List<Integer> userList) {\n this.list = userList;\n}\n</code></pre>\n\n<h3>Alternative design</h3>\n\n<ol>\n<li>In my opinion, your selection sort algorithm should just be one <code>static</code> method that takes the list as input. That would make it similar to the <code>Collections.sort()</code> method that already exists in Java.</li>\n<li><code>Scanner</code> is a resource that must be closed. You can make Java close it automatically by using a <a href=\"https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow noreferrer\">try with resources</a>.</li>\n</ol>\n\n<pre class=\"lang-java prettyprint-override\"><code>try (Scanner in = new Scanner(System.in)) {\n // your code\n}\n</code></pre>\n\n<ol start=\"3\">\n<li>You can still keep the convenience method <code>exchange</code> (as <code>static</code> and taking the list as parameter), but since it is quite short and you only call it in one place I think you could just write the code directly. If you decide to keep the function, I would change the parameter names to just <code>i</code> and <code>j</code>, and the method name to <code>swap</code> (it's more common). Since it's the same doing <code>exchange(current_elem, new_min)</code> than <code>exchange(new_min, current_elem)</code> those parameter names do not make much sense. BUT you don't even need to implement that method, you can just use <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#swap-java.util.List-int-int-\" rel=\"nofollow noreferrer\"><code>Collections.swap()</code></a></li>\n</ol>\n\n<h2>Final code</h2>\n\n<pre class=\"lang-java prettyprint-override\"><code>/**\n * Sorts the given list using a selection sort algorithm.\n * @param list The list to be sorted.\n */\npublic static void selectionSort(final List<Integer> list) {\n // outer for loop to pick one element at a time\n // e.g if list is 20,12,3,4,5,6,98----this loop will first pick 20\n for (int i = 0; i < list.size(); i++) {\n int min = list.get(i);\n int minIndex = i;\n // Go over the rest of the list and compare minimum by rest of list. If number smaller than min is found, then it is assigned as new min\n // So go over list starting from 12 and comparing 20 with each of them and finding the new min, in this case it will be 3\n for (int j = i + 1; j < list.size(); j++) {\n if (list.get(j) < min) {\n min = list.get(j);\n minIndex = j;\n }\n }\n if (i != minIndex) {\n Collections.swap(list, i, minIndex);\n }\n }\n}\n\n\npublic static void main(String[] args) {\n try (Scanner in = new Scanner(System.in)) {\n System.out.println(\"Enter how many numbers you want to sort\");\n int count = in.nextInt();\n\n System.out.println(\"Enter the numbers you want to sort\");\n List<Integer> list = new ArrayList<>();\n for(int i = 0; i < count; i++) {\n list.add(in.nextInt());\n }\n\n selectionSort(list);\n\n System.out.println(\"Sorted entered are: \");\n for (int x : list) {\n System.out.print(x + \" \");\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T08:49:08.093",
"Id": "438469",
"Score": "0",
"body": "thanks for your comments @eric.m. Will take care of all these"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T08:41:33.560",
"Id": "225754",
"ParentId": "225751",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "225754",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T07:06:44.427",
"Id": "225751",
"Score": "2",
"Tags": [
"java",
"sorting"
],
"Title": "Selection Sort Java -Arraylist"
}
|
225751
|
<p>I have written a filter that intercepts http calls and logs request parameters. </p>
<pre><code>public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException,
ServletException
{
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
String uri = httpRequest.getRequestURI();
String queryString = httpRequest.getQueryString();
long startTime = System.currentTimeMillis();
if (shouldBeRedirected(uri)) {
String type = getType(uri);
String redirectUrl = Util.getURLBasedUponStabilityLevel(Constants.STABILITY_LEVEL);
((HttpServletResponse) response).sendRedirect(redirectUrl + type);
return;
}
filterChain.doFilter(httpRequest, httpResponse);
long endTime = System.currentTimeMillis();
Timestamp startTimestamp = Timestamp.getInstance(startTime);
StringBuilder logString = new StringBuilder();
logString.append("Request URL: ");
logString.append(uri);
logString.append(" Query String: ");
logString.append(queryString);
logString.append(" Session Id: ");
logString.append(httpRequest.getRequestedSessionId());
logString.append(" Took: ");
logString.append(endTime - startTime);
logString.append("milliseconds. ");
logString.append(" StartTime: ");
logString.append(startTimestamp);
if(httpRequest.getMethod().equals("POST")){
JSONObject postParameters = new JSONObject();
Map parameterMap = httpRequest.getParameterMap();
Iterator<Map.Entry<String, String[]>> it = parameterMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String[]> entry = it.next();
if(entry.getValue().length == 1){
postParameters.put(entry.getKey(), entry.getValue()[0].toString());}
else{
JSONArray valueList = new JSONArray();
for(String value : entry.getValue()){
valueList.add(value.toString());
}
postParameters.put(entry.getKey(), valueList);
}
}
logString.append(" Post Parameters: ");
logString.append(postParameters.toString());
}
LOG.info(logString.toString());
}
</code></pre>
<p>Code looks a bit clumsy to me, any suggestions to improve this?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T05:08:37.283",
"Id": "438576",
"Score": "0",
"body": "There are better ways to transform your map of parameters into json or just a string in general. This stackoverflow post has a lot of great suggestions. https://stackoverflow.com/questions/10120273/pretty-print-a-map-in-java"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-13T10:40:46.207",
"Id": "457501",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] |
[
{
"body": "<p>The redirect doesn't seem to be part of the logging. Maybe put it in a separate filter that runs before this one?</p>\n\n<p>The logged string could be built using <code>String.format()</code> or <code>MessageFormat</code> which would be more readable. Most logging frameworks have such formatting built into their logging methods anyway.</p>\n\n<p>Do you really need to convert the post parameters into JSON? Isn't the standard <code>toString</code> representation of the <code>Map</code> good enough for logging? Apart from that most JSON libraries have a built-in mechanism to convert a <code>Map</code> into a JSON object so you don't need to do it yourself.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T11:16:03.257",
"Id": "225760",
"ParentId": "225757",
"Score": "2"
}
},
{
"body": "<p>Elaborating on RoToRa's comments:</p>\n\n<ol>\n<li><p>If you are going to build a string by concatenation, then using a string builder like that only improves performance if there is a loop. That doesn't apply here. So your code could be written as:</p>\n\n<pre><code>String logString = \"Request URL: \") + uri + \" Query String: \" + queryString\n + \" Session Id: \" + httpRequest.getRequestedSessionId() + \" Took: \"\n + (endTime - startTime) + \" milliseconds. \" + \" StartTime: \"\n + startTimestamp \n + (httpRequest.getMethod().equals(\"POST\") ? \n httpRequest.getParameterMap() : \"\");\nLOG.info(logString);\n</code></pre></li>\n<li><p>You should be using a format String and parameters; e.g.</p>\n\n<pre><code>LOG.info(\"Request URL: {} Query String: {} Session Id: {} Took: {} \" +\n \"milliseconds. StartTime: {} {}\",\n uri, queryString, httpRequest.getRequestedSessionId(), \n (endTime - startTime), startTimestamp,\n (httpRequest.getMethod().equals(\"POST\") ?\n httpRequest.getParameterMap() : \"\"));\n</code></pre>\n\n<p>This is not just neater. It is also a lot more efficient, since the work of interpolating the parameters into the format will <em>only</em> happen if \"info\" level logging is enabled.</p>\n\n<p>(Just using <code>String.format</code> is not the solution ...)</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T18:19:11.983",
"Id": "438543",
"Score": "0",
"body": "As per my understanding \"Request URL: \") + uri will create a string object say str1 then str1 + \" Query String: \" will create another string object ..... and hence we will end up creating lots of throwaway strings. Isn't this suboptimal?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T18:22:12.950",
"Id": "438544",
"Score": "0",
"body": "Also, I am confused after your answer (#1 and #2 above can't be done at the same time right?). If I am creating logString then why will I use format string? can you please provide the complete snippet with optimizations you feel are correct?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T23:24:25.403",
"Id": "438570",
"Score": "0",
"body": "Your understanding is incorrect. The Java compiler optimizes a simple sequence of concatenations to use a string builder. You don't need to do it yourself. You only need to resort to using `StringBuilder` explicitly in cases involving loops that the compiler doen't optimize."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T23:26:33.967",
"Id": "438571",
"Score": "0",
"body": "You are correct that you do #1 or #2, not both. The code snippets in my answer are more or less complete replacements for your code."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T13:26:30.587",
"Id": "225764",
"ParentId": "225757",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T09:53:29.890",
"Id": "225757",
"Score": "1",
"Tags": [
"java",
"http",
"logging"
],
"Title": "Filter for logging http request parameters"
}
|
225757
|
<p>I wrote a general purpose file compression program out of curiosity, but I am concerned about readability. I don't know if the variable names are useful, and whether most of the comments are unneeded or not, so any advice/criticism is welcome.</p>
<p>You can check the <a href="https://github.com/vkyriakakis/fg2019-file-compressor" rel="noreferrer">repo</a>, for more information.</p>
<h2>const.h</h2>
<pre><code>
#ifndef CONST_GUARD
#define CONST_GUARD
/* The total number of possible symbols,
meaning all possible 256 byte values and the
special EOF symbol, defined to make decompression easier. */
#define SYM_NUM 257
// Size of an integer in bits.
#define INT_SIZE sizeof(int)*8
#endif
</code></pre>
<h2>codes.h</h2>
<pre><code>#ifndef CODE_GUARD
#define CODE_GUARD
#include "const.h"
#define MAX_CODELEN 12 // Max length of prefix codes
#define DECOMP_SIZE (1 << MAX_CODELEN) // Size of lookup array (2^max)
// prefixNodeT: Huffman tree node
struct huffmanNode {
// freq: The frequency of the symbol corresponding to the node
size_t freq;
struct huffmanNode *left;
struct huffmanNode *right;
/* symbol: For a leaf node, the symbol correspoding to the node,
for an inner node it isn't used. */
unsigned int symbol;
};
typedef struct huffmanNode huffmanNodeT;
/* compTableT: Lookup table used in compression,
contains the prefix code and value for a given symbol.
So, compression using the table is done by getting the
(val, len) code pair for every byte of the original file. */
typedef struct {
// Vals, lens are indexed by symbol numeric value
unsigned int vals[SYM_NUM];
int lens[SYM_NUM]; //in bits
} compTableT;
/* decompTableT: Lookup table used in decompression, as described in
https://commandlinefanatic.com/cgi-bin/showarticle.cgi?article=art007 */
typedef struct {
char codeLens[DECOMP_SIZE]; //in bits
int symbols[DECOMP_SIZE];
} decompTableT;
/* initCompressionTable(): Initialize the lookup table used in compression.
Input:
> compTablePtr: Pointer to the compression table
> freqs: Array containing the appearance frequency of all the symbols
Output:
>
>
Assumptions:
> compTablePtr != NULL
*/
int initCompressionTable(compTableT *compTablePtr, size_t freqs[SYM_NUM]);
/* initDecompressionTable(): Initialize the lookup table used in decompression.
Assumptions:
> decompTablePtr != NULL
*/
int initDecompressionTable(decompTableT *decompTablePtr, int codeLens[SYM_NUM]);
#endif
</code></pre>
<h2>codes.c</h2>
<pre><code>#include <stdlib.h>
#include "const.h"
#include "minQueue.h"
#include "error.h"
#include "codes.h"
/* symbolT: Contains a symbol and the prefix code corresponding to it.
Needed to maintain the symbol -> (len,val) mapping after sorting. */
typedef struct {
unsigned int symbol;
unsigned int codeVal;
int codeLen;
} symbolT;
// initLeafNode(): Initalizes a leaf node of the Huffman tree.
huffmanNodeT *initLeafNode(unsigned int symbol, size_t freq) {
huffmanNodeT *leaf = malloc(sizeof(huffmanNodeT));
if (!leaf) {
reportError("malloc", __FILE__, __LINE__);
return NULL;
}
leaf->symbol = symbol;
leaf->left = leaf->right = NULL;
leaf->freq = freq;
return leaf;
}
/* initInnerNode: Initializes an inner node of the Huffman tree
(corresponds to a composite symbol). */
huffmanNodeT *initInnerNode(huffmanNodeT *left, huffmanNodeT *right) {
huffmanNodeT *node = malloc(sizeof(huffmanNodeT));
if (!node) {
reportError("malloc", __FILE__, __LINE__);
return NULL;
}
node->left = left;
node->right = right;
node->freq = left->freq + right->freq;
return node;
}
/* freeHuffmanTree(): Frees the Huffman tree.
Assumes that root != NULL. */
void freeHuffmanTree(huffmanNodeT *root) {
if (root->left != NULL)
freeHuffmanTree(root->left);
if (root->right != NULL)
freeHuffmanTree(root->right);
free(root);
}
/* initHuffmanTree(): Uses the textbook Huffman coding algorithm to initialize
the Huffman tree, using the frequencies of all the symbols. */
huffmanNodeT *initHuffmanTree(size_t freqs[SYM_NUM]) {
minQueueT minQueue;
huffmanNodeT **initialNodes;
huffmanNodeT *node1, *node2, *newNode, *huffmanRoot;
int nonZeroTotal = 0;
int k, t;
/* Initialize the array of the initial nodes, excluding the symbols with freq = 0
so that they will not waste heap operations. */
for (k = 0 ; k < SYM_NUM ; k++)
if (freqs[k] != 0)
nonZeroTotal++;
initialNodes = malloc(sizeof(huffmanNodeT*)*nonZeroTotal);
if (!initialNodes) {
reportError("malloc", __FILE__, __LINE__);
return NULL;
}
for (t = 0, k = 0 ; k < SYM_NUM ; k++) {
if (freqs[k]) {
initialNodes[t] = initLeafNode(k, freqs[k]);
if (!initialNodes[t]) {
reportError("malloc", __FILE__, __LINE__);
return NULL;
}
t++;
}
}
/* Use the array to initialize the min queue used in the algorithm,
no more than nonZeroTotal positions are needed in the min queue,
as in each step 2 symbols merge into 1, so #symbols =< nonZeroTotal. */
minQueueInit(&minQueue, initialNodes, nonZeroTotal);
while (minQueue.nodeTotal > 1) {
node1 = delMin(&minQueue);
node2 = delMin(&minQueue);
newNode = initInnerNode(node1, node2);
if (!newNode) {
reportError("malloc", __FILE__, __LINE__);
return NULL;
}
minQueueIns(&minQueue, newNode);
}
/* Remove the root from the min queue, before freeing the queue's array,
as the array is used in the minQueue, not a copy. */
huffmanRoot = delMin(&minQueue);
free(initialNodes);
return huffmanRoot;
}
/* compHuffmanLens(): Computes the Huffman code length correspoding to each
symbol by recursively traversing the symbol tree.
Assumptions:
> codeLens = 0 when the function is called outside itself.
> symbols[] is sorted in such a way that symbols[k].symbol == k, where k is a symbol. */
void compHuffmanLens(huffmanNodeT *huffmanNode, symbolT symbols[SYM_NUM], int codeLen) {
if (huffmanNode->left == NULL && huffmanNode->right == NULL) {
symbols[huffmanNode->symbol].codeLen = codeLen;
return;
}
if (huffmanNode->left != NULL)
compHuffmanLens(huffmanNode->left, symbols, codeLen+1);
if (huffmanNode->right != NULL)
compHuffmanLens(huffmanNode->right, symbols, codeLen+1);
}
// lenComp(): For use in qsort(), compares 2 symbols by code length.
int lenComp(const void *ptr1, const void *ptr2) {
symbolT sym1 = *((symbolT*)ptr1);
symbolT sym2 = *((symbolT*)ptr2);
return sym1.codeLen - sym2.codeLen;
}
/* lenThenLexComp(): For use in qsort(), first compares 2 symbols by code length, then
lexicographically (by their numeric values). */
int lenThenLexComp(const void *ptr1, const void *ptr2) {
symbolT sym1 = *((symbolT*)ptr1);
symbolT sym2 = *((symbolT*)ptr2);
int diff = sym1.codeLen - sym2.codeLen;
if (diff != 0)
return diff;
return sym1.symbol - sym2.symbol;
}
/* limitCodeLens(): Limits code lengths to MAX_CODELEN, using the heuristic algorithm
detailed here http://cbloomrants.blogspot.com/2010/07/07-03-10-length-limitted-huffman-codes.html,
in order for the decompression lookup table scheme to be used.
Assumptions:
> symbols[] is sorted by increasing codeLen.
*/
void limitCodeLens(symbolT symbols[SYM_NUM]) {
// kraftSum: The sum of 1 / 2^codeLen that appears in Kraft's inequality.
double kraftSum = 0;
int k;
/* 1. In the following loops, symbols with codeLen = 0 are ignored,
because they do not appear in the file to be compressed.
2. Casting to double is used to compute the Kraft inequality sum without
using pow() from math.h */
for (k = 0 ; k < SYM_NUM ; k++) {
if (symbols[k].codeLen) {
if (symbols[k].codeLen > MAX_CODELEN)
symbols[k].codeLen = MAX_CODELEN;
kraftSum += 1 / (double)(1 << symbols[k].codeLen);
}
}
for (k = SYM_NUM-1 ; k >= 0 ; k--)
while (symbols[k].codeLen && symbols[k].codeLen < MAX_CODELEN && kraftSum > 1 ) {
symbols[k].codeLen++;
kraftSum -= 1 / (double)(1 << symbols[k].codeLen);
}
for (k = 0 ; k < SYM_NUM ; k++)
while (symbols[k].codeLen && (kraftSum + 1 / (double)(1 << symbols[k].codeLen)) <= 1) {
kraftSum += 1 / (double)(1 << symbols[k].codeLen);
symbols[k].codeLen--;
}
}
/* computeCodeVals(): Compute prefix code values using the Canonical Huffman code
generation algorithm.
Assumptions:
> symbols[] is sorted by increasing codeLen and then lexicographically (this is needed in order
to enforce the same ordering of symbols with equal lengths during compression and decompression, so
that the same code values are produced).
*/
void computeCodeVals(symbolT symbols[SYM_NUM]) {
int prevLen, prevVal = 0;
int k;
for (k = 0 ; k < SYM_NUM ; k++)
if (symbols[k].codeLen) {
symbols[k].codeVal = 0;
prevLen = symbols[k].codeLen;
break;
}
for (k++ ; k < SYM_NUM ; k++)
if (symbols[k].codeLen) {
prevVal = symbols[k].codeVal = (prevVal + 1) << (symbols[k].codeLen - prevLen);
prevLen = symbols[k].codeLen;
}
}
/* initCompressionTable(): Initialize the lookup table used in compression.
Assumptions:
> compTablePtr != NULL
*/
int initCompressionTable(compTableT *compTablePtr, size_t freqs[SYM_NUM]) {
huffmanNodeT *huffmanRoot;
symbolT symbols[SYM_NUM];
int k;
huffmanRoot = initHuffmanTree(freqs);
if (!huffmanRoot)
return -1;
// Iterate over all of the symbols and init symbols[]
for (k = 0 ; k < SYM_NUM ; k++) {
symbols[k].symbol = k;
/* Not computed yet, codeLen init to 0 in order to indicate
a symbol that does not appear in the file to be compressed. */
symbols[k].codeLen = 0;
symbols[k].codeVal = 0;
}
compHuffmanLens(huffmanRoot, symbols, 0);
// The tree is not needed anymore
freeHuffmanTree(huffmanRoot);
// Sort symbol array by increasing code length, needed by limitCodeLens()
qsort(symbols, SYM_NUM, sizeof(symbolT), lenComp);
limitCodeLens(symbols);
qsort(symbols, SYM_NUM, sizeof(symbolT), lenThenLexComp);
computeCodeVals(symbols);
// Fill the compression table
for (k = 0 ; k < SYM_NUM ; k++) {
/* symbols[k].symbol is used as the index
and not k, because due to the above sorting
symbols[k].symbols != k in the general case. */
compTablePtr->lens[symbols[k].symbol] = symbols[k].codeLen;
compTablePtr->vals[symbols[k].symbol] = symbols[k].codeVal;
}
return 0;
}
/* initDecompressionTable(): Initialize the lookup table used in decompression.
Assumptions:
> decompTablePtr != NULL
*/
int initDecompressionTable(decompTableT *decompTablePtr, int codeLens[SYM_NUM]) {
symbolT symbols[SYM_NUM];
int k, j;
/*
leftVal: The codeVal of the currently checked symbol left shifted,
so that the codeLen least significant bits become the most
significant.
leftIdx: The current value of index left shifted,
so that the MAX_CODELEN least significant bits become the most
significant.
mask: AND mask of the form 111110....000, used to determine if
leftVal is a prefix of leftIdx.
*/
int leftVal, leftIdx, mask;
// curLen: Length of the current symbol checked
int curLen;
for (k = 0 ; k < SYM_NUM ; k++) {
symbols[k].symbol = k;
symbols[k].codeLen = codeLens[k];
symbols[k].codeVal = 0; // Not known yet
}
/* Sort symbol array by length and then lexicographically to produce the same codes values
that were used in compression. */
qsort(symbols, SYM_NUM, sizeof(symbolT), lenThenLexComp);
// Compute code vals using the same algo as in compression
computeCodeVals(symbols);
/* The table is filled as follows:
For every MAX_CODELEN-bit integer k, find the
prefix code C that is a prefix of k (in a prefix code, a code cannot be
prefixed by another, so only one code can be a prefix of k).
To find the prefix, check all of the codes (len, val pairs) in the inner loop,
The index k is left shifted so that the MAX_CODELEN LSBs become the MSBs,
and the value of the code being checked is left shifted so that the codeLen LSBs
become the MSBs. If k is AND masked by a mask of the form 111111111000..0,
\codeLen/
and masked(k) == the shifted value of the current code, C is a prefix of k.
Upon finding C, codeLens[k] = the length of C (in bits),
symbols[k] = the symbol encoded by C.
*/
for (k = 0 ; k < DECOMP_SIZE ; k++)
for (j = 0 ; j < SYM_NUM ; j++) {
curLen = symbols[j].codeLen;
if (curLen != 0) { // Ignore the symbols that do not appear in the original file
leftIdx = k << (INT_SIZE - MAX_CODELEN);
mask = ((1 << curLen) - 1) << (INT_SIZE - curLen);
leftVal = symbols[j].codeVal << (INT_SIZE - curLen);
if ((leftIdx & mask) == leftVal) {
decompTablePtr->codeLens[k] = curLen;
decompTablePtr->symbols[k] = symbols[j].symbol;
break;
}
}
}
return 0;
}
</code></pre>
<h2>minQueue.h</h2>
<pre><code>#ifndef QUEUE_GUARD
#define QUEUE_GUARD
#include "codes.h"
// Min queue implementation used in Huffman coding (encoding.c).
// minQueueT: Binary min-heap implemented using arrays
typedef struct {
/* Array of pointers to Huffman tree nodes. */
huffmanNodeT **array;
/* Number of positions in the array that are used (due to how
a binary heap works they are the adjacent positions [0, nodeTotal-1] */
int nodeTotal;
} minQueueT;
/* minQueueInit(): Initialize the minimum queue, using an array of Huffman tree nodes.
Assumptions:
> minQueuePtr is not a NULL pointer.
> nodeTotal > 0
*/
void minQueueInit(minQueueT *minQueuePtr, huffmanNodeT **initialNodes, int nodeTotal);
/* minQueueIns(): Insert a Huffman tree root into the queue.
Assumptions:
> minQueuePtr is not a NULL pointer.
*/
void minQueueIns(minQueueT *minQueuePtr, huffmanNodeT *node);
/* delMin(): Remove the root of minimum frequency from the queue and return it.
Assumptions:
> minQueuePtr is not a NULL pointer.
*/
huffmanNodeT *delMin(minQueueT *minQueuePtr);
#endif
</code></pre>
<h2>minQueue.c</h2>
<pre><code>#include <stdlib.h>
#include "codes.h"
#include "minQueue.h"
void swap(huffmanNodeT **array, int x, int y) {
huffmanNodeT *temp = array[x];
array[x] = array[y];
array[y] = temp;
}
/* siftDown(): Sinks a node down the heap until the min heap
property is satisfied, by swapping it with the child of
minimum frequency.
Assumptions:
> minQueuePtr != NULL
> 0 <= pos < nodeTotal
*/
void siftDown(minQueueT *minQueuePtr, int pos) {
int minChild = 2*pos + 1;
int nodeTotal = minQueuePtr->nodeTotal;
huffmanNodeT **array = minQueuePtr->array;
while (minChild < nodeTotal) {
if (minChild + 1 < nodeTotal && array[minChild+1]->freq < array[minChild]->freq)
minChild++;
if (array[pos]->freq > array[minChild]->freq) {
swap(array, pos, minChild);
pos = minChild;
minChild = 2*pos+1;
}
else
break;
}
}
void minQueueInit(minQueueT *minQueuePtr, huffmanNodeT **initialNodes, int nodeTotal) {
minQueuePtr->array = initialNodes;
minQueuePtr->nodeTotal = nodeTotal;
for (int pos = nodeTotal/2 - 1 ; pos >= 0 ; pos--)
siftDown(minQueuePtr, pos);
}
void minQueueIns(minQueueT *minQueuePtr, huffmanNodeT *node) {
int pos = minQueuePtr->nodeTotal++;
huffmanNodeT **array = minQueuePtr->array;
array[pos] = node;
while (pos > 0 && array[(pos-1)/2]->freq > node->freq) {
swap(array, pos, (pos-1)/2);
pos = (pos-1)/2;
}
}
huffmanNodeT *delMin(minQueueT *minQueuePtr) {
huffmanNodeT *min = minQueuePtr->array[0];
minQueuePtr->array[0] = minQueuePtr->array[--minQueuePtr->nodeTotal];
siftDown(minQueuePtr, 0);
return min;
}
</code></pre>
<h2>file.h</h2>
<pre><code>#ifndef FILE_GUARD
#define FILE_GUARD
#include <stdio.h>
#include "const.h"
#include "codes.h"
/* The file format used for the compressed files is the
following:
> A header, which includes:
1. The magic number "FG2019" in ASCII.
2. The number of compressed data bytes (sizeof(size_t))
3. The code lengths of all 256 possible byte values and of the EOF symbol,
with values that do not appear in the original file being indicated
with a length of 0, which are needed to generate the same codes
as in compression, so that the data will be able to be decoded.
> The compressed data bytes (their number is stored in the header),
which always include the EOF symbol (of numeric value EOF_VAL) as
the last encoded symbol to aid in decompression.
Some bits of the last byte might be "padding" bits, used to fill
the last byte when the compression data size is not divisible by 8
(so the last bits do not fill a whole byte). Once the EOF symbol is
decoded, no more bits are to be processed, so those "padding" bits are igneored.
*/
/* isEmpty(): Checks if the file is empty. */
int isEmpty(FILE *fptr);
/* countSyms(): Return the frequencies of all symbols (byte or EOF)
in the file pointed to by src.
Assumptions:
> src != NULL
*/
int countSyms(FILE *src, size_t freqs[SYM_NUM]);
/* compress(): Compresses the file pointed to by src,
and writes the compressed data to dest.
Assumptions:
> All arguements != NULL
*/
int compress(FILE *src, FILE *dest, compTableT *compTablePtr);
/* compress(): Decompresses the compressed file pointed to by src
and writes the decompressed data to dest.
Assumptions:
> All arguements != NULL
*/
int decompress(FILE *src, FILE *dest, decompTableT decompTable, size_t compSize);
/* writeHeader(): Writes information necessary for decompression
(the compression header) to the file pointed to by dest. */
int writeHeader(FILE *dest, compTableT *compTablePtr, size_t freqs[SYM_NUM]);
/* readHeader(): Reads the compression header, and stores the
necessary information (code lengths and compressed data size). */
int readHeader(FILE *src, int codeLens[SYM_NUM], size_t *compSizePtr);
#endif
</code></pre>
<h2>file.c</h2>
<pre><code>#include <stdio.h>
#include <string.h>
#include "const.h"
#include "codes.h"
#include "error.h"
#include "file.h"
// Magic number and length
#define MAGIC_NUM "FG2019"
#define MAGIC_LEN 6
/* AND mask used in decoding, with the
x least significant bits being 1. */
#define MASK(x) (x >= INT_SIZE ? 0xFFFFFFFF : (1 << x) - 1)
// Size (in bytes) of the various buffers used
#define BUF_SIZE 1024
/* Shift amount used to make the MAX_CODELEN LSBs of the integer
the MAX_CODELEN MSBs by left shifting, used in decoding. */
#define LOOKUP_SHIFT (INT_SIZE - MAX_CODELEN)
/* The numerical value of the EOF symbol, used to simplify the
decoding process, as once an EOF symbol is decoded, no more
bits of the compressed file contain data of the original and
decoding can stop. */
#define EOF_VAL 256
int isEmpty(FILE *fptr) {
char c;
/* If the end-of-file is reached upon trying to read one character,
then the file is empty. */
c = fgetc(fptr);
if (c == EOF) {
if (feof(fptr))
fprintf(stderr, "The file is empty!\n");
else
reportError("fgetc", __FILE__, __LINE__);
return 1;
}
// Put the character back into the stream.
c = ungetc(c, fptr);
if (c == EOF) {
reportError("ungetc", __FILE__, __LINE__);
return 1;
}
return 0;
}
int countSyms(FILE *src, size_t freqs[SYM_NUM]) {
unsigned char buffer[BUF_SIZE];
size_t bytesRead;
int k;
bzero(freqs, SYM_NUM*sizeof(size_t));
/* Read the data in chunks of BUF_SIZE bytes until the end-of-file, to perform less read operations,
and count the appearances of each symbol. */
do {
bytesRead = fread(buffer, 1, BUF_SIZE, src);
if (ferror(src)) {
reportError("safeRead", __FILE__, __LINE__);
return -1;
}
for (k = 0 ; k < bytesRead ; k++)
freqs[buffer[k]] += 1;
} while (!feof(src));
/* Add one appearance for the special EOF symbol (not to be confused with the actual end-of-file)
that is used in decoding. */
freqs[EOF_VAL] = 1;
return 0;
}
int compress(FILE *src, FILE *dest, compTableT *compTablePtr) {
/*
readBuf[]: Buffer used to read BUF_SIZE from src at once, an optimization
to limit fread() function calls (1 call for BUF_SIZE bytes is cheaper
than BUF_SIZE calls to read 1 byte).
writeBuf[]: Used for similar reasons to readBuf[], only for
fwrite() function calls. Must be initialized to 0,
so that OR operations involving it give the wanted results.
*/
unsigned char readBuf[BUF_SIZE], writeBuf[BUF_SIZE] = {0};
/* bitsRemCode: The bits of the code corresponding to the current
byte of the read buffer being encoded, that need to be written to the
write buffer. */
int bitsRemCode;
/* bitsRemByte: The bits remaining in the byte of the write buffer
that is currently used. Initialized to 8, as the first byte
will initially have all of its 8bits unused. */
char bitsRemByte = 8;
// wPos: The position of the current byte in writeBuf.
int wPos = 0;
int k;
size_t bytesRead, bytesWritten;
int *codeLens = compTablePtr->lens;
unsigned int *codeVals = compTablePtr->vals;
// curVal: The current code value being written to the write buffer.
unsigned int curVal;
do {
bytesRead = fread(readBuf, 1, BUF_SIZE, src);
if (ferror(src)) {
reportError("safeRead", __FILE__, __LINE__);
return -1;
}
for (k = 0 ; k < bytesRead ; k++) {
bitsRemCode = codeLens[readBuf[k]];
curVal = codeVals[readBuf[k]];
/* While the code bits that haven't been written yet do
not fit in the current byte of the write buffer,
write as many bits as possible to fit in the byte, then
move on to the next byte of the buffer, or in the
case that the buffer is full, flush it and then begin from wPos = 0. */
while (bitsRemCode > bitsRemByte) {
writeBuf[wPos] |= curVal >> (bitsRemCode - bitsRemByte);
wPos++;
if (wPos == BUF_SIZE) {
bytesWritten = fwrite(writeBuf, 1, BUF_SIZE, dest);
if (bytesWritten < BUF_SIZE) {
reportError("fwrite", __FILE__, __LINE__);
return -1;
}
// Clear the write buffer, else OR operations will produce garbage
bzero(writeBuf, BUF_SIZE);
wPos = 0;
}
/* bitsRemByte bits of the code were written to the buffer,
so bitsRemCode - bitsRemByte remain */
bitsRemCode -= bitsRemByte;
// A new byte will be used, so all of its 8 bits are free
bitsRemByte = 8;
}
// Write the reamining bits of the code to the current byte
writeBuf[wPos] |= curVal << (bitsRemByte - bitsRemCode);
bitsRemByte -= bitsRemCode;
}
} while (!feof(src));
// Another loop to write the encoded EOF symbol to the file.
curVal = codeVals[EOF_VAL];
bitsRemCode = codeLens[EOF_VAL];
while (bitsRemCode > bitsRemByte) {
writeBuf[wPos] |= curVal >> (bitsRemCode - bitsRemByte);
wPos++;
if (wPos == BUF_SIZE) {
bytesWritten = fwrite(writeBuf, 1, BUF_SIZE, dest);
if (bytesWritten < BUF_SIZE) {
reportError("fwrite", __FILE__, __LINE__);
return -1;
}
bzero(writeBuf, BUF_SIZE);
wPos = 0;
}
bitsRemCode -= bitsRemByte;
bitsRemByte = 8;
}
writeBuf[wPos] |= curVal << (bitsRemByte - bitsRemCode);
bitsRemByte -= bitsRemCode;
/* If wPos > 0 after the above while loop ends,
some compressed data is still in the
write buffer. In that case a last write to the
file should be performed. */
bytesWritten = fwrite(writeBuf, 1, wPos+1, dest);
if (bytesWritten < wPos+1) {
reportError("fwrite", __FILE__, __LINE__);
return -1;
}
return 0;
}
int writeHeader(FILE *dest, compTableT *compTablePtr, size_t freqs[SYM_NUM]) {
// compSize: Size of the compressed data in bytes.
size_t compSize = 0;
size_t written;
// lenBuf: Buffer that stores the codeLens to be written.
unsigned char lenBuf[SYM_NUM];
written = fwrite(MAGIC_NUM, 1, MAGIC_LEN, dest);
if (written < MAGIC_LEN) {
reportError("fwrite", __FILE__, __LINE__);
return -1;
}
// Compute compSize in bits.
for (int k = 0 ; k < SYM_NUM ; k++)
compSize += freqs[k] * compTablePtr->lens[k];
// Convert compSize to byte size by ceil.
compSize = (compSize % 8 == 0) ? (compSize / 8) : (compSize / 8 + 1);
/* Write size to file (for error written != 0 is checked,
due to writing only 1 item of size sizeof(size_t)). */
written = fwrite(&compSize, sizeof(size_t), 1, dest);
if (written == 0) {
reportError("fwrite", __FILE__, __LINE__);
return -1;
}
/* Write the code lengths for every symbol (EOF included) to
the file (even the 0 lengths for the symbols that do not appear).
There is no need to provide further information, the codeVals
can be computed using the codeLens using the canonical Huffman algorithm
in code.c. */
for (int k = 0 ; k < SYM_NUM ; k++)
lenBuf[k] = compTablePtr->lens[k];
written = fwrite(lenBuf, 1, SYM_NUM, dest);
if (written < SYM_NUM) {
reportError("fwrite", __FILE__, __LINE__);
return -1;
}
return 0;
}
int readHeader(FILE *src, int codeLens[SYM_NUM], size_t *compSizePtr) {
// compSize: Size of the compressed data in bytes.
size_t compSize;
/* readBuf: Buffer used for reading from the file, both the magic number,
and the codelengths of the SYM_NUM symbols fit into it. */
char readBuf[SYM_NUM] = {0};
// Read MAGIC_LEN bytes, if there are not enough, the file does not adhere to the format.
fread(readBuf, 1, MAGIC_LEN, src);
if (feof(src)) {
fprintf(stderr, "%s:%d: Malformed magic num error.\n", __FILE__, __LINE__);
return -1;
}
else if (ferror(src)) {
reportError("safeRead", __FILE__, __LINE__);
return -1;
}
if (strcmp(readBuf, MAGIC_NUM) != 0) {
fprintf(stderr, "Magic number missing!\n");
return -1;
}
// Read compSize from file.
fread(&compSize, sizeof(size_t), 1, src);
if (feof(src)) {// Again if not enough bits, the header is malformed
fprintf(stderr, "%s:%d: Malformed header error.\n", __FILE__, __LINE__);
return -1;
}
else if (ferror(src)) {
reportError("safeRead", __FILE__, __LINE__);
return -1;
}
*compSizePtr = compSize;
// Read all of the code lengths.
fread(readBuf, 1, SYM_NUM, src);
if (feof(src)) {
fprintf(stderr, "%s:%d: Malformed header error.\n", __FILE__, __LINE__);
return -1;
}
else if (ferror(src)) {
reportError("safeRead", __FILE__, __LINE__);
return -1;
}
for (int k = 0 ; k < SYM_NUM ; k++)
codeLens[k] = readBuf[k];
return 0;
}
int decompress(FILE *src, FILE *dest, decompTableT decompTable, size_t compSize) {
// readBuf, writeBuf: Used for the same reason as in compress()
unsigned char readBuf[BUF_SIZE], writeBuf[BUF_SIZE];
// Bits remaining in the current read buffer byte
char bitsRem = 8;
// wPos: write buffer position, rPos: read buffer positions
int wPos = 0, rPos;
size_t bytesRead, bytesWritten;
int readLoops = (compSize % BUF_SIZE == 0) ? (compSize / BUF_SIZE) : (compSize / BUF_SIZE + 1);
/* decIdx: A 32bit buffer, the MAX_CODELEN most significant bits of
which are used as the index of the decoding lookup table, by doing decIdx >> LOOKUP_SHIFT
Initialized to 0, in order for the first bit write using OR operations to work correctly.
*/
unsigned int decIdx = 0;
// Bits needed until all 32bits of decIdx are filled.
int bitsNeeded = INT_SIZE;
/* totalBytes: The total number of bytes that have been read, used to detect
if the compressed data is less than that indicated by compSize. */
size_t totalBytes = 0;
for (int k = 0 ; k < readLoops ; k++) {
// (Re)fill read buffer
bytesRead = fread(readBuf, 1, BUF_SIZE, src);
if (ferror(src)) {
reportError("safeRead", __FILE__, __LINE__);
return -1;
}
/* If the end-of-file (not to be confused with the EOF symbol) is reached,
and the total number of bytes read is less than compSize, then some
bytes are missing. Else, it is just the last loop of filling the read buffer. */
else if (feof(src) && (totalBytes + bytesRead < compSize)) {
fprintf(stderr, "%s:%d: Malformed file error, less data than promised.\n", __FILE__, __LINE__);
return -1;
}
totalBytes += bytesRead;
// Reset read buffer position
rPos = 0;
/* The decoding table decIdx is formed using the bits read from the file,
and should always contain sizeof(int)*8 bits. The number of bits
is arbitrary, as long as it is greater than MAX_CODELEN (so that
there won't be a need to find more bits during decoding). The requirement
for the number of bits to remain constant is to simplify the
algorithm a bit, with decIdx mimicking a bit stream.
Initially, decIdx is empty (bitsNeeded == INT_SIZE),
so it is filled with bits from the read buffer.
When the x most significant bits of decIdx are used to
decode a symbol (which is written to the write buffer), they are
consumed (removed from decIdx through left shifting by x).
Those x bits are then replenished by bits of the read buffer (as
mention, decIdx always contains sizeof(int)*8 bits), and
if the read buffer is out of bits, the while(1){} loop is
exited, and the read buffer is refilled.
*/
while (1) {
/* The approach to writing bits to decIdx is similar to that used
in compress() for writing bits to writeBuf[wPos], but a mask is
needed because decIdx is not 8bits long (unlike writeBuf[wPos]),
so if bits other than the bitsNeeded LSBs are != 0, the value of
decIdx will be wrong. */
while (bitsNeeded > bitsRem && rPos < bytesRead) {
// Left shift promotes unsigned char to int
decIdx |= ((readBuf[rPos] << (bitsNeeded - bitsRem)) & MASK(bitsNeeded));
rPos++;
bitsNeeded -= bitsRem;
bitsRem = 8;
}
if (rPos == bytesRead)
break;
decIdx |= ((readBuf[rPos] >> (bitsRem - bitsNeeded)) & MASK(bitsNeeded));
bitsRem -= bitsNeeded;
writeBuf[wPos] = decompTable.symbols[decIdx >> LOOKUP_SHIFT];
wPos++;
// If the write buffer is full, flush and reset position
if (wPos == BUF_SIZE){
bytesWritten = fwrite(writeBuf, 1, BUF_SIZE, dest);
if (bytesWritten < BUF_SIZE) {
reportError("fwrite", __FILE__, __LINE__);
return -1;
}
wPos = 0;
}
bitsNeeded = decompTable.codeLens[decIdx >> LOOKUP_SHIFT];
decIdx <<= bitsNeeded;
}
}
/* After all of the compressed file's bits have been read,
bits stored in decIdx cannot be replenished, so the bits
remaining in decIdx are decoded into the symbols of t
he original file, until the EOF symbol is found.
Assuming the compressed file is not corrupted, the EOF
symbol should always be found. */
// Check if EOF was found using its numeric value.
while (decompTable.symbols[decIdx >> LOOKUP_SHIFT] != EOF_VAL) {
writeBuf[wPos] = decompTable.symbols[decIdx >> LOOKUP_SHIFT];
wPos++;
if (wPos == BUF_SIZE){
bytesWritten = fwrite(writeBuf, 1, BUF_SIZE, dest);
if (bytesWritten < BUF_SIZE) {
reportError("fwrite", __FILE__, __LINE__);
return -1;
}
wPos = 0;
}
// Consume the bits of decIdx needed for decoding.
bitsNeeded = decompTable.codeLens[decIdx >> LOOKUP_SHIFT];
decIdx <<= bitsNeeded;
}
/* If wPos > 0 after the above while loop ends,
some data is still in the
write buffer. In that case a last write to the
file should be performed. */
if (wPos > 0) {
bytesWritten = fwrite(writeBuf, 1, wPos, dest);
if (bytesWritten < wPos) {
reportError("fwrite", __FILE__, __LINE__);
return -1;
}
}
return 0;
}
</code></pre>
<h2>error.h</h2>
<pre><code>#ifndef ERROR_GUARD
#define ERROR_GUARD
void reportError(char *message, char *filename, int line);
#endif
</code></pre>
<h2>error.c</h2>
<pre><code>#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
void reportError(char *message, char *filename, int line) {
fprintf(stderr, "%s:%d: ", filename, line);
perror(message);
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T11:10:12.973",
"Id": "438483",
"Score": "1",
"body": "I think you should provide the struct declaration of `huffmanNodeT`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T12:12:09.350",
"Id": "438488",
"Score": "1",
"body": "What are `\"const.h\"`, `\"minQueue.h\"`, `\"error.h\"`, `\"file.h\"` and `\"codes.h\"`? They seem to be missing from the review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T12:47:27.430",
"Id": "438492",
"Score": "0",
"body": "Could you please add the header files. Right now there isn't enough information to provide a good review. Please look at https://codereview.stackexchange.com/help/how-to-ask and https://codereview.stackexchange.com/help/dont-ask."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T12:49:20.263",
"Id": "438493",
"Score": "0",
"body": "It might also be helpful if you explained what kind of file is being compressed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T14:57:00.490",
"Id": "438499",
"Score": "0",
"body": "Thanks for the feedback, I included the missing files now."
}
] |
[
{
"body": "<h1>Write inline documentation in Doxygen format</h1>\n\n<p>You are making a good effort to document the functions, variables and macros you declare. It would be even better if you use a standardized format for it, like <a href=\"http://www.doxygen.nl/\" rel=\"nofollow noreferrer\">Doxygen</a>. This can then be processed by tools to provide that documentation in HTML and PDF format, and those tools can even check if you describe all input and output parameters of functions, and whether you forgot to document anything.</p>\n\n<h1>In addition to documenting assumptions, <code>assert()</code> them</h1>\n\n<p>If a function requires that a parameter that's passed in is non-<code>NULL</code>, add an <code>assert()</code> statement at the start of that function to check that. You can disable the\n<code>assert()</code>-statements when making a release build by adding <code>-DNDEBUG</code> to the compiler flags. But during development, this helps debugging issues.</p>\n\n<h1>Avoid macros where possible</h1>\n\n<p>Don't <code>#define</code> anything you could just as well have written as a const variable or as a function. The problem with macros is that it is easy to forget necessary parentheses, or to evaluate macro arguments with side-effects multiple times. Constants and inlined functions are just as performant as macros. Also, you get stronger typing. So for example, instead of:</p>\n\n<pre><code>#define MASK(x) (x >= INT_SIZE ? 0xFFFFFFFF : (1 << x) - 1)\n</code></pre>\n\n<p>Write:</p>\n\n<pre><code>static inline int mask(int x) {\n if (x >= INT_SIZE)\n return 0xFFFFFFFF;\n else\n return (1 << x) - 1;\n}\n</code></pre>\n\n<p>Note that the above already hints at an issue: the constant <code>0xFFFFFFFF</code> is larger than the maximum value of an int. Maybe this should return an <code>unsigned int</code>? And while you are at it, you should probably just <code>assert(x < INT_SIZE)</code>.</p>\n\n<h1>Make functions <code>static</code> where possible</h1>\n\n<p>If you have a function that is only used in the file it is defined in, you should make it <code>static</code>. This is especially important for libraries, as it prevents these function names leaking into the global namespace. Also, it allows the compiler to make more aggressive optimizations.</p>\n\n<h1>Use a code formatter</h1>\n\n<p>There are some inconsistencies in your code with spaces around braces and math operators, there's mixed <code>/* ... */</code> and <code>// ...</code> comment styles, newlines around code blocks, and so on. Use a code formatter like indent, astyle or clang-format to ensure everything has a consistent style. This also makes it easier if you have other people contributing to your code.</p>\n\n<h1>Remove unnecessary parentheses and casts</h1>\n\n<p>This is rather personal, but I believe that adding unnecessary parentheses to expressions more often makes them less readable than that it improves readability.\nFor example:</p>\n\n<pre><code>symbolT sym1 = *((symbolT*)ptr1);\n</code></pre>\n\n<p>This can be written as:</p>\n\n<pre><code>symbolT sym1 = *(symbolT*)ptr1;\n</code></pre>\n\n<p>Also, you can avoid explicit casts to <code>double</code> in some cases. For example:</p>\n\n<pre><code>kraftSum += 1 / (double)(1 << symbols[k].codeLen);\n</code></pre>\n\n<p>Can be rewritten as:</p>\n\n<pre><code>kraftSum += 1.0 / (1 << symbols[k].codeLen);\n</code></pre>\n\n<p>The <code>1.0</code> makes it explicit to the compiler that you want to do a floating point division.</p>\n\n<h1>Don't indent inside header guards</h1>\n\n<p>Don't indent code inside <code>#ifndef FOO_GUARD</code> ... <code>#endif</code>. This would indent all but two lines in a file. This doesn't really improve readability, it just shifts everything to the right, resulting in shorter lines and useless whitespace at the left.</p>\n\n<p>Alternatively to the header guard style you are using, you can also just put <code>#pragma once</code> at the start of each header file. All major compilers for all major platforms support this.</p>\n\n<h1>Consider delaying I/O error checking</h1>\n\n<p>When you are writing to the output, you check the return value of <code>fwrite()</code> every time. It is good practice to do error checking for all functions that might return an error. However, you will have noticed it adds a lot of lines to the code. Wouldn't it be nice if that can be avoided? It would save typing and makes the code look nicer. With most functions operating on a <code>FILE *</code>, the C library actually keeps track of the error state for each file. You can check whether the stream is still OK at any time by calling <code>ferror()</code>. The chance of an error actually occuring is low, and if it does, then delaying the error message a bit is not a problem. So in this case, you can just call <code>fwrite()</code> without checking the results, and just check <code>ferror()</code> once at the end. If <code>ferror()</code> returns a non-zero value, print an error and return an error.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T15:23:02.320",
"Id": "438746",
"Score": "0",
"body": "Regarding static functions, why would a global library function be a bad thing? Is there any way for someone to write machine code calling the function after linkage?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T17:27:52.547",
"Id": "438760",
"Score": "2",
"body": "@Hashew One problem is the one he said: naming collisions: you can't write two functions with the same name if they aren't `static`. If you do, even if they are in different files, the linker won't know what to do, because it will see two functions with the same name."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T17:37:39.963",
"Id": "438764",
"Score": "1",
"body": "@G.Sliepen I would advise against `static inline` in favour of `inline`. The reason is basically that static inline may produce more code. Here's a link where I explained with more detail: https://codereview.stackexchange.com/a/223755/200418"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T17:55:36.283",
"Id": "438770",
"Score": "1",
"body": "About macros I would say they are great for 3 things: -I mostly use macros instead of `static const` because you can use them to initialize `static` variables, and I always write parentheses around them just to be safe, even if I don't need them. -Function-like macros that can't be written as functions: `#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))`. -Generic functions: `MAX(a, b);` It's something very simple, and is relatively safe with a conscious user that knows it is a macro. But yes, function-like macros that can be easily replaced by `inline` functions should always be replaced."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T11:50:08.837",
"Id": "438842",
"Score": "0",
"body": "@CacahueteFrito: the `static` is there to keep the name from polluting the global namespace. Especially since macros typically have short, generic names. Of course, if the name is unique enough then indeed dropping `static` might give some benefit, but by the time a function is so large that you will notice the benefit, it probably should not be `inline` anymore either."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T11:54:33.620",
"Id": "438844",
"Score": "0",
"body": "@CacahueteFrito: you can initialize `static` variables with `static const` variables just fine, or am I missing something?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T15:23:51.317",
"Id": "438858",
"Score": "1",
"body": "@G.Sliepen Initializers: although some compilers may allow that as an extension, that is not necessarily true: https://stackoverflow.com/a/3025106/6872717"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T15:27:25.663",
"Id": "438860",
"Score": "1",
"body": "@G.Sliepen About functions replacing macros: If the function is in a header, it is in global namespace anyway, so `static` will only produce bad consequences. If the function is in a source file, then the compiler will know when to inline, so `inline` will be useless 99.9% of the time. Basically, `inline` in headers, and `static` in sources."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T16:02:05.623",
"Id": "438861",
"Score": "1",
"body": "@CacahueteFrito: if it is `static` in a header file, the *name* of that function will only be in the global namespace at compile time for those source files that include that header file. But more importantly, there will be no *symbol* in the global namespace that the linker will see. But I do agree about `inline` being useless 99.9% of the time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T16:14:04.053",
"Id": "438862",
"Score": "1",
"body": "@G.Sliepen In case you don't want a function to be there at link time, yes, it should be `static inline`, but in that case I would also use non-standard extensions such as `__attribute__((always_inline))` to avoid the problems caused by `static`."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T15:23:08.887",
"Id": "225768",
"ParentId": "225759",
"Score": "3"
}
},
{
"body": "<p>The decompression table construction algorithm is unusual and not an improvement over the usual algorithm. To sum up the difference,</p>\n\n<ul>\n<li>This algorithm: for each \"decode pattern\", find the code with matching prefix.</li>\n<li>The common algorithm: for each code, append all possible padding bit-patterns.</li>\n</ul>\n\n<p>The common algorithm has no \"search\" element to it, every iteration of the inner loop fills an entry of the decoding table. Using the bit-order that you use, the entries generated from a given code inhabit a contiguous range in the decoding table, starting at the code padded on the right with zeroes and ending at the code padded on the right with ones. It does not rely on any particular order of the <code>symbols</code> array though.</p>\n\n<p>As a bonus, the code for this is bit simpler than what you have now. For example (not tested):</p>\n\n<pre><code>for (j = 0 ; j < SYM_NUM ; j++) {\n curLen = symbols[j].codeLen;\n unsigned int curCode = symbols[j].codeVal;\n int curSym = symbols[j].symbol;\n\n // The code for the current symbol corresponds to all decoding\n // patterns that have it as a prefix.\n // Extend the code up to the length of a decoding pattern in all\n // possible ways, starting from all zeroes and stopping after all ones.\n int padding = MAX_CODELEN - curLen;\n unsigned int start = curCode << padding;\n unsigned int end = (curCode + 1) << padding;\n for (k = start ; k < end ; k++) {\n decompTablePtr->codeLens[k] = curLen;\n decompTablePtr->symbols[k] = curSym;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T16:07:03.700",
"Id": "225773",
"ParentId": "225759",
"Score": "1"
}
},
{
"body": "<h2><code>CHAR_BIT</code></h2>\n\n<p>Use that macro when you write 8 meaning how many bits there are in a <code>char</code>.</p>\n\n<p>You can find it in <code><limits.h></code></p>\n\n<hr>\n\n<h2>Safe (future-proof) usage of <code>sizeof</code></h2>\n\n<ul>\n<li><code>sizeof(type)</code> vs <code>sizeof(*foo)</code>:</li>\n</ul>\n\n<p><code>foo = malloc(sizeof(*foo));</code> is better because if you ever change the type of <code>foo</code>, this call will still be valid, while if not, you would have to change every line where malloc is called with foo. If you forget any of those lines, good luck.</p>\n\n<p>In your <code>qsort</code> calls happens the same.</p>\n\n<hr>\n\n<h2>Header naming collision</h2>\n\n<p>The header file <a href=\"http://man7.org/linux/man-pages/man3/error.3.html\" rel=\"nofollow noreferrer\"><code><error.h></code></a> exists in GNU C. If you never intend to support GCC or any compiler that is compatible with GNU C (which is a lot of them), then fine. You should probably rename your header file. Using a path, such as <code>#include \"my_project/error.h\"</code> is the best solution I can think of, because you never know what weird names they might have invented as extensions to standard C; they might even invent them later than you. Yes, in <code>\"\"</code> included files, your files have precedence over the installed ones, but I wouldn't rely much on that.</p>\n\n<p>From the top of my head I can't remember, but I would say that <code><file.h></code> also exists somewhere; just do the same to be safe.</p>\n\n<hr>\n\n<h2>Bitwise operations on signed integers</h2>\n\n<p>Unless you really need to do that, and you're completely sure that what you're doing is correct, don't. It's very very unsafe and unreliable. And even if you need to use Bitwise operations on signed integers, I would cast them to unsigned just to do the operation, and then cast back to the signed type to continue using it.</p>\n\n<p>Also, if you can, use fixed width integers for even more safety (<code><stdint.h></code>)</p>\n\n<hr>\n\n<h2>Names and Order of Includes (source: <a href=\"https://google.github.io/styleguide/cppguide.html#Names_and_Order_of_Includes\" rel=\"nofollow noreferrer\">Google C++ Style Guide</a>)</h2>\n\n<p>Use standard order for readability and to avoid hidden dependencies: Related header, C library, C++ library, other libraries' .h, your project's .h.</p>\n\n<p>All of a project's header files should be listed as descendants of the project's source directory without use of UNIX directory shortcuts <code>.</code> (the current directory) or <code>..</code> (the parent directory). For example, <code>google-awesome-project/src/base/logging.h</code> should be included as:</p>\n\n<pre><code>#include \"base/logging.h\" \n</code></pre>\n\n<p>In <code>dir/foo.cc</code> or <code>dir/foo_test.cc</code>, whose main purpose is to implement or test the stuff in <code>dir2/foo2.h</code>, order your includes as follows:</p>\n\n<p>dir2/foo2.h.</p>\n\n<p>A blank line</p>\n\n<p>C system files.</p>\n\n<p>C++ system files.</p>\n\n<p>A blank line</p>\n\n<p>Other libraries' .h files.</p>\n\n<p>Your project's .h files.</p>\n\n<p>Note that any adjacent blank lines should be collapsed.</p>\n\n<p>With the preferred ordering, if <code>dir2/foo2.h</code> omits any necessary includes, the build of <code>dir/foo.cc</code> or <code>dir/foo_test.cc</code> will break. Thus, this rule ensures that build breaks show up first for the people working on these files, not for innocent people in other packages.</p>\n\n<p><code>dir/foo.cc</code> and <code>dir2/foo2.h</code> are usually in the same directory (e.g. <code>base/basictypes_test.cc</code> and <code>base/basictypes.h</code>), but may sometimes be in different directories too.</p>\n\n<p>Within each section the includes should be ordered alphabetically.</p>\n\n<ul>\n<li>In your case this would mean this order of includes:</li>\n</ul>\n\n<p><code>minQueue.c</code>:</p>\n\n<pre><code>#include \"my_project/minQueue.h\"\n\n#include <stdlib.h>\n\n#include \"my_project/codes.h\"\n</code></pre>\n\n<hr>\n\n<h2><code>BUFSIZ</code></h2>\n\n<p>If you don't have the need of a very specific buffer size, don't write your own value, and just use this macro from <code><stdio.h></code>.</p>\n\n<hr>\n\n<h2><code>bzero</code> is deprecated</h2>\n\n<p><a href=\"http://man7.org/linux/man-pages/man3/bzero.3.html\" rel=\"nofollow noreferrer\"><code>man bzero</code></a>:</p>\n\n<blockquote>\n <p>CONFORMING TO</p>\n \n <p>The <code>bzero()</code> function is deprecated (marked as LEGACY in\n POSIX.1-2001); use memset(3) in new programs. POSIX.1-2008 removes the\n specification of <code>bzero()</code>. The <code>bzero()</code> function first appeared in\n 4.3BSD.</p>\n \n <p>The <code>explicit_bzero()</code> function is a nonstandard extension that is\n also present on some of the BSDs. Some other implementations have a\n similar function, such as <code>memset_explicit()</code> or <code>memset_s()</code>.</p>\n</blockquote>\n\n<p>Use <code>memset()</code> instead.</p>\n\n<hr>\n\n<h2><code>strncmp</code></h2>\n\n<p>When you use <code>fread</code> on a buffer, you can't guarantee that it will contain a valid string, so I would use <code>strncmp()</code> instead of <code>strcmp()</code> just to be safe.</p>\n\n<hr>\n\n<h2>DRY</h2>\n\n<p>Don't repeat yourself: In every call to <code>reportError()</code> you repeat the file and line special identifiers. You could embed those in a macro. This is what I do:</p>\n\n<pre><code>/*\n * void alx_perror(const char *restrict str);\n */\n#define alx_perror(str) do \\\n{ \\\n alx_perror__(__FILE__, __LINE__, __func__, str); \\\n} while (0)\n\n\n__attribute__((nonnull(1, 3)))\ninline\nvoid alx_perror__ (const char *restrict file, int line,\n const char *restrict func, const char *restrict str);\n\n\ninline\nvoid alx_perror__ (const char *restrict file, int line,\n const char *restrict func, const char *restrict str)\n{\n\n fprintf(stderr, \"%s:\\n\", program_invocation_name);\n fprintf(stderr, \" %s:%i:\\n\", file, line);\n fprintf(stderr, \" %s():\\n\", func);\n if (str)\n fprintf(stderr, \" %s\\n\", str);\n fprintf(stderr, \" E%i - %s\\n\", errno, strerror(errno));\n}\n</code></pre>\n\n<hr>\n\n<h2><code>ARRAY_SIZE()</code></h2>\n\n<p>When calling <code>qsort()</code> (actually, any function that accepts an array), in the field that states the size of the array, there are different possibilities:</p>\n\n<ul>\n<li>Pass the actual value</li>\n<li>Pass the result of <code>ARRAY_SIZE(arr)</code> (defined typically as <code>#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))</code>)</li>\n</ul>\n\n<p>If you can use the second one, which is when you have a global static-duration array or an array local to the function, it's the best method, because if the size of the array is changed (for example if I had <code>int a[FOO];</code> and then I decide to use a different size such as <code>int a[BAR];</code>), I don't need to change the rest of the code. And with recent compilers, such as GCC 8, you will receive a warning if you apply that to something that is not an array, so it is safe. With old compilers, there are still tricks to make this macro safe (you can find them in StackOverflow easily).</p>\n\n<p>If you can't use it, just use the value. (Never use <code>sizeof</code> directly, which would give the size of a pointer!).</p>\n\n<p>In your call to <code>qsort()</code>, it would be like this:</p>\n\n<pre><code>qsort(symbols, ARRAY_SIZE(symbols), sizeof(symbols[0]), lenThenLexComp);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T08:08:20.187",
"Id": "225810",
"ParentId": "225759",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T11:07:50.197",
"Id": "225759",
"Score": "5",
"Tags": [
"c",
"compression"
],
"Title": "File compression project"
}
|
225759
|
<p>The solution found to filtering <code>pathname</code> with customising current <code>normalizeTme()</code> function. For sure it is not the ideal way of fixing. It would be great if any one can guide me with better option with less number of line code.</p>
<p>DEMO: <a href="https://codepen.io/athimannil/pen/vojVmL" rel="nofollow noreferrer">https://codepen.io/athimannil/pen/vojVmL</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const initialLinks = [
"http://www.lchfmalayalam.com",
"https://t.me/Malappuram",
"https://t.me/keraladevelopers/42716",
"http://www.whatsapp.com",
"https://www.youtube.com/watch?v=BnbFRSyHIl4",
"http://google.com",
"https://t.me/joinchat/NHNd1hcSMCoYlnZGSC_H7g",
"https://t.me/keraladevelopers/",
"http://t.me/keraladevelopers",
"http://athimannil.com/react/",
"http://athimannil.info/",
"https://t.me/hellomates/5",
"http://t.me/Malappuram",
"http://t.me/keraladevelopers/42716",
"http://t.me/joinchat/NHNd1hcSMCoYlnZGSC_H7g",
"http://t.me/keraladevelopers/",
"http://t.me/hellomates/5"
];
const normalizeTme = R.replace(
/^(?:@|(?:https?:\/\/)?(?:t\.me|telegram\.(?:me|dog))\/)(\w+)(\/.+)?/i,
(_match, username, rest) => {
return /^\/\d+$/.test(rest) ?
`https://t.me/${username.toLowerCase()}` :
`https://t.me/${username.toLowerCase()}${rest || ""}`;
}
);
const filterOwnLinks = groupUsername => {
return R.match(
/^(?:@|(?:https?:\/\/)?(?:t\.me|telegram\.(?:me|dog))\/)(\w+)(\/.+)?/i,
(_match, username, rest) => {
if (username) {
return currentGroup.toLowerCase() !== username.toLowerCase();
}
return true;
}
);
};
const currentGroup = "Malappuram";
const urls = R.uniq(initialLinks)
.filter(links => {
const matse = R.match(
/^(?:@|(?:https?:\/\/)?(?:t\.me|telegram\.(?:me|dog))\/)(\w+)(\/.+)?/i,
links
);
if (matse[1]) {
return currentGroup.toLowerCase() !== matse[1].toLowerCase();
}
return true;
})
.map(normalizeTme);
console.log(initialLinks);
console.log(urls);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.17.1/ramda.min.js"></script></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T21:13:46.633",
"Id": "438562",
"Score": "0",
"body": "@ggorlen Updated the question https://codepen.io/athimannil/pen/vojVmL"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T21:39:52.147",
"Id": "438564",
"Score": "0",
"body": "@ggorlen The code pen seems to working for me. Unfortunately I don't know how to import **ramda** in to the stackoverflow snippet, I have tried a lot "
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T22:16:54.123",
"Id": "438567",
"Score": "1",
"body": "@ggorlen Yes, finally snippet is working. Thanks a lot for your help"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T22:19:37.427",
"Id": "438568",
"Score": "1",
"body": "Awesome. Looks great. I'd like to echo my original question: what do you mean by normalizing? I'm not entirely sure I understand what the code is supposed to do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T23:03:16.370",
"Id": "438569",
"Score": "0",
"body": "@ggorlen Actually this is part of Telegram bot. I need to remove current group related links from the array list. You can see the original code here https://github.com/thedevs-network/the-guard-bot/blob/develop/handlers/middlewares/checkLinks.js"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T11:43:00.543",
"Id": "225761",
"Score": "0",
"Tags": [
"javascript",
"regex",
"ecmascript-6",
"url"
],
"Title": "How to filter URL from the array list based on the string name with regExp?"
}
|
225761
|
<p>I would like to merge two <code>double</code> arrays and remove from the result array <code>approximately equal items</code>.</p>
<p>My two input arrays have length up to 100000 and are sorted. Them self they don't contain <code>approximately equal items</code>.</p>
<p>What are <code>approximately equal items</code>, see <a href="https://docs.microsoft.com/en-us/dotnet/api/system.double?view=netframework-4.8#Equality" rel="nofollow noreferrer">System.Double</a> documentation and there the example <code>IsApproximatelyEqual</code></p>
<blockquote>
<pre><code>static bool IsApproximatelyEqual(double value1, double value2, double epsilon)
{
// If they are equal anyway, just return True.
if (value1.Equals(value2))
return true;
// Handle NaN, Infinity.
if (Double.IsInfinity(value1) | Double.IsNaN(value1))
return value1.Equals(value2);
else if (Double.IsInfinity(value2) | Double.IsNaN(value2))
return value1.Equals(value2);
// Handle zero to avoid division by zero
double divisor = Math.Max(value1, value2);
if (divisor.Equals(0))
divisor = Math.Min(value1, value2);
// https://github.com/dotnet/samples/pull/1152/
return Math.Abs((value1 - value2) / divisor) <= epsilon;
}
</code></pre>
</blockquote>
<p>I wrote the following method, but it gets very slow using large arrays.</p>
<pre><code>public static double[] Union(double[] a, double[] b)
{
List<double> alist = new List<double>(a);
for (int i = 0; i < b.Length; i++)
{
if (!alist.Exists(ai => IsApproximatelyEqual(ai, b[i], 1e-15))
alist.Add(b[i]);
}
alist.Sort();
return alist.ToArray();
}
</code></pre>
<p>Then I wrote the following method, which is much faster:</p>
<pre><code>public static double[] Union2(double[] a, double[] b)
{
int i1 = 0, i2 = 0;
int n1 = a.Length, n2 = b.Length;
List<double> c = new List<double>(n1 + n2);
while (i1 < n1 || i2 < n2)
{
if (i1 < n1)
{
if (i2 < n2)
{
if (IsApproximatelyEqual(a[i1], b[i2], 1e-15))
{
c.Add(a[i1++]);
i2++;
}
else if (a[i1] < b[i2])
{
c.Add(a[i1++]);
}
else
{
c.Add(b[i2++]);
}
}
else
{
c.Add(a[i1++]);
}
}
else //if (i2 < n2)
{
c.Add(b[i2++]);
}
}
return c.ToArray();
}
</code></pre>
<p>You can <a href="https://dotnetfiddle.net/JnCKmv" rel="nofollow noreferrer">try it out online</a>.</p>
<p>Is there a way to speed up the above code?</p>
<p>For <code>epsilon</code> I'm using <code>1e-15</code> because a <code>double</code> has a maximum precision of 15 digits and an internal precision of 17 digits.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T15:28:46.470",
"Id": "438503",
"Score": "1",
"body": "You should be able to sort both arrays then iterate through them checking if values are close to determine which to keep. This would also mean the result was sorted since you seem to need that at the end anyway."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T16:00:09.320",
"Id": "438507",
"Score": "0",
"body": "How many items do your real arrays contain?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T16:00:33.120",
"Id": "438508",
"Score": "1",
"body": "I don't understand the \"remove the duplicates\" requirement: could you make that clearer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T16:31:49.317",
"Id": "438524",
"Score": "2",
"body": "@t3chb0t It's a confusing question. I propose OP to clarify with proper use cases that show difference between absolute and relative tolerance. Also, when swapping array a with b, I think different results could yield."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T16:39:25.703",
"Id": "438525",
"Score": "0",
"body": "@juharr, I wouldn't bother sorting the arrays, if the final statement of the question can be confirmed..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T17:21:26.433",
"Id": "438531",
"Score": "1",
"body": "\"which have a relative accuracy of 1e-15\" is that the chance of them being rightfully a duplicate or the chance they're not? That's a major difference. The way you phrase it now, it looks like random chance has a higher accuracy than your program."
}
] |
[
{
"body": "<p>Wait, are the arrays already sorted?</p>\n\n<p>These are just my initial thoughts, but:</p>\n\n<ul>\n<li><p>The initial creation of your new list I'm guessing is <span class=\"math-container\">\\$O(n)\\$</span> to create a copy of array <code>a</code> (<span class=\"math-container\">\\$n\\$</span> is the length of <code>a</code>). This might be unavoidable if you want a nondestructive function, though the arrays <em>are</em> passed in by value, so it may not be necessary.</p></li>\n<li><p><code>List.Exists</code> is that it's a linear operation, so the combination of the two arrays I <em>think</em> will be <span class=\"math-container\">\\$O(m(n+m))\\$</span> (<span class=\"math-container\">\\$m\\$</span> is the length of <code>b</code>). I arrived at this conclusion because for every element in <code>b</code>, we have to search through our combined list. so that's <span class=\"math-container\">\\$m\\$</span> * the search complexity. For the search complexity, since this is big <span class=\"math-container\">\\$O\\$</span> notation, I assumed that <code>a</code> did not contain any of <code>b</code>'s elements, so as we insert an element from <code>b</code> into our combined list, the search complexity grows, up until the size of <code>a</code> + <code>b</code>. There's actually a little more complexity to the <code>List.Add</code> operation due to some nuances, but we'll just say it's <span class=\"math-container\">\\$O(1)\\$</span>.</p></li>\n<li><p>Finally, you sort the list after combining everything, so I imagine C# uses one of the faster sorting algorithms, and that is <span class=\"math-container\">\\$O(xlog(x))\\$</span> (<span class=\"math-container\">\\$x\\$</span> is the length of the final combined list).</p></li>\n</ul>\n\n<p>So in terms of complexity, if all of this is true, we have <span class=\"math-container\">\\$n + m(m+n) + xlogx\\$</span>.</p>\n\n<p>Back to my initial question, if the arrays are already sorted coming in, I'm thinking you can find any element with a binary search which is <span class=\"math-container\">\\$O(log(y))\\$</span> (<span class=\"math-container\">\\$y\\$</span> is the size of the array you're searching in), so you can search for every element in <code>b</code> within <code>a</code>, and we can probably tweak the binary search to return the left and/or right indexes if the number wasn't found, in which case we simply have to insert between those indexes. The operation then would be <span class=\"math-container\">\\$O(mlog(n))\\$</span> + the complexity to insert. Unfortunately, and in shameful admittance, random access inserts of arrays is where this algorithm falls off, but you can optimize the insert complexity by choosing a different data structure from an array.</p>\n\n<p>Of course, this method actually only requires one of the arrays be sorted before starting, and sorting <em>one</em> array beforehand would be faster than sorting the whole array at the end.</p>\n\n<p>So in conclusion, you can drop the sort at the end, and you can work to remove the linear <code>List.exists</code> operation to speed up your code. If you're truly gungho you can try using a different data structure that can amortize both search and insert operations.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T17:03:14.513",
"Id": "438528",
"Score": "2",
"body": "You don't need a binary search - just a similar approach to Merge Sort: starting from the front of both inputs, take the lower one, and enter it into the result array, unless it's the same value (within tolerance) as the current back of the result."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T17:05:13.770",
"Id": "438529",
"Score": "0",
"body": "@TobySpeight But it is not clear how to calculate the tolerance. depending which array is _a_ and which _b_ 2 values are either equivalent or not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T17:21:52.330",
"Id": "438532",
"Score": "1",
"body": "It shouldn't matter - the difference between `b`-`a` < 1e-15 × `b` and `b`-`a` < 1e-15 × `a` is only 1e-30 × `b`, which is near the limit of precision."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T11:46:40.577",
"Id": "438596",
"Score": "1",
"body": "You feel your answer got invalidated because of the updated question? If so, I suggest OP to post a new question as follow-up to this one and we'll revert this one and keep it closed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T17:05:09.137",
"Id": "438625",
"Score": "2",
"body": "@dfhwze I think this answer is still valid as the only point where it speaks about OP's code is that the arrays are sorted... and they still are. Anything else is very abstract and general."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T16:43:48.680",
"Id": "225777",
"ParentId": "225769",
"Score": "3"
}
},
{
"body": "<p>If you need performance optimized code, your solution looks very well. I think the performance can be optimized best by using a simplified aproximation approach (e.g.: <code>Math.Abs(value1 - value2) <= Double.Epsilon</code>).</p>\n\n<p>Another note (that actually doesn't affect performance): Use '||' instead of use '|' because the second one evaluates always both conditions whereas the firs one stops as soon as the result is known.</p>\n\n<p>However, for 100.000 sorted values, performance doesn't matter. For that use case I would optimize code for maintainablity and readability:</p>\n\n<pre><code>public class ApproximatelyDoubleComparer : IEqualityComparer<Double>\n{\n private readonly double epsilon;\n\n public ApproximatelyDoubleComparer(double epsilon)\n {\n this.epsilon = epsilon;\n }\n\n public bool Equals(double value1, double value2)\n {\n // If they are equal anyway, just return True.\n if (value1.Equals(value2))\n return true;\n\n // Handle NaN, Infinity.\n if (Double.IsInfinity(value1) | Double.IsNaN(value1))\n return value1.Equals(value2);\n else if (Double.IsInfinity(value2) | Double.IsNaN(value2))\n return value1.Equals(value2);\n\n // Handle zero to avoid division by zero\n double divisor = Math.Max(value1, value2);\n if (divisor.Equals(0))\n divisor = Math.Min(value1, value2);\n\n // https://github.com/dotnet/samples/pull/1152/\n return Math.Abs((value1 - value2) / divisor) <= epsilon;\n }\n\n public int GetHashCode(double obj)\n {\n return obj.GetHashCode();\n }\n}\n</code></pre>\n\n<p>Usage;</p>\n\n<pre><code>var union = a1.Concat(a2)\n .Distinct(new ApproximatelyDoubleComparer(1e-15))\n .OrderBy(x => x) // if a sorted list is required\n .ToArray();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T18:09:52.257",
"Id": "438646",
"Score": "0",
"body": "Your first statement does change the specification of the OP's intended precision. I don't think we should change spec for the mere purpose of optimizing performance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T18:12:29.673",
"Id": "438647",
"Score": "0",
"body": "Do you mean `Math.Abs(value1 - value2) <= Double.Epsilon`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T18:13:08.900",
"Id": "438648",
"Score": "0",
"body": "Yes or am I missing your point here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T18:17:01.580",
"Id": "438649",
"Score": "0",
"body": "You are right. My point was: There is not much potential in the algorithm for perfomance optimization. If performance optimization is a requirement, a simplified definition of \"Approximately\" has the most potential ;)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T18:17:28.820",
"Id": "438650",
"Score": "0",
"body": "Fair enough :-)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T18:05:26.663",
"Id": "225842",
"ParentId": "225769",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T15:26:29.273",
"Id": "225769",
"Score": "-1",
"Tags": [
"c#",
"performance",
"array",
"comparative-review",
"floating-point"
],
"Title": "Union of two double arrays"
}
|
225769
|
<p>My file tree is <a href="https://github.com/SeanDez/delayedCoupons/tree/2d7732cf932801a904059f501d7a8e88234833e6" rel="nofollow noreferrer">here</a>.</p>
<p>It does not look good. I would appreciate any tips you have on improving code organization. My React mindset of breaking folders by component didn't carry over well into php/wordpress. I'm thinking for my next project I'll follow convention to put all <code>classes</code> in <code>/classes</code></p>
<p>As is most of the project is in /adminSettingsArea. The React app is in the subfolder /src but what I really would like feedback on is how to organize all the PHP and dependent code.</p>
<p>Here is my entryPoint.php:</p>
<pre><code><?php
namespace DelayedCoupons;
////// Plugin Declaration (read by WP Core) //////
/**
* Plugin Name: Delayed Coupons
* Description: Show coupons after a visitor visits a specific page a certain number of times
* */
/** Basic Project Setup
* Env variables, constant definitions, class autoloads
*/
require_once ('bootstrap.php');
////// On Plugin Activation //////
require_once ('adminSettingsArea/DataBase.php');
/** Creates DB tables on plugin activation
*/
use \DataBase;
$database = new DataBase();
register_activation_hook(__FILE__, [$database, 'initializeTables']);
register_activation_hook(__FILE__, [$database, 'initializeDummyTable']);
////// Page Builder Functions & Matching Hooks //////
// Admin Page
require_once ('adminSettingsArea/index.php');
/** Handles all aspects of triggers and coupon display
* Cookie setting. Trigger checks. Coupon retrieval and rendering
*/
require_once (ADMIN_SETTINGS_PATH . '/Visitors.php');
use admin\controllers\Visitors;
$visitors = new Visitors();
add_action('init', [$visitors, 'logVisitsAndControlCouponDisplay']);
/** Rest Api Extensions
* Endpoints for adding coupons, deleting, and loading coupon data.
*/
require_once ('adminSettingsArea/ApiController.php');
use \admin\controllers\ApiController;
function hookAllRestControllers() {
$apiController = new ApiController();
$apiController->registerDummyRoute();
$apiController->registerLoadCouponRoute();
$apiController->registerDeleteSingleCouponRoute();
}
add_action('rest_api_init', '\DelayedCoupons\hookAllRestControllers');
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T15:45:16.980",
"Id": "225770",
"Score": "1",
"Tags": [
"php",
"plugin",
"wordpress"
],
"Title": "WordPress plugin to reveal coupons after several visits to a page"
}
|
225770
|
<p>I have a requirement to implement this simple table from one of the DVB S2X standards. The table is relatively small that contains no more than 28 rows. I need to use the key for the table as the second column from the structure below i.e. the <code>kbch</code> value.</p>
<pre><code>typedef struct __attribute__((packed)) {
float ldpcCodeId;
unsigned int kbch;
unsigned int kldpc;
unsigned char tErrCorrection;
} dvbS2xRecord;
</code></pre>
<p>I tried to use some complex hashing algorithms on this 5 digit positive integer to create a hash that I can use an index for my array. I realized that size 28 is a much smaller value for any hashing algorithm to create a hash index without creating any collisions. I tried using <code>key % arrSize</code> which didn't perform as expected.</p>
<p>So I created a simple version of the hash table that can lookup in O(1), by creating a static mapping of the integer with the index in the array. The full version of the code is</p>
<pre><code>#include <stdio.h>
typedef struct __attribute__((packed)) {
float ldpcCodeId;
unsigned int kbch;
unsigned int kldpc;
unsigned char tErrCorrection;
}dvbS2xRecord;
static const dvbS2xRecord dvbS2xRecordTable[28] = { { .22 , 14208, 14400, 12 },
{ .25 , 16008, 16200, 12 },
{ .28 , 18528, 18720, 12 },
{ .33 , 21408, 21600, 12 },
{ .4 , 25728, 25920, 12 },
{ .45 , 28968, 29160, 12 },
{ .5 , 32208, 32400, 12 },
{ .53 , 34368, 34560, 12 },
{ .55 , 35448, 35640, 12 },
{ .555, 35808, 36000, 12 },
{ .57 , 37248, 37440, 12 },
{ .6 , 38688, 38880, 12 },
{ .62 , 40128, 40320, 12 },
{ .63 , 41208, 41400, 12 },
{ .64 , 41568, 41760, 12 },
{ .66 , 43008, 43200, 12 },
{ .68 , 44448, 44640, 12 },
{ .69 , 44808, 45000, 12 },
{ .71 , 45888, 46080, 12 },
{ .72 , 46608, 46800, 12 },
{ .73 , 47328, 47520, 12 },
{ .75 , 48408, 48600, 12 },
{ .77 , 50208, 50400, 12 },
{ .8 , 51648, 51840, 12 },
{ .83 , 53840, 54000, 10 },
{ .85 , 55248, 55440, 12 },
{ .88 , 57472, 57600, 8 },
{ .9 , 58192, 58320, 8 },
};
unsigned char hashOf(unsigned int kbch);
inline unsigned char hashOf(unsigned int kbch)
{
unsigned char idx = 0;
switch(kbch) {
case 14208: idx = 0 ; break; case 16008: idx = 1 ; break; case 18528: idx = 2 ; break; case 21408: idx = 3 ; break;
case 25728: idx = 4 ; break; case 28968: idx = 5 ; break; case 32208: idx = 6 ; break; case 34368: idx = 7 ; break;
case 35448: idx = 8 ; break; case 35808: idx = 9 ; break; case 37248: idx = 10 ; break; case 38688: idx = 11 ; break;
case 40128: idx = 12 ; break; case 41208: idx = 13 ; break; case 41568: idx = 14 ; break; case 43008: idx = 15 ; break;
case 44448: idx = 16 ; break; case 44808: idx = 17 ; break; case 45888: idx = 18 ; break; case 46608: idx = 19 ; break;
case 47328: idx = 20 ; break; case 48408: idx = 21 ; break; case 50208: idx = 22 ; break; case 51648: idx = 23 ; break;
case 53840: idx = 24 ; break; case 55248: idx = 25 ; break; case 57472: idx = 26 ; break; case 58192: idx = 27 ; break;
default: break ;
}
return idx;
}
int main()
{
for (int i=0; i< 28; i++) {
printf("value:%d hash:%d\n", dvbS2xRecordTable[i].kbch, hashOf( dvbS2xRecordTable[i].kbch ) );
}
return 0;
}
</code></pre>
<p>I made the function <code>inline</code> to make the frequent access to lookup the index a bit faster. With this logic e.g. for looking up a record information for a particular <code>kbch</code> value</p>
<pre><code> unsigned int kbch = 50208;
printf( "%d %0.3f %d\n", dvbS2xRecordTable[hashOf(kbch)].kldpc, \
dvbS2xRecordTable[hashOf(kbch)].ldpcCodeId, \
dvbS2xRecordTable[hashOf(kbch)].tErrCorrection );
</code></pre>
<p>The code is compiled with <code>gcc 4.8.5</code> on Centos 7 without any warnings or errors</p>
<pre><code> gcc -std=c11 -Wall -Wextra -pedantic-errors hashTable.c
</code></pre>
<p>How can I further improve this hashing and/or loopkup algorithm?</p>
|
[] |
[
{
"body": "<h1>Use a perfect hash function</h1>\n\n<p>What you want is to implement a <a href=\"https://en.wikipedia.org/wiki/Perfect_hash_function\" rel=\"nofollow noreferrer\">perfect hash function</a>. This is any function that for any of the valid input values, results in a unique value into to the hash table. Despite the name, there is more than one way to make such a function. Also, it's easier to make if you allow the hash table to be bigger than the number of valid items. There are tools available that, given a set of inputs, can create a perfect hash function for you. One example is <a href=\"https://www.gnu.org/software/gperf/manual/gperf.html\" rel=\"nofollow noreferrer\">GNU gperf</a>, unfortunately it expects the set of inputs to be strings.</p>\n\n<p>Another option is to find try to find a suitable mapping yourself. For example, the smallest difference between two values of kbch is 360, and the minimum value is 14208. So a possible perfect (but not minimal) hash function is:</p>\n\n<pre><code>unsigned int hashOf(unsigned int kbcd) {\n return (kcbd - 14208) / 360;\n}\n</code></pre>\n\n<p>The maximum output value of this function is 122, so you have to make an array of 123 elements, even though only 28 elements will have a useful entry.</p>\n\n<p>28 possible values is a small number, so writing something by hand might outperform a function generated by a generic tool. If you want to know what is faster, benchmark your code.</p>\n\n<h1>Don't use <code>__attribute__((packed))</code> unless you really need strict packing</h1>\n\n<p>Why is <code>dvbS2xRecord</code> packed? You may think this is faster because it might use fewer cache lines for <code>dvbS2xRecordTable[]</code>, but now the CPU has to do unaligned reads from the <code>dvbS2xRecord</code>s, which might slow things down, or result in undefined behavior on CPU architectures that do not support unaligned access.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T18:28:27.390",
"Id": "438546",
"Score": "0",
"body": "I did look at some implementations of the perfect hash function but I just can’t figure out the last step, to generate an index for the 28 length array. Can you show an example if possible?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T20:10:13.930",
"Id": "438549",
"Score": "0",
"body": "You run `hashOf()` on all the possible values for kbch in order, and then you get a set of numbers. Either you have to manually arrange the array such that the first possible value of kbch is at place `hashOf(14208)` in the array, or if you can rely on GCC, write the elements of the array in the original order, but prepend `[hash] = ` to each line, where `hash` is the output of `hashOf()` for the value of `kbch` in that line. Tools like gperf can output the array in the right order for you."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T18:12:23.120",
"Id": "225784",
"ParentId": "225778",
"Score": "2"
}
},
{
"body": "<h2>Use <code>int main(void)</code></h2>\n\n<p>C17::6.11.6: </p>\n\n<blockquote>\n <p>Function declarators The use of function declarators with empty\n parentheses (not prototype-format parameter type declarators) is an\n obsolescent feature.</p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T08:39:30.870",
"Id": "225813",
"ParentId": "225778",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T16:45:16.283",
"Id": "225778",
"Score": "2",
"Tags": [
"performance",
"algorithm",
"c",
"hash-map"
],
"Title": "Hash table implementation in C for a simple table record"
}
|
225778
|
<p>The idea here is that we have some resource that is relatively very expensive to generate, but once we have a bunch of them in a pool, we can keep reusing them instead of generating new ones. "HTTP connections" would be an example. In my particular use-case, it's "2048-bit RSA keys" (let's pass over the obligatory what-a-terrible-idea-that-is). Generating a new key takes about 200ms, so I just need a pool that can dole out existing keys faster than 200ms.</p>
<p>My other design goal is that the thing needs to be thread-safe (against maybe thousands of threads at a time), and in fact it's going to be accessed from greenthreads, not <code>std::thread</code>s, so I can't use <code>std::mutex</code>; I have to do everything lock-freely.</p>
<p>If you dole out <em>shared read access</em> to items, then you have to think about what happens if thread A is reading an item while thread B is trying to delete/overwrite it. I don't want to deal with that. So I made my <code>AtomicRoundRobinPool</code> dole out <em>exclusive access</em> to items. When you <code>get_item</code> from the pool, you get a <code>unique_ptr</code> to it (nobody else can see it but you). When you're done using the item, you may choose to <code>put_item</code> the <code>unique_ptr</code> back, or you may drop it on the floor; the pool class doesn't care.</p>
<p>If you <code>put_item</code> when there's no room left in the pool, the pool just kicks your item back to you. But we also want the ability to inject fresh blood into a full pool. So I made a <code>force_put_item</code> method, too; it <em>always</em> inserts the item you give it, but it might do so by evicting an item (in which case it kicks the evicted item back to you).</p>
<p>I also wrote a <code>try_quick_get_item</code> method that just checks the current round-robin slot and doesn't iterate over the entire array, but I don't think I'd end up using that method for anything in real life.</p>
<pre><code>#include <atomic>
#include <cassert>
#include <memory>
template<class T, int N>
class AtomicRoundRobinPool {
std::atomic<T*> array_[N] {};
std::atomic<int> get_idx_ {0};
std::atomic<int> put_idx_ {0};
std::atomic<int> size_ {0};
int postincrement_mod_N(std::atomic<int>& x) {
int expected = x.load(std::memory_order_relaxed);
while (true) {
int desired = (expected + 1) % N;
if (x.compare_exchange_strong(expected, desired)) {
return expected;
}
}
}
public:
static constexpr int capacity() { return N; }
int approximate_size() const {
return size_.load();
}
std::unique_ptr<T> try_quick_get_item() noexcept {
// Try grabbing the first slot we see. If the table is
// very full, then we expect this usually to work.
int idx = postincrement_mod_N(get_idx_);
T *result = array_[idx].exchange(nullptr);
if (result != nullptr) {
size_.fetch_sub(1);
}
return std::unique_ptr<T>(result);
}
std::unique_ptr<T> get_item() noexcept {
int idx = postincrement_mod_N(get_idx_);
for (int i=0; i < N; ++i) {
T *result = array_[idx].exchange(nullptr);
if (result != nullptr) {
size_.fetch_sub(1);
return std::unique_ptr<T>(result);
}
idx = (idx + 1) % N;
}
// If we've gone around the whole array once and found no items,
// we should give up.
return nullptr;
}
std::unique_ptr<T> put_item(std::unique_ptr<T> item) noexcept {
assert(item != nullptr);
int idx = postincrement_mod_N(put_idx_);
for (int i=0; i < N; ++i) {
T *expect_null = nullptr;
if (array_[idx].compare_exchange_strong(expect_null, item.get())) {
item.release();
size_.fetch_add(1);
return nullptr;
}
idx = (idx + 1) % N;
}
// If we've gone around the whole array once and found
// no empty slots, we should give up.
return item;
}
std::unique_ptr<T> force_put_item(std::unique_ptr<T> item) noexcept {
assert(item != nullptr);
int idx = postincrement_mod_N(put_idx_);
T *removed_item = array_[idx].exchange(item.release());
if (removed_item == nullptr) {
// We found an empty slot on our first try; excellent.
size_.fetch_add(1);
return nullptr;
} else {
// `item` is now in the pool, but at the cost of `removed_item`.
// Put `removed_item` back in the pool somewhere, if possible.
return put_item(std::unique_ptr<T>(removed_item));
}
}
~AtomicRoundRobinPool() {
for (std::atomic<T*>& elt : array_) {
delete elt.load();
}
}
};
</code></pre>
<p>And here's my example usage. Sadly, I can't think of any good way to unit-test this thing.</p>
<pre><code>#include <chrono>
#include <stdio.h>
#include <string>
#include <thread>
int main() {
AtomicRoundRobinPool<std::string, 10> pool;
auto generate_new_item = [&]() {
static std::atomic<int> i{0};
std::this_thread::sleep_for(std::chrono::milliseconds(200));
return std::make_unique<std::string>(std::to_string(++i));
};
auto producer = [&]() {
for (int i=0; i < 100'000; ++i) {
puts("Producer is generating new item");
auto new_item = generate_new_item();
if (pool.force_put_item(std::move(new_item))) {
puts("Producer put the new item but removed an old one");
} else {
puts("Producer put the new item");
}
}
};
auto consumer = [&]() {
for (int i=0; i < 100'000; ++i) {
std::unique_ptr<std::string> item = pool.get_item();
if (item != nullptr) {
printf("Consumer got item: %s\n", item->c_str());
} else {
puts("Consumer must generate new item");
item = generate_new_item();
// Always put this new item into the pool; it's new blood!
item = pool.force_put_item(std::move(item));
if (item != nullptr) {
puts("Consumer put the new item but removed an old one");
} else {
puts("Consumer put the new item");
}
}
// At this point, we have either item==nullptr or
// item== an item that we got from the pool, which means
// it's been used at least once before.
if (pool.approximate_size() < pool.capacity() / 2) {
// The pool is low; put this item back.
if (item != nullptr) {
if (pool.put_item(std::move(item))) {
puts("Consumer failed to putback the old item");
} else {
puts("Consumer putback the old item");
}
}
}
}
};
std::thread ts[] = {
std::thread(producer),
std::thread(consumer),
std::thread(consumer),
std::thread(consumer),
std::thread(consumer),
std::thread(consumer),
};
for (auto&& t : ts) {
t.join();
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T13:42:25.520",
"Id": "438854",
"Score": "0",
"body": "Isn't it possible for std atomic to use a mutex? If you cannot use a mutex, then you might want to (static_)assert that your atomics are lock free. Or not use atomic."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T17:08:52.730",
"Id": "225780",
"Score": "4",
"Tags": [
"c++",
"c++14",
"collections",
"lock-free",
"atomic"
],
"Title": "C++14 AtomicRoundRobinPool for sharing a pool of keys"
}
|
225780
|
<p>I have the following challenge problem for which I was able to get a solution working, but not in <span class="math-container">\$O(1)\$</span> time as the problem asks for. Could someone point me in the right direction to optimize this? I am also open to other criticisms of my coding style.</p>
<p>QUESTION: </p>
<blockquote>
<p>Implement an LRU (Least Recently Used) cache. It should be able to be initialized with a cache size n, and contain the following methods:</p>
<ul>
<li><p><code>set(key, value)</code>: sets key to value. If there are already n items in the cache and we are adding a new item, then it should also remove the least recently used item.</p></li>
<li><p><code>get(key)</code>: gets the value at key. If no such key exists, return null.</p></li>
</ul>
<p>Each operation should run in <span class="math-container">\$O(1)\$</span> time.</p>
</blockquote>
<p>CODE: </p>
<pre><code>class LRUcache():
def __init__(self,n):
self.vals = dict()
self.max_size = n
def set(self,key,value):
if key in self.vals:
del self.vals[key]
self.vals[key] = value
else:
if(len(self.vals) < self.max_size):
self.vals[key] = value
else:
del self.vals[list(self.vals)[0]]
self.vals[key] = value
def get(self,key):
if key in self.vals:
tempval = self.vals[key]
del self.vals[key]
self.vals[key] = tempval
return self.vals[key]
return None
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T23:44:23.760",
"Id": "438573",
"Score": "1",
"body": "I think that the CS textbooks simplify things, when they claim that hash tables are O(1) containers. The never are. The real hash tables are always O(n), but with a very small C (the implicit mutiplier in the Big O notation). In other words, I do not think you can improve this."
}
] |
[
{
"body": "<p>Your code reads very much like you have written some Java and are trying to translate it to Python. You need to \"drink the Kool-Aid\" and start embracing idiomatic Python, instead.</p>\n\n<p>First, start by noting that storing <code>None</code> as a value is a legitimate thing to do in Python. So the idea of returning <code>None</code> to mean \"no key found\" is weak. A better approach would be to <code>raise</code> an exception -- probably a <code>KeyError</code>.</p>\n\n<p>However, since it's part of your problem statement, we can ignore that issue (except to note that your problem statement likely came from Java or C++ or someplace like that).</p>\n\n<p>In your <code>set()</code> method:</p>\n\n<pre><code>def set(self,key,value):\n if key in self.vals:\n del self.vals[key]\n self.vals[key] = value\n else:\n if(len(self.vals) < self.max_size):\n self.vals[key] = value\n else:\n del self.vals[list(self.vals)[0]]\n self.vals[key] = value\n</code></pre>\n\n<p>You can overwrite items in a dictionary directly. Just assign to them:</p>\n\n<pre><code>if key in self.vals:\n self.vals[key] = value\n</code></pre>\n\n<p>And your missing-key code is redundant. You assign value in both branches of the <code>if/else</code> statement. Just refactor the assignment down:</p>\n\n<pre><code>if len(self.vals) >= self.max_size:\n del self.vals[list(self.vals)[0]]\n\nself.vals[key] = value\n</code></pre>\n\n<p>Once you do that, you realize that the assignment is <em>also</em> present in the upper (key-found) condition, and you can refactor it again:</p>\n\n<pre><code>def set(self, key, value):\n vals = self.vals\n if key in vals and len(vals) >= self.max_size:\n del vals[list(vals)[0]]\n vals[key] = value\n</code></pre>\n\n<p>In your <code>get()</code> method:</p>\n\n<p>You are doing things pretty much spot-on, here, but you are depending on dictionaries to preserve insertion order. That is a somewhat new feature in python (added as an implementation detail in 3.6, and guaranteed in 3.7) that won't work in 3.5. You should at least comment this, and probably should add code at the top of your module to verify the version of python.</p>\n\n<p><strong>On the other hand:</strong> there is a <a href=\"https://docs.python.org/3/library/collections.html?highlight=collections%20ordereddict#collections.OrderedDict\" rel=\"nofollow noreferrer\"><code>collections.OrderedDict</code></a> in the standard library that has been around for a while, and which even includes an example of building an LRU cache in the documentation. Just sayin'. ;-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T23:39:23.183",
"Id": "438572",
"Score": "1",
"body": "I thing you are wrong. Deleting and adding a key-value pair is not going to work the same way as assigning a value by a key. The whole point of doing the way OP did is to alter the internal order of the map. In your case, I think, it won' happen."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T12:17:37.580",
"Id": "438601",
"Score": "0",
"body": "thanks for the tips! My code looks much nicer now!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T20:32:54.397",
"Id": "225794",
"ParentId": "225788",
"Score": "3"
}
},
{
"body": "<p>At first look, it seems like it should be O(1), except for the <code>list(self.vals())[0]</code>.\nTry iterating over the keys instead:</p>\n\n<pre><code>def set(self,key,value):\n if key in self.vals:\n del self.vals[key]\n self.vals[key] = value\n else:\n if(len(self.vals) < self.max_size):\n self.vals[key] = value\n else:\n del self.vals[next(iter(self.vals))] #### changed\n self.vals[key] = value\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T12:11:11.343",
"Id": "438598",
"Score": "0",
"body": "This is just what I was missing, thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T22:25:49.153",
"Id": "225800",
"ParentId": "225788",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "225800",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T18:50:03.320",
"Id": "225788",
"Score": "4",
"Tags": [
"python",
"performance",
"python-3.x",
"programming-challenge",
"cache"
],
"Title": "Least Recently Used Cache Daily Coding Practice"
}
|
225788
|
<p>I want to differentiate between comments I make for </p>
<ul>
<li>(1) myself,</li>
<li>(2) team members,</li>
<li>(3) on business rules,</li>
<li>(4) on watchout notes for hardcoded constants,</li>
<li>(5) on ideas for improvements, and</li>
<li>(6) on general flow of the code.</li>
</ul>
<p>Right now all my comments look the same.</p>
<p>I'm open to any other tools. I don't know how bookmarking works, or if I really should be adding debug points as a "TODO" (the auto "TODO" font is weird and intrusive), but I'm open to anything.</p>
<p>I use PyCharm.</p>
<p>As for what this code accomplishes, it takes in an input of data on students who tested for a Science exam and filters out the students with errors. That means errors in scoring that a school needs to resolve. Therefore, it gives back a highly filtered list of students (200 rows) from a much larger (40,000 rows) dataset.</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import numpy as np
import xlrd
import openpyxl
import win32com.client
import paths
import utils as u
'''
Extraction
'''
# (4) SXRX row starts at row 5
# (4) SXRX has 19 rows at its footer
SXRX_df = pd.read_excel(paths.corr_outputs_path, sheet_name='SXRX', header=4, skipfooter=19)
# (4) drop first row because it's blank
SXRX_df = SXRX_df[1:]
# (5) better to do writer?
corr_outputs_df = pd.read_excel(paths.corr_outputs_path, sheet_name='Correct Outputs')
'''
Operations
'''
def reason_incomplete(school_follow_up, site_follow_up, errors):
"""
We expect mainly P.1 Not Scanned. Teacher errors, while rare, will still exist (especially in Charter schools)
:param school_follow_up: RCSD school follow up
:param site_follow_up: RCSD site follow up
:param errors: RCSD errors, can come in the format of 046/57, sometimes none
:return: text according to business rules
"""
# (2) explicitly cast errors as string, because sometimes it will come in as a float and the "in errors" syntax will
# not work
errors = str(errors)
if school_follow_up == 'P.1 Not Scanned':
return 'P.1 Not Scanned'
elif site_follow_up == 'FOLLOW UP':
return 'P.2 Not Scanned'
elif '40' in errors:
return 'Abs + Response'
elif '41' in errors:
return 'Multiples in Student Answers'
elif '47' in errors:
return 'Omits in Teacher Answers'
elif '46' in errors:
return 'Multiples in Teacher Answers'
else:
return None
df = pd.DataFrame()
# (1) genericize later
df['Last Name'] = SXRX_df['Last Name']
df['First Name'] = SXRX_df['First Name']
df['Student ID'] = SXRX_df['Student Id']
df['School DBN'] = SXRX_df['School DBN']
df['Ofc Cls'] = SXRX_df['Cls']
df['Section'] = SXRX_df['Section']
df['Final Score'] = SXRX_df['Score.1']
df['Reason Incomplete'] = np.vectorize(reason_incomplete)(SXRX_df['Follow Up'],
SXRX_df['Follow Up.1'],
SXRX_df['Errors'])
df['Exam'] = 'SXRX'
# (6) filter out Reason Incomplete Nones
# (6) filter out Final Score INV and MIS
# (6) reorder columns
df = df.reindex(columns=corr_outputs_df.columns)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T20:47:56.180",
"Id": "438558",
"Score": "1",
"body": "Welcome to Code Review. In order to give you proper advice, we must first understand the code ourselves. Please explain what this code accomplishes, ideally with example inputs and outputs. See [ask]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T08:40:36.927",
"Id": "438583",
"Score": "0",
"body": "Are the comments used as temporary TODO's, as a discussion starter, as static information about some code?"
}
] |
[
{
"body": "<h2>Meta discussions vs Code comments</h2>\n\n<p>You should distinguish comments meant for discussion with team members and code comments. Since you work in a team, I take it you have a source control system. For instance, GIT allows to make a <a href=\"https://help.github.com/en/articles/about-pull-requests\" rel=\"nofollow noreferrer\">Pull Request</a>. This means you put your code up for the team to review. Comments can be made on this pull request, rather than polluting the code. You can even set a policy that all comments need to be 'resolved' before the code is allowed to be merged back into the master branch.</p>\n\n<hr>\n\n<h3>Review</h3>\n\n<p>A note on your choice of tags. You use (1) for self and (2) for team members. What if team members use the same system? Who would be the author of tag (1)? Choose your tags more carefully regarding the fact you are a team.</p>\n\n<blockquote>\n <p><em>I want to differentiate between comments I make for</em></p>\n \n <p><em>(1) myself, (2) team members, ..</em></p>\n</blockquote>\n\n<p>Perhaps it's not such a bad thing that TODO's are intrusive. This gives you an additional motivation to refactor the code and work those TODO's out.</p>\n\n<blockquote>\n <p><em>.. the auto \"TODO\" font is weird and intrusive</em></p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T08:49:21.203",
"Id": "225815",
"ParentId": "225789",
"Score": "2"
}
},
{
"body": "<p>I think the major problem with this current system is this: Imagine you come back 6 month after having written these comments and have not used this commenting system elsewhere since then. What category does a comment like <code>(4) ...</code> belong to? Without looking it up! Now imagine someone else looks at your code and needs to figure out which comments are meant for them.</p>\n\n<p><strong>In other words, the system is not self explanatory.</strong></p>\n\n<p>(Ab)using multi-line strings as comments is also discouraged. You are not even using them as multi-line string anyway.</p>\n\n<p>It would already help if you used words instead of numbers. Maybe this is already enough to cover all your cases:</p>\n\n<ul>\n<li><code># TODO NAME note to name</code> or <code># FIXME important bugfix</code></li>\n<li><code># TODO TEAM note to team members</code>,</li>\n<li><code># just plain comments for business rules</code></li>\n<li><code># CONSTANT description</code></li>\n<li><code># NOTE idea for improvement</code></li>\n<li><code># just plain comments on the flow of the code</code></li>\n</ul>\n\n<p>At least in my editor, <code>TODO</code>, <code>FIXME</code> and <code>NOTE</code> all get the same special highlight.</p>\n\n<hr>\n\n<p>Your code itself you should re-organize a bit. Ideally you define all your classes and functions first and put code calling it afterwards. Don't intersperse the two.</p>\n\n<p>The definition of <code>df</code> can also be simplified a bit using extended indexing of <code>pandas</code> dataframes and <code>pandas.DataFrame.rename</code>:</p>\n\n<pre><code>df = SXRX_df[['Last Name', 'First Name', 'Student Id', 'School DBN', 'Cls', 'Section', \n 'Score.1']]\ndf = df.rename(columns={'Cls': 'Ofc Cls', 'Score.1': 'Final Score'})\ndf['Exam'] = 'SXRX'\ndf['Reason Incomplete'] = reason_incomplete(SXRX_df['Follow Up'],\n SXRX_df['Follow Up.1'],\n SXRX_df['Errors'])\n</code></pre>\n\n<p>Note that the columns are in the order in which they appeared in the list, so you might not even need the <code>reindex</code>.</p>\n\n<p>The <code>np.vectorize</code> can also already be used as a decorator at the time of function definition and save some real estate in the block above:</p>\n\n<pre><code>@np.vectorize\ndef reason_incomplete(school_follow_up, site_follow_up, errors):\n ...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T08:52:29.623",
"Id": "225816",
"ParentId": "225789",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "225815",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T19:12:58.037",
"Id": "225789",
"Score": "4",
"Tags": [
"python",
"pandas"
],
"Title": "Ways to differentiate comments in source code (PyCharm)"
}
|
225789
|
<p>I wrote a server-client application in Python where the server sends a never-ending stream of messages to connecting clients. </p>
<p>I was in need for such an architecture since I want to retrieve and process data from a public streaming endpoint, however the company limits the number of active connections to one per user. </p>
<p>With this setup, I can start my server ONCE and then forward the data to any number of connecting clients. This allows me to process data in different ways simultaneously (e.g. one client might write items to a DB, while another calculates some metrics etc.). Further, it allows me to develop a new module and connect it once it is ready for deployment, without interfering with my production modules. </p>
<hr>
<p><strong>Some details:</strong></p>
<p>I send individual variable-length items by prefixing them with their length and then read this number of bytes of on the client side. </p>
<p>To avoid that a buggy client brings down the server, I have a capped message queue for each client and the client gets disconnected once the queue reaches a defined limit. </p>
<hr>
<p>It's my first time writing network code in Python (and in general), so I'm looking for ANY advice or suggestions. </p>
<p><strong>Thanks!</strong></p>
<hr>
<p><strong>Server:</strong></p>
<pre><code>import socket
import struct
import time
from threading import Thread
from queue import Queue
MAX_CLIENTS = 16
MAX_CLIENT_QSIZE = 600
HEADER_FORMAT = struct.Struct('!I')
class _ClientHandler(Thread):
def __init__(self, sock, address, server):
Thread.__init__(self, daemon = True)
self.sock = sock
self.address = address
self.server = server # Reference to server
self.queue = Queue() # Message queue
def _send_item(self, item):
"""Send item to client. Blocks thread."""
self.sock.sendall(HEADER_FORMAT.pack(len(item)))
self.sock.sendall(item.encode('utf-8'))
def run(self):
"""Pop items from queue and sent to client."""
while True:
try:
item = self.queue.get()
self._send_item(item)
except BrokenPipeError:
self.server.delete_client(self.ident)
except OSError:
self.server.delete_client(self.ident)
except:
raise
class StreamServer(Thread):
def __init__(self, address):
Thread.__init__(self, daemon = True)
self.address = address
self._clients = dict()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
"""Disconnect clients and remove client threads when leaving context."""
for ident in self._clients.keys():
self.delete_client(ident)
def queue_item(self, item):
"""Push item to every client queue."""
for ident, client in self._clients.items():
if client.queue.qsize() >= MAX_CLIENT_QSIZE:
print('Client', client.sock.getsockname(), 'reached maximum qsize')
self.delete_client(ident)
client.queue.put(item)
def get_qsizes(self):
"""Get list of client queue sizes."""
return [client.queue.qsize() for _, client in self._clients.items()]
def delete_client(self, ident):
"""Close client socket and delete client thread."""
self._clients[ident].sock.close()
del self._clients[ident] # Delete only client thread reference (garbage collection?)
def run(self):
"""Listen for incomming client connections."""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(self.address)
sock.listen(4)
print('Listening at', sock.getsockname())
while True:
try:
# Refuse connections once client limit reached
while len(self._clients) >= MAX_CLIENTS:
time.sleep(60)
client_sock, client_addr = sock.accept()
client_sock.shutdown(socket.SHUT_RD)
client = _ClientHandler(client_sock, client_addr, self)
print('Connection from', client_sock.getsockname())
client.start()
self._clients[client.ident] = client
except:
# ...
# What exceptions to expect?
raise
if __name__ == '__main__':
with StreamServer(('localhost', 1060)) as server:
server.start() # Start server thread
last_time = time.time()
for item in range(1,1000):
server.queue_item(str(item))
time.sleep(1)
if time.time() - last_time > 10.0:
print('Client queue sizes:', server.get_qsizes())
last_time = time.time()
</code></pre>
<hr>
<p><strong>Client:</strong></p>
<pre><code>import socket
import struct
HEADER_FORMAT = struct.Struct('!I')
class StreamClient():
def __init__(self, address):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect(address)
self.sock.shutdown(socket.SHUT_WR)
print('Connected to', self.sock.getsockname())
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.sock.close()
def _recvall(self, size):
data = b''
while size:
block = self.sock.recv(size)
if not block:
raise EOFError('Socket closed during message transmission')
data += block
size -= len(block)
return data
def __iter__(self):
while True:
try:
(item_size,) = HEADER_FORMAT.unpack(self._recvall(HEADER_FORMAT.size))
yield self._recvall(item_size).decode('utf-8')
except EOFError:
return
except:
# ...
# What exceptions to expect?
raise
if __name__ == '__main__':
with StreamClient(('localhost', 1060)) as stream:
for item in stream:
print(item)
</code></pre>
|
[] |
[
{
"body": "<p>This looks very reasonable, but some improvements are possible:</p>\n\n<h1><code>getsockname()</code> returns the local side's address</h1>\n\n<p>In your code you write:</p>\n\n<pre><code>client_sock, client_addr = sock.accept()\n...\nprint('Connection from', client_sock.getsockname())\n</code></pre>\n\n<p>That should have been <code>client_sock.getpeername()</code>. But you don't need to call any extra function, since the address of the peer is already stored in <code>client_addr</code>, so just write:</p>\n\n<p>print('Connection from', client_addr)</p>\n\n<h1>Avoid transcoding between bytes and strings</h1>\n\n<p>It looks like you call <code>encode('utf-8')</code> in the server, and <code>decode('utf-8')</code> in the client. This sounds a bit redundant. Especially if, as you say, you are receiving data from a socket to a public endpoint, so I assume this already is in a bytes array initially.</p>\n\n<h1>Don't add sleep() calls to your code</h1>\n\n<p>I see this often in code: adding a <code>sleep()</code> here and there to patch around some issue. The problem is that now your code is suddenly becoming unresponsive for the time you are sleeping. And 60 seconds is a long time. What if within that 60 seconds, all clients drop their connections? You could accept lots of new connections during that time, but you can't because you have to wait until the end of that minute. Either just close the connection if you didn't want to accept it, or wait indefinitely, but have some way for a <code>_ClientHandler</code> to wake up the <code>StreamServer</code> as soon as it notices the peer closed its connection.</p>\n\n<h1>Add support for IPv6</h1>\n\n<p>You really should support IPv6 nowadays. It's not hard at all. Depending on which platform you are running on, you might get away with just using <code>AF_UNSPEC</code> instead of <code>AF_INET</code> when creating a listening socket, and it will accept connections from either version of IP. Otherwise, create two listening sockets, one for <code>AF_INET</code> and one for <code>AF_INET6</code>.</p>\n\n<h1>Add graceful shutdown of all threads</h1>\n\n<p>Add a way to shut down threads in a graceful way. To shut down a <code>_ClientHandler</code>, add a special item to the queue that signals that this handler should return from <code>run()</code>. For the <code>StreamServer()</code>, add a flag named <code>running</code> for example that is <code>True</code> by default. In <code>run()</code>, check the flag each iteration of the loop. If it's no longer <code>True</code>, exit the loop. To shutdown in an orderly way, you have to set <code>self.running = False</code>, then create a connection to the listening socket in order to have <code>sock.accept()</code> return.</p>\n\n<p>Don't attempt to just close client sockets or the listening socket. There is no guarantee that this will cause the threads to immediately receive an error.</p>\n\n<h1>Consider using non-blocking sockets</h1>\n\n<p>Instead of having a queue per client, you could instead make use of the TCP send buffer for each client connection. So instead of first enquing some data, you immediately send copies of the data on each client's socket. Now the problem is to know when the send buffer is full. You can do that by making the socket non-blocking using <code>socket.setblocking(False)</code>. When you attempt to write to a non-blocking socket, you will receive an error. If that happens, you can just close the connection.</p>\n\n<p>You can tune the size of the sendbuffer in this way:</p>\n\n<pre><code>socket.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, size)\n</code></pre>\n\n<p>Since you no longer need queues, you also don't need one <code>Thread</code> per client anymore.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T15:27:11.150",
"Id": "439112",
"Score": "0",
"body": "Thank you, these are some very helpful remarks. Is there anything more I can do to improve stability?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T17:46:34.900",
"Id": "439118",
"Score": "1",
"body": "@bi_scholar It looks stable enough to me. But if you have a lot of clients, then at some point you will reach a limit to how many clients you can handle simultaneously. The code will drop client connections when that happens, which is fine in a way (it doesn't crash), but if you need it to be able to handle more clients, then I see two solutions: port the code to C, and/or have one primary StreamServer and several secondary StreamServers that each connect to the primary one. This should provide virtually limitless scalability."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T18:53:09.493",
"Id": "439135",
"Score": "0",
"body": "That makes sense, thanks!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-12T21:41:44.213",
"Id": "226005",
"ParentId": "225796",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "226005",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T21:13:04.580",
"Id": "225796",
"Score": "5",
"Tags": [
"python",
"networking",
"socket",
"server",
"tcp"
],
"Title": "Streaming Messages to multiple Clients"
}
|
225796
|
<p>I am creating an iOS game with In-App purchases for "Coins" and I wish to prevent (or make it very difficult) for the user to simply edit the save-game file and increase the number of "Coins" without paying for them. I am only concerned with non-jailbroken devices.</p>
<p>I have created a <code>GameData</code> class that roughly follows the first part of <a href="https://www.raywenderlich.com/2468-how-to-save-your-game-s-data-part-2-2" rel="nofollow noreferrer">this tutorial</a>, with the following aims:</p>
<ol>
<li>Whenever the game data is saved, a hash is stored in the keychain</li>
<li>Whenever the game data is loaded, if the hash doesn't match the keychain then mark the data as invalid (presumably tampered with)</li>
<li>No false positives: if the data hasn't been tampered with it should not be marked as invalid</li>
</ol>
<p><strong>GameData.swift</strong></p>
<pre><code>import Foundation
import KeychainAccess
import CommonCrypto
enum CodingKeys: CodingKey {
case coins
}
class GameData: Codable {
private static let FILE_NAME = "gamedata.json"
private static let KEYCHAIN_KEY = "GameDataVerification"
private static let keychain = Keychain()
public static let shared: GameData = {
if let gameData = GameData.load() {
return gameData
}
return GameData()
}()
private let queue = DispatchQueue(label: "GameDataSave", qos: .background)
private(set) public var invalid: Bool = false
public var coins: Int
init() {
self.coins = 0
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.coins = try container.decodeIfPresent(Int.self, forKey: .coins) ?? 0
}
func encode(to encoder: Encoder) throws {
let container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.coins, forKey: .coins)
}
public func save() {
// Don't save if the data is invalid.
guard !self.invalid else { return }
self.queue.async {
// TODO: Handle the case that the game data is written successfully but the hash isn't.
do {
// Save the game data to file.
let encoder = JSONEncoder()
let data = try encoder.encode(self)
try data.write(to: GameData.filePath())
// Save the hash of the game data for verification.
try GameData.keychain.set(GameData.hash(data), key: GameData.KEYCHAIN_KEY)
} catch {
print("Unable to save game data:", error)
}
}
}
private static func load() -> GameData? {
do {
// Load the game data from file.
if let data = FileManager.default.contents(atPath: GameData.filePath().path) {
// Load the hash of the saved game data.
let storedHash = try GameData.keychain.get(GameData.KEYCHAIN_KEY)!
// Decode the stored data.
let decoder = JSONDecoder()
let gameData = try decoder.decode(GameData.self, from: data)
// If the hashes don't match, set a flag on the game data.
let hashesMatch = storedHash == GameData.hash(data)
if !hashesMatch {
print("Hashes don't match!")
gameData.invalid = true
}
return gameData
}
print("No game data found.")
return nil
} catch {
print("Unable to load game data:", error)
return nil
}
}
private static func filePath() -> URL {
let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
return url!.appendingPathComponent(GameData.FILE_NAME, isDirectory: false)
}
private static func hash(_ data: Data) -> String {
var digest = [UInt8](repeating: 0, count: Int(CC_SHA512_DIGEST_LENGTH))
data.withUnsafeBytes {
_ = CC_SHA512($0.baseAddress, CC_LONG(data.count), &digest)
}
return digest.map({ String(format: "%02hhx", $0) }).joined(separator: "")
}
}
</code></pre>
<p><strong>Basic usage:</strong></p>
<pre><code>print(GameData.shared.coins)
GameData.shared.coins += 100
GameData.shared.save()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T06:00:35.433",
"Id": "438577",
"Score": "0",
"body": "Is `var coins` the only variable that needs to be saved as game state, or is this a simplified example?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T07:01:10.410",
"Id": "438579",
"Score": "0",
"body": "This is a simplified example; I didn't think there was much point expanding the size of the code sample with 10-20 similar variables."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-08T21:41:45.690",
"Id": "225797",
"Score": "1",
"Tags": [
"swift"
],
"Title": "Preventing tampering with save game data (iOS)"
}
|
225797
|
<p>This is my take on the first challenge on the cryptopals crypto challenges list. I think that i made it quite simple but i feel like it is possible to optimize it further. Any suggestion? </p>
<p>The code:</p>
<pre><code>import qualified Data.HashMap.Strict as HM
import qualified Data.IntMap.Strict as IM
import Data.Maybe
import Data.Char (digitToInt)
import Numeric (readInt)
type BinString = String
type HexString = String
type Base64String = String
base64 = IM.fromList (zip [0..63] (['A'..'Z'] ++ ['a'..'z'] ++ ['0'..'9'] ++ ['+','/']))
hexToBinDict = HM.fromList [('0',"0000"),('1',"0001"),('2',"0010"),('3',"0011"),('4',"0100"),('5',"0101"),
('6',"0110"),('7',"0111"),('8',"1000"),('9',"1001"),('a',"1010"),('b',"1011"),
('c',"1100"),('d',"1101"),('e',"1110"),('f',"1111")]
hexToBase64 :: HexString -> Base64String
hexToBase64 xs = map fromJust [IM.lookup x base64 | x <- base10] ++ padMissingSextets sextets
where base10 = map (fromJust) (map (binToDec) sextets)
sextets = binToSextets (hexToBin xs)
--returns a list of the 4-digit binary encodings of the given string's hex codes
hexToQuartets :: HexString -> [BinString]
hexToQuartets [] = []
hexToQuartets hexCode = fromJust (HM.lookup (head hexCode) hexToBinDict) : hexToQuartets (tail hexCode)
--converts an hex string into a binary string
hexToBin :: HexString -> BinString
hexToBin xs = concat (hexToQuartets xs)
--pads the string with 0's on the right until its a sextet
padRight :: BinString -> BinString
padRight xs = xs ++ (replicate n '0')
where n = 6 - length xs
--returns a list of all full sextets on the string
binToSextets :: BinString -> [BinString]
binToSextets xs = binToSextetsAux (tail xs) [] [head xs] 1
--recursiverly find sextets and pad the last one if necessary
binToSextetsAux :: BinString -> [BinString] -> BinString -> Int -> [String]
binToSextetsAux [] sextets ys _
|length ys == 6 = sextets ++ [ys]
|otherwise = sextets ++ [padRight ys]
binToSextetsAux xs sextets ys i
|i == 6 = binToSextetsAux (tail xs) (sextets ++ [ys]) [head xs] 1
|otherwise = binToSextetsAux (tail xs) sextets (ys ++ [head xs]) (i+1)
--binary string to decimal conversion
binToDec :: Integral a => BinString -> Maybe a
binToDec = fmap fst . listToMaybe . readInt 2 (`elem` "01") digitToInt
--pads with "=" on the right for each empty sextet
--if the length is not divisible by 4, then theres 1 or 2 empty sextets
padMissingSextets :: [BinString] -> BinString
padMissingSextets sextets
|(length sextets) `mod` 4 /= 0 = if (length sextets) `mod` 4 == 2 then "=="
else "="
|otherwise = ""
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>Ok, for starters, it mentions on the first challenge:</p>\n\n<p><strong>Always operate on raw bytes, never on encoded strings. Only use hex and base64 for pretty-printing.</strong></p>\n\n<p>Since <code>String</code> is actually a list of encoded <code>Char</code>s, it would make more sense to migrate to an implementation that uses <a href=\"http://hackage.haskell.org/package/bytestring-0.10.10.0/docs/Data-ByteString.html\" rel=\"noreferrer\"><code>ByteString</code></a> instead. This data structure is suited for handling raw data, like we will be doing here. There is also a very helpful parser library called <a href=\"http://hackage.haskell.org/package/attoparsec\" rel=\"noreferrer\"><code>attoparsec</code></a>. It is a parser combinator library, similar to <code>parsec</code>, but specialized for <code>ByteString</code>. Using it to parse the input as a <code>ByteString</code> makes the most sense in this situation.</p>\n\n<hr>\n\n<h3>Parsing ByteStrings</h3>\n\n<p>A <code>ByteString</code> can be formed from <code>[Word8]</code> using <a href=\"https://hackage.haskell.org/package/bytestring-0.10.10.0/docs/Data-ByteString.html#v:pack\" rel=\"noreferrer\"><code>pack</code></a>, and it can also be broken apart again using <code>unpack</code>. <code>Word8</code> is just an 8-bit unsigned integer, and interestingly, an 8-bit unsigned integer is also what is needed for holding the value a single hex-digit! This means that we can parse two <code>Word8</code>s from <code>'0'</code> to <code>'f'</code> and get a single <code>Word8</code> which holds the encoded number.</p>\n\n<pre><code>import Control.Applicative (liftA2, liftA3, many)\nimport Data.Attoparsec.ByteString.Char8\nimport qualified Data.ByteString as B\nimport Data.ByteString (ByteString, pack, uncons)\nimport Data.Bits (shift)\nimport Data.Char (ord)\n-- The strict version is suitable here\nimport Data.IntMap.Strict (IntMap, fromAscList, (!))\nimport Data.Word8\n\nhexMap :: IntMap Word8\nhexMap = fromAscList $ zip (map ord $ ['0'..'9'] ++ ['a'..'f']) [0..]\n\n\nhex :: Parser Word8\nhex = liftA2 mkWord8 hexChar hexChar\n where\n hexChar :: Parser Word8\n hexChar = choice $ map char8 $ ['0'..'9'] ++ ['a'..'f']\n\n mkWord8 :: Word8 -> Word8 -> Word8\n mkWord8 a b =\n (hexMap ! fromIntegral a) `shift` 4\n + (hexMap ! fromIntegral b)\n\nhexStr :: Parser ByteString\nhexStr = fmap pack (many hex) -- Parser is a Functor\n\nparseHex :: ByteString -> Either String ByteString\nparseHex = parseOnly hexStr\n</code></pre>\n\n<p>Let's take a look at how the <code>hex</code> parser is put together. First, look at the inner functions. <code>mkWord8</code> takes two <code>Word8</code> values and looks both of them up in <code>hexMap</code>. Then, it <em>bit shifts</em> the first result by four bits to the left and adds it to the second result. This means that if the first and second arguments to <code>mkWord8</code> are \"f2\", then we will have <code>11110010</code> stored in the resulting <code>Word8</code>.</p>\n\n<p><code>hexChar</code> is a <code>Parser</code> that matches a single character in the range of <code>['0'..'9']</code> or <code>['a'..'f']</code>. This works by mapping <a href=\"http://hackage.haskell.org/package/attoparsec-0.13.2.2/docs/Data-Attoparsec-ByteString-Char8.html#v:char8\" rel=\"noreferrer\"><code>char8 :: Char -> Parser Word8</code></a> over the list of acceptable characters and then calling <a href=\"http://hackage.haskell.org/package/attoparsec-0.13.2.2/docs/Data-Attoparsec-ByteString-Char8.html#v:choice\" rel=\"noreferrer\"><code>choice :: [Parser Word8] -> Parser Word8</code></a> to indicate that any of the generated parsers will work.</p>\n\n<p>Now, it is easy to understand how <code>hex</code> works. It is a parser that takes two characters and calls <code>mkWord8</code> on the results, assuming both characters match. To extend <code>hex</code> in order to allow for arbitrary numbers of hex-digits, we just need to utilize <a href=\"https://hackage.haskell.org/package/base-4.12.0.0/docs/Control-Applicative.html#v:many\" rel=\"noreferrer\"><code>many :: Parser Word8 -> Parser [Word8]</code></a>, as in <code>many hex</code>. To actually <em>use</em> <code>hex</code>, we can utilize <code>parseOnly</code> which will run a parser and return either the results or a <code>String</code> containing an error message if it fails.</p>\n\n<hr>\n\n<h3>Converting bytes to Base64</h3>\n\n<p>We are halfway to a working solution now that we can parse an incoming hex string into a <code>ByteString</code>. To make it all the way, we need to convert the <code>ByteString</code> into Base64 and print it. This can be done by first converting to something that we are more familiar with, such as decimals, but it may be possible to convert more directly using a little math. Since we know that Base64 uses 6 bits (64 = 2^6) and <code>Word8</code> uses 8 bits, we can conclude that both formats will line up every 24 bits. When this happens, we can convert 3 bytes into 4 Base64 characters. If there aren't 3 bytes left to use, we will have to utilize as much as we can before giving up.</p>\n\n<pre><code>-- These two functions pull 3 items or 2 items from the front of the ByteString,\n-- respectively. (`uncons` pulls one off)\n\nuncons3 :: ByteString -> Maybe ((Word8,Word8,Word8), ByteString)\nuncons3 b = do -- We will use the Monad instance of Maybe by using `do`\n (w1,b1) <- uncons b\n (w2,b2) <- uncons b1\n (w3,b3) <- uncons b2\n Just ((w1,w2,w3), b3)\n\nuncons2 :: ByteString -> Maybe ((Word8,Word8), ByteString)\nuncons2 b = do\n (w1,b1) <- uncons b\n (w2,b2) <- uncons b1\n Just ((w1,w2), b2)\n\n---\n\ntype Base64 = Char -- Might as well use good 'ol Strings again...\n\ntoBase64 :: ByteString -> [Base64] -- [Base64] is equivalent to String\ntoBase64 b =\n case uncons3 b of\n Just ((w1,w2,w3),b') -> from3Bytes w1 w2 w3 ++ toBase64 b' -- loop\n Nothing -> -- Less than 3 bytes left...\n case uncons2 b of\n Just ((w1,w2),b') -> from2Bytes w1 w2\n Nothing -> -- Less than 2 bytes left...\n case uncons b of\n Just (w,b') -> from1Byte w\n Nothing -> [] -- No more data, so end the string\n\nbase64Map :: IntMap Base64\nbase64Map = undefined\n\n-- Convert 3 Word8's to 4 Chars\nfrom3Bytes :: Word8 -> Word8 -> Word8 -> [Base64]\nfrom3Bytes = undefined\n\n-- Convert 2 Word8's to 2 Chars (drop the remainder)\nfrom2Bytes :: Word8 -> Word8 -> [Base64]\nfrom2Bytes = undefined\n\n-- Convert 1 Word8 to 1 Char (drop the remainder)\nfrom1Byte :: Word8 -> [Base64]\nfrom1Byte = undefined\n\n\n</code></pre>\n\n<hr>\n\n<p>I'll leave it up to you to finish up by filling in the <code>undefined</code> portions. Keep in mind that you can do bitwise manipulations with <code>Data.Bits</code>. Obviously you will need to break up the 8-bit <code>ByteString</code>s into smaller chunks in order to reassemble them into 6-bit pieces, and have some mapping from these pieces to their Base64 character representation. I left the stub for <code>base64Map</code> as a reminder of <em>one possible</em> solution here.</p>\n\n<p>There's a lot to digest here, but I think this will give you some other strategies to consider. Good luck and happy coding!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T11:24:19.090",
"Id": "225822",
"ParentId": "225804",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "225822",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T03:08:17.240",
"Id": "225804",
"Score": "1",
"Tags": [
"programming-challenge",
"haskell",
"serialization",
"number-systems",
"base64"
],
"Title": "Hex string to Base64 in Haskell"
}
|
225804
|
<p>I am working on a product-related app where the data model for a product attribute feels too heavy. But I can't split it into several small data models because they are all about goods. </p>
<p>At present, my approach is to parse network data directly into a data model. The properties of the data model are readwrite. For example, when I want to modify a property, I will directly modify it, without copying or reinitializing the new data model.
I know there may be problems with this, but I don't have a better way, if you have, please help me.</p>
<ul>
<li><code>ATProductModel.h</code></li>
</ul>
<pre class="lang-c prettyprint-override"><code>#import "ATBaseModel.h"
NS_ASSUME_NONNULL_BEGIN
typedef NS_ENUM(NSUInteger, ATFilterType) {
ATFilterTypeComplex = 0,
ATFilterTypeSales,
ATFilterTypePrice,
ATFilterTypeVoucher,
};
typedef NS_ENUM(NSUInteger, ATFilterLayoutType) {
ATFilterLayoutTypeNone = 0,
ATFilterLayoutTypeOneRows,
ATFilterLayoutTypeMoreRows,
};
@interface ATProductSubModel : ATBaseModel
@property (copy, nonatomic) NSString *productId;
@property (copy, nonatomic) NSString *productURL;
@property (copy, nonatomic) NSString *productURLShort;
@property (copy, nonatomic) NSString *productIcon;
@property (copy, nonatomic) NSString *title;
@property (copy, nonatomic) NSString *voucher;
@property (copy, nonatomic) NSString *currentPrice;
@property (copy, nonatomic) NSString *price;
@property (copy, nonatomic) NSString *couponURL;
@property (copy, nonatomic) NSString *discountRate;
@property (copy, nonatomic) NSString *endTime;
@property (copy, nonatomic) NSString *couponInfo;
@property (copy, nonatomic) NSString *volume;
@property (copy, nonatomic) NSString *couponStartTime;
@property (copy, nonatomic) NSString *couponEndTime;
@property (copy, nonatomic) NSArray <NSString *>* smallImages;
@property (copy, nonatomic) NSString *shopName;
@property (copy, nonatomic) NSString *shopLogo;
@property (copy, nonatomic) NSString *platType;
@property (copy, nonatomic) NSString *shopScore;
@property (copy, nonatomic) NSString *share;
@property (copy, nonatomic) NSString *shareFee;
@property (copy, nonatomic) NSString *income;
@property (copy, nonatomic) NSString *upIncome;
@property (strong, nonatomic) NSNumber *finished;
+ (instancetype)defaultModel;
@end
@interface ATProductModel : ATBaseModel
@property (strong, nonatomic) NSArray <ATProductSubModel *>* products;
@property (assign, nonatomic) ATFilterLayoutType layoutType;
@property (assign, nonatomic) BOOL recommended;
@end
NS_ASSUME_NONNULL_END
</code></pre>
<ul>
<li><code>ATProductViewController.h</code></li>
</ul>
<pre><code>#import "ATProductModel.h"
NS_ASSUME_NONNULL_BEGIN
@interface ATProductViewController : UIViewController
@property (strong, nonatomic) ATProductSubModel *model;
@end
</code></pre>
<ul>
<li><code>ATProductViewController.m</code></li>
</ul>
<pre><code>#import "ATStringUtil.h"
@implementation ATProductViewController
@property (strong, nonatomic) ATProductModel *productModel;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self defaultModels];
}
- (void)defaultModels{
NSMutableArray *smallImages = [NSMutableArray arrayWithArray:self.model.smallImages];
if (![ATStringUtil containStr:self.model.icon inArr:self.model.smallImages]) {
[smallImages insertObject:self.model.icon atIndex:0];
}
self.model.smallImages = smallImages;
}
@end
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>In terms of number of properties, I wouldn’t worry about that. There are situations where you can have lots of properties. As the philosopher says, “it is what it is.”</p>\n\n<p>Obviously, from a data modeling perspective, what doesn’t feel quite right is to combine product info, coupon info, shop info, etc. into a single object. E.g. products sometimes are eligible for multiple coupons. Or perhaps you’ll be repeating the “shop” information multiple times in your result set.</p>\n\n<p>That having been said, it depends upon what this feed is for: If this is a search result employed within a particular view within the app, then perhaps a fairly flat structure, like yours, is fine (though I might call the object a “search result” rather than a “product”). But if this is for populating a local data store that users can search locally, then I might expect separate objects for the different entity types (a product object, a shop object, etc.). I’d ask myself how often can the same information be repeated in a particular result set. But whether you have a denormalized/flat result set, or a more normalized product database, just depends upon the nature of the API and how this is being used within the app.</p>\n\n<p>The only change that really jumps out at me is that there are several properties that would appear to be numeric types that are captured as strings (e.g. prices, rates, fees, income, etc.). Perhaps your feed returns them as strings, but within your app, you don’t want to have to sprinkle your code with string-to-number conversions so that you can do things like show the user grand totals, convert rates to totals, or the like. I might be inclined to do that string-to-number conversion while parsing the feed (or, better, change the feed to actually return numeric types) and then I’m working purely with numeric types within the app.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T02:33:34.413",
"Id": "442721",
"Score": "0",
"body": "Thank you very much for your answer. According to your suggestion, some attributes can also be packaged into new classes. Some attributes need to be modified to a numeric type.\n\nI have been learning refactoring recently, and controlling variable values is very final. I plan to add an initialization method, all public properties are changed to read-only, and an update method is provided for the properties that need to be modified. I have two problems, the first initialization method is too long, the second one if too many properties need to provide an update method"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T05:28:21.480",
"Id": "442732",
"Score": "0",
"body": "Out of curiosity, why do your properties need update methods vs just enjoying the synthesized setters?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T06:46:22.307",
"Id": "442742",
"Score": "0",
"body": "The property is readable and writable by default, meaning it can be changed anywhere, which is dangerous for the property being used. So modify the property to read-only, but sometimes you need to update the property value, this time I want to provide an updated method. This seems to be the same as the default readable and writable, I also feel a bit strange"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T18:21:27.510",
"Id": "227428",
"ParentId": "225808",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "227428",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T07:33:38.623",
"Id": "225808",
"Score": "2",
"Tags": [
"objective-c",
"ios"
],
"Title": "iOS Attributes in the data model"
}
|
225808
|
<p>This was a simple game I was making in python. Below is the main class. This is more or less of a prototype for the game. Any criticism or advice is welcome.</p>
<p><a href="https://github.com/Dev-AviSingh/SpaceInvaders" rel="nofollow noreferrer">Source Code</a></p>
<pre class="lang-py prettyprint-override"><code>import tkinter as tk
from threading import Thread
from time import time,sleep
from random import randint, choice
import math
from PIL import Image, ImageTk
import Constants
import Entities
class Box(object):
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
def __and__(self, r2):
return (abs(self.x - r2.x) * 2 < (self.width + r2.width)) and (abs(self.y - r2.y) * 2 < (self.height + r2.height))
# The above method is more efficient
#return not (r2.x > (self.x + self.width) or (r2.x + r2.width) < self.x or r2.y > (self.y + self.height) or (r2.y + r2.height) < self.y)
class Bullet(Box):
def __init__(self, canvas = None, x = 0, y = 0, score = None):
self.x = x
self.y = y
self.width = 2
self.height = 10
self.canvas = canvas
self.scoreBoard = score
self.velocity = -10
self.sprite = self.canvas.create_image(x, y, image = ImageTk.PhotoImage(Image.open('./Assets/Bullet/Bullet.png')))
sprite1 = ImageTk.PhotoImage(Image.open('./Assets/Bullet/Bullet.png').resize((self.width, self.height), Image.ANTIALIAS))
self.currentAnimation = Animation(canvas = self.canvas, fps = 5, initialFrame = sprite1, xpos = self.x, ypos = self.y)
self.canvas.tag_raise(self.currentAnimation.currentFrame)
self.dead = False
def deleteNow(self):
self.canvas.delete(self.sprite)
self.currentAnimation = None
def update(self, asteroids):
self.y += self.velocity
for asteroid in asteroids.getAsteroidList():
if self.__and__(asteroid):
asteroid.reset()
self.scoreBoard.score += 20
self.dead = True
break
self.currentAnimation.update(self.x, self.y)
def render(self):
self.currentAnimation.render()
class Animation(object):
def __init__(self, canvas = None, fps = 10, initialFrame = None, xpos = 0, ypos = 0):
self.canvas = canvas
self.xpos = xpos
self.ypos = ypos
self.xvel = 0
self.yvel = 0
self.frames = []
self.frames.append(initialFrame)
self.frameIndex = 0
self.currentFrame = self.canvas.create_image(xpos, ypos, image = self.frames[self.frameIndex])
self.canvas.tag_lower(self.currentFrame)
self.lastTime = time()
self.maxTime = 1 / fps
def addFrame(self, frame):
self.frames.append(frame)
def update(self, xpos, ypos):
self.xpos, self.ypos = self.canvas.coords(self.currentFrame)# This helps in finding the actual position of the sprite as the animation's position and the canvas sprite's position varies after resetting an asteroid, thus this is necessary, I do not know this worked but kindly do not remove this statement.
self.xvel = xpos - self.xpos
self.yvel = ypos - self.ypos
self.xpos = xpos
self.ypos = ypos
elapsed = time() - self.lastTime
if elapsed >= self.maxTime:
self.lastTime - time()
self.frameIndex += 1
if self.frameIndex >= len(self.frames):
self.frameIndex = 0
def render(self):
self.canvas.move(self.currentFrame, self.xvel, self.yvel)
self.canvas.itemconfig(self.currentFrame, image = self.frames[self.frameIndex])
class HealthBar(object):
def __init__(self, canvas = None, x = 0, y = 0, initialHealth = 100, maxHealth = 100):
self.canvas = canvas
self.x = x
self.y = y
self.width = 100
self.height = 5
self.xvel = 0
self.yvel = 0
self.health = initialHealth
self.barOutline = self.canvas.create_rectangle(self.x, self.y, self.x + self.width, self.y + self.height, outline = 'white')
self.barFill = self.canvas.create_rectangle(self.x, self.y, self.x + self.health, self.y + self.height, outline = 'white', fill = 'red')
def update(self, newX, newY, currentHealth):
self.xvel = newX - self.x
self.yvel = newY - self.y
self.x = newX
self.y = newY
self.health = currentHealth
def render(self):
self.canvas.move(self.barFill, self.xvel, self.yvel)
self.canvas.move(self.barOutline, self.xvel, self.yvel)
self.canvas.coords(self.barFill, self.x, self.y, self.x + self.health, self.y + self.height)
class CrashAnimation(object):
def __init__(self, canvas = None, x = 0, y = 0, fps = 3, toTrace = None):
self.canvas = canvas
self.x = x
self.y = y
self.fps = fps
self.toTrace = toTrace
self.frames = []
self.createFrames()
def startAnimation(self):
Thread(target = self.start, args = ()).start()
def createFrames(self):
for x in range(16):
self.frames.append(ImageTk.PhotoImage(
Image.open('./Assets/Explosion/{}.png'.format(x))
))
def start(self):
last = time()
maxTime = 1 / self.fps
self.currentSprite = self.canvas.create_image(self.x, self.y, image = self.frames[0])
for frame in self.frames:
elapsed = time() - last
wait = maxTime - elapsed
if(wait > 0):
sleep(wait)
self.canvas.itemconfig(self.currentSprite, image = frame)
self.canvas.move(self.currentSprite, self.toTrace.x - self.x, self.toTrace.y - self.y)
self.x, self.y = self.toTrace.x, self.toTrace.y
last = time()
if self.currentSprite != None:
self.canvas.delete(self.currentSprite)
del self.x, self.y, self.frames, self.currentSprite
class Player(Box):
def __init__(self, canvas = None, xPos = 0, yPos = 0, xVel = 0, yVel = 0, asteroids = None, entities = None, scoreBoard = None):
self.canvas = canvas
self.x = xPos
self.y = yPos
self.width = 35
self.height = 50
self.xVel = xVel
self.yVel = yVel
self.scoreBoard = scoreBoard
self.health = 100
self.asteroids = asteroids
self.entities = entities
self.firingRate = 5
self.shooting = False
sprite1 = ImageTk.PhotoImage(Image.open('./Assets/SpaceShip/Frame0.png').resize((self.width, self.height), Image.ANTIALIAS))
sprite2 = ImageTk.PhotoImage(Image.open('./Assets/SpaceShip/Frame1.png').resize((self.width, self.height), Image.ANTIALIAS))
sprite3 = ImageTk.PhotoImage(Image.open('./Assets/SpaceShip/Frame2.png').resize((self.width, self.height), Image.ANTIALIAS))
sprite4 = ImageTk.PhotoImage(Image.open('./Assets/SpaceShip/Frame3.png').resize((self.width, self.height), Image.ANTIALIAS))
self.currentAnimation = Animation(canvas = self.canvas, fps = 5, initialFrame = sprite1, xpos = self.x, ypos = self.y)
self.currentAnimation.addFrame(sprite2)
self.currentAnimation.addFrame(sprite3)
self.currentAnimation.addFrame(sprite4)
self.healthBar = HealthBar(canvas = self.canvas, x = self.x - 25, y = self.y - 25, maxHealth = 50)
self.maxInterval = 1 / self.firingRate
self.lastShoot = time()
def update(self):
asteroids = self.asteroids.getAsteroidList()
for asteroid in asteroids:
if(self.__and__(asteroid)):
asteroid.reset()
crash = CrashAnimation(canvas = self.canvas, x = self.x, y = self.y, fps = 60, toTrace = self)
crash.startAnimation()
self.health -= 10
break
if self.xVel < 0:
if self.x <= 15:
self.xVel = 0
elif self.xVel > 0:
if self.x + 15 >= Constants.windowWidth:
self.xVel = 0
if self.yVel < 0:
if self.y <= 0:
self.yVel = 0
elif self.yVel > 0:
if self.y + 50 >= Constants.windowHeight:
self.yVel = 0
if self.shooting:
self.shootBullet()
self.x += self.xVel
self.y += self.yVel
self.currentAnimation.update(self.x, self.y)
self.healthBar.update(self.x - 50, self.y - 40, self.health)
def render(self):
self.currentAnimation.render()
self.healthBar.render()
def getPosition(self):
return self.x, self.y
def moveUp(self, stop = False):
if not stop:
self.vely = -3
else:
self.vely = 0
def moveDown(self, stop = False):
if not stop:
self.vely = 3
else:
self.vely = 0
def moveLeft(self, stop = False):
if not stop:
self.velx = -3
else:
self.velx = 0
def moveRight(self, stop = False):
if not stop:
self.velx = 3
else:
self.velx = 0
def shootBullet(self):
elapsed = time() - self.lastShoot
wait = self.maxInterval - elapsed
if(wait > 0):
return
bullet = Bullet(canvas = self.canvas, x = self.x, y = self.y, score = self.scoreBoard)
self.entities.addBullet(bullet)
self.lastShoot = time()
class Asteroid(Box):
def __init__(self, canvas = None, xpos = 0, ypos = 0):
self.canvas = canvas
self.x = xpos
self.y = ypos
self.width = 30
self.height = 30
self.velx = 0
self.vely = 7
sprite1 = ImageTk.PhotoImage(Image.open('./Assets/Asteroid/Frame0.png').resize((self.width, self.height), Image.ANTIALIAS))
self.currentAnimation = Animation(canvas = self.canvas, fps = 10, initialFrame = sprite1, xpos = self.x, ypos = self.y)
start = randint(1, 20)
for x in range(start, 20):
self.currentAnimation.addFrame(ImageTk.PhotoImage(Image.open('./Assets/Asteroid/Frame{}.png'.format(x)).resize((self.width, self.height), Image.ANTIALIAS)))
for x in range(1, start):
self.currentAnimation.addFrame(ImageTk.PhotoImage(Image.open('./Assets/Asteroid/Frame{}.png'.format(x)).resize((self.width, self.height), Image.ANTIALIAS)))
def update(self):
self.y += self.vely
if self.y > Constants.windowHeight:
self.x = xpos = choice(range(30, Constants.windowWidth - 30, 30))
self.y = ypos = choice(range(-300, 0, 30))
self.currentAnimation.update(self.x, self.y)
self.currentAnimation.update(self.x, self.y)
def render(self):
self.currentAnimation.render()
def reset(self):
self.y = -150
self.x = choice(range(30, Constants.windowWidth - 30, 30))
self.currentAnimation.update(self.x, self.y)
def getPosition(self):
return self.x, self.y
class Asteroids:
def __init__(self, canvas = None, maxNumber = 20):
self.canvas = canvas
self.maxNumber = maxNumber
self.asteroids = []
self.createObstacles()
def createObstacles(self):
for a in range(self.maxNumber):
xpos = choice(range(30, Constants.windowWidth - 30, 30))
ypos = choice(range(-300, Constants.windowHeight - 200, 60))
self.asteroids.append(Asteroid(canvas = self.canvas, xpos = xpos, ypos = ypos))
def createNewObstacle(self):
xpos = choice(range(30, Constants.windowWidth - 30, 30))
ypos = -300
asteroid = Asteroid(canvas = self.canvas, xpos = xpos, ypos = ypos)
for x in range(10):
self.canvas.tag_raise(asteroid)
self.asteroids.append(asteroid)
def getAsteroidList(self):
return self.asteroids
def update(self):
for asteroid in self.asteroids:
asteroid.update()
def render(self):
for asteroid in self.asteroids:
asteroid.render()
class BackGround(object):
def __init__(self, canvas = None, speed = 2):
self.canvas = canvas
self.speed = speed
self.xpos = 200
self.ypos = 350
self.sprite1 = self.sprite2 = ImageTk.PhotoImage(Image.open('./Assets/BackGround/BackGround.png'))
self.s1 = self.canvas.create_image(self.xpos, self.ypos, image = self.sprite1)
self.s2 = self.canvas.create_image(self.xpos, self.ypos - 700, image = self.sprite2)
self.canvas.tag_lower(self.s1)
self.canvas.tag_lower(self.s1)
self.canvas.tag_lower(self.s1)
self.canvas.tag_lower(self.s1)
self.canvas.tag_lower(self.s2)
self.canvas.tag_lower(self.s2)
self.canvas.tag_lower(self.s2)
self.canvas.tag_lower(self.s2)
def update(self):
self.xpos, self.ypos = self.canvas.coords(self.s1)
self.ypos += self.speed
if self.ypos >= Constants.windowHeight + 350:
self.ypos = -700
self.canvas.move(self.s1, 0, -700)
self.canvas.move(self.s2, 0, -700)
def render(self):
self.canvas.move(self.s1, 0, self.speed)
self.canvas.move(self.s2, 0, self.speed)
class Score(object):
def __init__(self, canvas = None, asteroids = None):
self.canvas = canvas
self.score = 0
self.board = self.canvas.create_text(Constants.windowWidth / 2, 50, font = "Jokerman 20 bold italic",
text = "{}".format(self.score), justify = "center", fill = 'white')
self.lastTime = time()
self.maxTime = 1 / 10
self.canvas.tag_raise(self.board)
self.canvas.tag_raise(self.board)
self.canvas.tag_raise(self.board)
self.asteroids = asteroids
def update(self):
elapsed = time() - self.lastTime
self.lastTime - time()
wait = self.maxTime - elapsed
if(wait > 0):
return
else:
self.score += 1
def render(self):
self.canvas.itemconfig(self.board, text = "{}".format(self.score))
class MainWindow(tk.Frame):
def __init__(self, master = None):
super().__init__()
self.master = master
self.windowWidth = 400
self.windowHeight = 700
self.master.geometry("{}x{}".format(self.windowWidth, self.windowHeight))
self.master.resizable(False, False)
self.place(x = 0, y = 0, width = self.windowWidth, height = self.windowHeight)
self.canvas = tk.Canvas(bg = 'black')
self.canvas.place(x = 0, y = 0, width = self.windowWidth, height = self.windowHeight)
self.maxFPS = 60
self.asteroids = Asteroids(canvas = self.canvas, maxNumber = 10)
self.scoreBoard = Score(canvas = self.canvas, asteroids = self.asteroids)
self.player = Player(canvas = self.canvas, xPos = Constants.windowWidth / 2 - 25, yPos = Constants.windowHeight - 10 - 50, asteroids = self.asteroids, scoreBoard = self.scoreBoard)
self.entities = Entities.Entities(self.asteroids, self.player)
self.entities.addEntity(self.scoreBoard)
self.player.entities = self.entities
self.backGround = BackGround(canvas = self.canvas)
self.entities.addEntity(self.backGround)
self.master.bind('<KeyPress>', self.keyPress)
self.master.bind('<KeyRelease>', self.keyRelease)
self.stop = False
self.gameLoop()
self.mainloop()
def keyPress(self, event):
keyCode = event.keycode
if keyCode == Constants.up:
self.player.yVel = -5
elif keyCode == Constants.down:
self.player.yVel = 5
elif keyCode == Constants.left:
self.player.xVel = -5
elif keyCode == Constants.right:
self.player.xVel = 5
elif keyCode == Constants.space:
self.player.shooting = True
else:
pass
def keyRelease(self, event):
keyCode = event.keycode
if keyCode == Constants.up and self.player.yVel < 0:
self.player.yVel = 0
elif keyCode == Constants.down and self.player.yVel > 0:
self.player.yVel = 0
elif keyCode == Constants.left and self.player.xVel < 0:
self.player.xVel = 0
elif keyCode == Constants.right and self.player.xVel > 0:
self.player.xVel = 0
elif keyCode == Constants.space:
self.player.shooting = False
else:
pass
def gameLoop(self):
if self.stop:self.canvas.after(15, self.gameLoop)
maxTime = 1 / self.maxFPS - 0.015
start = time()
self.update()
self.render()
elapsed = time() - start
wait = maxTime - elapsed
if(wait > 0):
sleep(wait)
self.canvas.after(15, self.gameLoop)
def unCrash(self):
for asteroid in self.asteroids.getAsteroidList():
asteroid.reset()
self.player.x = Constants.windowWidth / 2 - 25
self.player.y = Constants.windowHeight - 60
self.entities.player.health = 100
self.scoreBoard.score = 0
self.canvas.delete(self.cover)
self.canvas.delete(self.message)
self.stop = False
def sendCrashedSignal(self):
self.stop = True
self.cover = self.canvas.create_rectangle(0, 0, Constants.windowWidth, Constants.windowHeight, fill = "black")
self.message = self.canvas.create_text(Constants.windowWidth / 2, Constants.windowHeight / 2, font = "Joker 30 bold",
text = "YOUR SHIP \nIS DESTROYED\nYOUR SCORE:{}".format(self.scoreBoard.score), fill = 'white', justify = 'center')
for _ in range(5):
self.canvas.tag_raise(self.cover)
self.canvas.tag_raise(self.message)
self.canvas.after(1000, self.unCrash)
self.stop = False
def update(self):
if(self.entities.update()):
self.sendCrashedSignal()
self.entities.player.health = 100
else:
pass
def render(self):
self.entities.render()
root = tk.Tk()
window = MainWindow(master = root)
</code></pre>
<p>The Entities.py file:</p>
<pre class="lang-py prettyprint-override"><code>
class Entities:
def __init__(self, asteroids = None, player = None):
self.entitiesList = []
self.bullets = []
self.asteroids = asteroids
self.player = player
def addEntity(self, entity):
self.entitiesList.append(entity)
def addBullet(self, bullet):
self.bullets.append(bullet)
def getEntity(self, entity):
for x in self.entitiesList:
if x == entity:
return x
def update(self):
self.asteroids.update()
self.player.update()
for bullet in self.bullets:
bullet.update(self.asteroids)
if bullet.dead:
bullet.deleteNow()
continue
if bullet.y <= 0:
bullet.deleteNow()
self.bullets = [x for x in self.bullets if x.y > 0 and not x.dead]
if(self.player.health <= 0):
return True
for entity in self.entitiesList:
entity.update()
def render(self):
self.asteroids.render()
self.player.render()
for bullet in self.bullets:
bullet.render()
for entity in self.entitiesList:
entity.render()
</code></pre>
<p>And the Constants.py file:</p>
<pre class="lang-py prettyprint-override"><code>windowWidth = 400
windowHeight = 700
# Keycodes
left = 37
right = 39
up = 38
down = 40
space = 32
</code></pre>
|
[] |
[
{
"body": "<p>I noticed you never actually use <code>getEntity(self, entity)</code>. (<a href=\"https://github.com/Dev-AviSingh/SpaceInvaders/blob/master/Entities.py#L16\" rel=\"nofollow noreferrer\">line 16</a> of Entities.py)</p>\n\n<p>It's not a big deal, but you should definitely remove it to avoid confusion down the line, or comment it out in the case that you pan on implementing it later.</p>\n\n<p>I also noticed that you use this little snippet: <code>self.bullets = [x for x in self.bullets if x.y > 0 and not x.dead]</code> on <a href=\"https://github.com/Dev-AviSingh/SpaceInvaders/blob/master/Entities.py#L35\" rel=\"nofollow noreferrer\">line 35</a> of Entities.py</p>\n\n<p>This is all well and good, but I feel that you could take advantage of the following performance boost:</p>\n\n<pre><code>def update(self):\n self.asteroids.update()\n self.player.update()\n\n index = 0\n l = len(self.bullets)\n while index < l:\n bullet = self.bullets[index]\n bullet.update(self.asteroids)\n if bullet.dead or bullet.y <= 0:\n bullet.deleteNow()\n del self.bullets[index]\n l -= 1\n else:\n index += 1\n</code></pre>\n\n<p>This allows you to completely remove line 35, thus removing the need to iterate over <code>self.bullets</code> a second time.</p>\n\n<p>I'll take another look at this later, but for now this is all I can help you with.</p>\n\n<p>Kudos to you for making a game!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-13T03:58:54.697",
"Id": "226013",
"ParentId": "225811",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T08:10:10.927",
"Id": "225811",
"Score": "3",
"Tags": [
"python",
"game",
"tkinter"
],
"Title": "A simple arcade shooter game in python tkinter"
}
|
225811
|
<p>I came across this problem while giving a sample test. </p>
<blockquote>
<p>The problem was that we have given a tree which is undirected. We can
start from any node of our choice. Initially we have power "P" and
while going from one node to other node we loose some power "X"
(consider as cost of travelling) and earn some profit "Y". So we need
to tell that what is the maximum profit that we can earn with a given
power ? Every node can be visited only once.</p>
</blockquote>
<p>Example: First line contains number of nodes and initial power</p>
<p>Next n-1 lines contains node-node-cost-profit</p>
<p>5 4</p>
<p>1 2 1 2</p>
<p>1 3 2 3</p>
<p>1 4 2 4</p>
<p>4 5 2 2</p>
<p>Answer => 7. We can start from 4 and go to 1 and than to 3.</p>
<p>I have applied DFS on this to get maximum profit earned by traversing every single path.</p>
<p>But is there a way to decrease time ??? Can we apply floyd warshall algorithm to calculate distances each edges ?? </p>
<pre><code>from collections import defaultdict
class tree:
def __init__(self,nodes):
self.nodes = nodes
self.graph = defaultdict(list)
def add(self,a,b,charge,profit):
self.graph[a].append([b,charge,profit])
self.graph[b].append([a,charge,profit])
def start(self,power):
maxi = -1
visited = [False for i in range(self.nodes)]
for i in range(1,self.nodes+1):
powers = power
visited[i-1] = True
for j in self.graph[i]:
temp = self.dfs(j,powers,0,visited)
if temp > maxi:
maxi = temp
visited[i-1] = False
return maxi
def dfs(self,node,powers,profit,visited):
v,p,pro=node[0],node[1],node[2]
if powers-p < 0:
return 0
if powers-p == 0:
return profit + pro
profit += pro
powers = powers-p
visited[v-1] = True
tempo = profit
for k in self.graph[v]:
if visited[k[0]-1] == False:
temp = self.dfs(k,powers,tempo,visited)
if temp > profit:
profit = temp
visited[v-1] = False
return profit
t = tree(5)
t.add(1,2,1,2)
t.add(1,3,2,3)
t.add(1,4,2,4)
t.add(4,5,2,2)
print(t.start(4))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T10:38:50.327",
"Id": "440486",
"Score": "1",
"body": "Is it allowed to visit a node more than once? The code assumes that it is not, but the problem description does not say one way or the other. Can you edit the question to make this clear?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T02:17:14.507",
"Id": "440587",
"Score": "0",
"body": "A node can be visited once . Yes, I will modify the question."
}
] |
[
{
"body": "<p>Firstly, use a PEP8 checker. It will raise a lot of issues about whitespace and also tell you to change</p>\n\n<blockquote>\n<pre><code> if visited[k[0]-1] == False:\n</code></pre>\n</blockquote>\n\n<p>to either</p>\n\n<pre><code> if visited[k[0]-1] is False:\n</code></pre>\n\n<p>or</p>\n\n<pre><code> if not visited[k[0]-1]:\n</code></pre>\n\n<hr>\n\n<p>The DFS is far more complicated than necessary:</p>\n\n<ul>\n<li>We don't need <code>visited</code>: given that we know that the graph is a tree, it suffices to track the previous vertex.</li>\n<li>I'm used to DFS tracking vertices, not edges.</li>\n<li>There's no reason for <code>dfs</code> to take <code>profit</code> as an argument: the profit that can be made in a rooted subtree is independent of the profit made getting there.</li>\n</ul>\n\n<p>Rewriting with those notes in mind, we can reduce it to</p>\n\n<pre><code> def start(self, power):\n return max(self.dfs(u, power, None) for u in range(1, self.nodes+1))\n\n def dfs(self, u, power, prev):\n return max((edge[2] + self.dfs(edge[0], power - edge[1], u)\n for edge in self.graph[u]\n if edge[0] != prev and edge[1] <= power),\n default=0)\n</code></pre>\n\n<hr>\n\n<p>However, I think this is still inefficient in some cases. It's doing <span class=\"math-container\">\\$n\\$</span> depth-first searches, for overall time <span class=\"math-container\">\\$\\Theta(n^2)\\$</span>. But those searches are traversing the same vertices. I believe (although I haven't written the code to verify it) that it should be possible to do it in <span class=\"math-container\">\\$\\Theta(np)\\$</span> where <span class=\"math-container\">\\$p\\$</span> is the starting power. The idea would be to do one DFS, but for each subtree to return a complicated structure containing the largest score available solely within that subtree, and the largest scores available from the root of that subtree for different powers (which would obviously be monotonically increasing). Then it would be necessary to combine these.</p>\n\n<p>(Floyd-Warshall is cubic time, so that would be worse. Similarly, matrix-based all-pairs-shortest-path algorithms for general graphs would be worse).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T08:41:00.643",
"Id": "226673",
"ParentId": "225818",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "226673",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T09:20:21.367",
"Id": "225818",
"Score": "4",
"Tags": [
"python",
"algorithm",
"tree",
"graph"
],
"Title": "Maximum profit earned on weighted un-directed tree"
}
|
225818
|
<p>I am beginner in C++ and I was given this assignment by my teacher. The assignment is to print the following shape:</p>
<pre><code> *
* *
* *
* *
* *
* *
*************
</code></pre>
<p>The following is what I have tried and basically it works, but I doubt my code is not simple, there's another way simpler than that. How can I make my code more simpler? Any hints are appreciated.</p>
<pre><code>#include <iostream>
using namespace std;
int main() {
/**
*
* *
* *
* *
* *
* *
*************
*/
int spaces_before = 6; // spaces before printing the stars
int spaces_after = 0; // spaces after printing the first star
int stars = 1;
for (int i = 1; i <= 7; i++) {
for (int j = 1; j <= spaces_before; j++) {
cout << ' ';
}
if (i == 1) {
cout << "*";
} else if (i != 7) {
cout << '*';
for (int j = 1; j <= spaces_after; j++) {
cout << ' ';
}
cout << '*';
} else {
for (int j = 1; j <= stars; j++) {
cout << '*';
}
}
spaces_before--;
if (i == 1) {
spaces_after++;
} else {
spaces_after += 2;
}
cout << '\n';
stars += 2;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>First of all, please avoid <code>using namespace std;</code>. It is considered bad practice and will cause many problems. See <a href=\"https://stackoverflow.com/q/1452721\">Why is <code>using namespace std;</code> considered bad practice?</a> for more information.</p>\n\n<p>Now let's try to simplify the logic. The following loop:</p>\n\n<pre><code>for (int j = 1; j <= spaces_before; j++) {\n cout << ' ';\n}\n</code></pre>\n\n<p>is a very verbose way to write</p>\n\n<pre><code>std::cout << std::string(spaces_before, ' ');\n</code></pre>\n\n<p>(this happened more than one time.)</p>\n\n<p>And you don't need to keep the variables <code>spaces_before</code>, <code>spaces_after</code>, and <code>star</code>. Just calculate them on demand. Also, don't include the special cases in the loop:</p>\n\n<pre><code>#include <iostream>\n#include <string>\n\nint main()\n{\n std::cout << \" *\\n\";\n for (int i = 0; i < 5; ++i)\n std::cout << std::string(5 - i, ' ') << '*'\n << std::string(2 * i + 1, ' ') << \"*\\n\";\n std::cout << std::string(13, '*') << '\\n';\n}\n</code></pre>\n\n<p>This should be enough since you are a beginner. After this is done, it would be very nice if you extract the magic numbers into named constants. And the whole process can be wrapped in a function for reuse:</p>\n\n<pre><code>#include <iostream>\n#include <string>\n\nvoid print(std::ostream& os, int rows)\n{\n os << std::string(rows - 1, ' ') << \"*\\n\";\n for (int i = 1; i < rows - 1; ++i)\n os << std::string(rows - i - 1, ' ') << '*'\n << std::string(2 * i - 1, ' ') << \"*\\n\";\n os << std::string(2 * rows - 1, '*') << '\\n';\n}\n\nint main()\n{\n print(std::cout, 7);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T13:03:42.263",
"Id": "225825",
"ParentId": "225821",
"Score": "3"
}
},
{
"body": "<p>Rather than creating strings (as @L.F. has done) I'd consider using the stream's <code>setw</code> manipulator to place the asterisks as needed (at least for all but the last row).</p>\n\n<p>So, given a width, we can then define a center. For what I'm going to call row 0, the first asterisk gets printed at the center: <code>cout << std::setw(center) << \"*\\n\";</code>.</p>\n\n<p>For rows 1 through N-1, we print two asterisks, one at <code>center-i</code>, and the other at <code>center+i</code>. Unfortunately, those are both relative to the left margin, but what we need for <code>std::setw</code> is relative to the current position on the line, after the previous write. To do that, we have to compute the distance from the left asterisk to the right asterisk. Fortunately, that's pretty simple: one space, then three spaces, then 5 spaces, and so on up to the number of rows we decide to print.</p>\n\n<p>For the final line, we have a number of asterisks followed by a new-line. We certainly could use <code>setw</code> and company to do this as well:</p>\n\n<pre><code>std::cout << std::setfill('*') << std::setw(2*rows) << '\\n';\n</code></pre>\n\n<p>...or we could use a <code>std::string</code>:</p>\n\n<pre><code>std::cout << std::string(2*rows-1, '*') + \"\\n\";\n</code></pre>\n\n<p>I don't see huge advantages or disadvantages to either method though.</p>\n\n<p>For the moment I'll skip over discussing putting the code into a function-- @L.F. has already covered that fairly well, with a couple of exceptions. First, I don't like the name <code>print</code>, which conveys little about what it really does. Second, I'm not entirely excited about combining generating the triangle with actually printing the results to a stream. I'd personally prefer to keep those to aspects separate.</p>\n\n<pre><code>#include <iostream>\n#include <iomanip>\n#include <string>\n#include <sstream>\n\nstd::string triangle(int rows) { \n std::stringstream buf;\n buf << std::setw(rows+1) << \"*\\n\";\n\n for (int i=1; i<rows-1; i++) {\n buf << std::setw(rows-i) << \"*\" << std::setw(2*i+1) << \"*\\n\";\n }\n buf << std::setfill('*') << std::setw(2*rows) << '\\n';\n return buf.str();\n}\n\nint main() { \n const int rows = 7;\n\n std::cout << triangle(rows);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T22:19:26.537",
"Id": "225862",
"ParentId": "225821",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "225825",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T10:50:52.300",
"Id": "225821",
"Score": "4",
"Tags": [
"c++",
"beginner",
"homework",
"ascii-art"
],
"Title": "Draw an outline of an upward-pointing triangle"
}
|
225821
|
<p>I am trying to find a maximum sum of elements in a list where the sum of three consecutive elements is not allowed. So, to find the max sum, you'll have to go through each element sequentially from the first element of the list(<em>Must have first element value in max sum output</em>). You can not select more than two elements in a row.</p>
<p>So, the simple example will be like this:</p>
<blockquote>
<p>Input: <strong>list</strong> = [1, 2, 3, 4, 5]</p>
<p>Possible combination of elements might be like this:</p>
<p>1 = [1, 2, 4, 5] & Sum of elements : 12</p>
<p>2 = [1, 3, 5] & Sum of elements: 9</p>
<p>Output: 12 (Elements used to calculate maximum sum: [1, 2, 4, 5])</p>
<p><strong>Rules followed</strong>:</p>
<p><strong>1</strong>. A must selection of first element of the list.</p>
<p><strong>2</strong>. Traverse through list sequentially.</p>
<p><strong>3</strong>. Can not select more than two elements in a row.(Here in this scenario, selected first two element which is 1 & 2, then skip 3 and choose 4 & 5)</p>
</blockquote>
<p>And I have got the solution, but I would like suggestions on how to make it more efficient.</p>
<p>These are the details of the problem:</p>
<blockquote>
<p><strong>Input format</strong></p>
<p><strong>Line 1</strong>: A single integer N, the number of elements.</p>
<p><strong>Line 2</strong>: List of elements.</p>
<p><strong>Output format</strong></p>
<p>The output consists of a maximum sum of elements</p>
<p><strong>Sample Input</strong>: 1</p>
<p>5</p>
<p>[10, 3, 5, 7, 3]</p>
<p><strong>Sample Output</strong>: 1</p>
<p>23</p>
<p>(<em>Explanation</em>: 10+3+7+3)</p>
<p><strong>Sample Input</strong>: 2</p>
<p>8</p>
<p>[3, 2, 3, 2, 3, 5, 1, 3]</p>
<p><strong>Sample Output</strong>: 2</p>
<p>17</p>
<p>(<em>Explanation</em>: 3+3+3+5+3)</p>
<p><strong>Sample Input</strong>: 3</p>
<p>5</p>
<p>[10, 1, 5, 7, 3]</p>
<p><strong>Sample Output</strong>: 3</p>
<p>22</p>
<p>(<em>Explanation</em>: 10+5+7)</p>
</blockquote>
<p>Now, for this problem, I have managed to provide a solution, which is this one</p>
<pre><code>def get_max_sum(num, input):
output_1 = {'skip': True, 'sum': input[0]+input[1], 0: input[0], 1:input[1]}
output_2 = {'skip': False, 'sum': input[0]+input[2], 0: input[0], 2:input[2]}
main_output = [output_1, output_2]
for i in range(2, num):
for output in main_output:
if output.get(i) is None:
if output['skip']:
output['skip'] = False
continue
if len(input) > i+1:
if input[i] > input[i+1] or output.get(i-1) is None:
output[i] = input[i]
output['sum'] += input[i]
if output.get(i-1) is not None:
output['skip'] = True
else:
output[i+1] = input[i+1]
output['sum'] += input[i+1]
if output.get(i) is not None:
output['skip'] = True
else:
output[i] = input[i]
output['sum'] += input[i]
if main_output[0]['sum'] >= main_output[1]['sum']:
return main_output[0]['sum']
else:
return main_output[1]['sum']
print(get_max_sum(8, [3, 2, 3, 2, 3, 5, 1, 3]))
print(get_max_sum(5, [10, 3, 5, 7, 3]))
print(get_max_sum(5, [10, 1, 5, 7, 3]))
print(get_max_sum(5, [1, 2, 3, 4, 5]))
</code></pre>
<p>And I got the output correct which is this:</p>
<pre><code>17
23
22
</code></pre>
<p>Now the thing is, I am looking for a better version of this. I know this is not the most efficient code and I will appreciate any suggestions to improve this code.</p>
<p>This is <a href="http://www.pythontutor.com/live.html#code=def%20get_max_sum%28num,%20input%29%3A%0A%20%20%20%20output_1%20%3D%20%7B'skip'%3A%20True,%20'sum'%3A%20input%5B0%5D%2Binput%5B1%5D,%200%3A%20input%5B0%5D,%201%3Ainput%5B1%5D%7D%0A%20%20%20%20output_2%20%3D%20%7B'skip'%3A%20False,%20'sum'%3A%20input%5B0%5D%2Binput%5B2%5D,%200%3A%20input%5B0%5D,%202%3Ainput%5B2%5D%7D%0A%20%20%20%20%0A%20%20%20%20main_output%20%3D%20%5Boutput_1,%20output_2%5D%0A%20%20%20%20%0A%20%20%20%20for%20i%20in%20range%282,%20num%29%3A%0A%20%20%20%20%20%20%20%20for%20output%20in%20main_output%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20if%20output.get%28i%29%20is%20None%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20if%20output%5B'skip'%5D%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20output%5B'skip'%5D%20%3D%20False%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20continue%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20if%20len%28input%29%20%3E%20i%2B1%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20if%20input%5Bi%5D%20%3E%20input%5Bi%2B1%5D%20or%20output.get%28i-1%29%20is%20None%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20output%5Bi%5D%20%3D%20input%5Bi%5D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20output%5B'sum'%5D%20%2B%3D%20input%5Bi%5D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20if%20output.get%28i-1%29%20is%20not%20None%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20output%5B'skip'%5D%20%3D%20True%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20output%5Bi%2B1%5D%20%3D%20input%5Bi%2B1%5D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20output%5B'sum'%5D%20%2B%3D%20input%5Bi%2B1%5D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20if%20output.get%28i%29%20is%20not%20None%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20output%5B'skip'%5D%20%3D%20True%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20output%5Bi%5D%20%3D%20input%5Bi%5D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20output%5B'sum'%5D%20%2B%3D%20input%5Bi%5D%0A%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20if%20main_output%5B0%5D%5B'sum'%5D%20%3E%3D%20main_output%5B1%5D%5B'sum'%5D%3A%0A%20%20%20%20%20%20%20%20return%20main_output%5B0%5D%5B'sum'%5D%0A%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20return%20main_output%5B1%5D%5B'sum'%5D%0A%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%20%20%20%0Aprint%28get_max_sum%288,%20%5B3,%202,%203,%202,%203,%205,%201,%203%5D%29%29%0Aprint%28get_max_sum%285,%20%5B10,%203,%205,%207,%203%5D%29%29%0Aprint%28get_max_sum%285,%20%5B10,%201,%205,%207,%203%5D%29%29%0Aprint%28get_max_sum%285,%20%5B1,%202,%203,%204,%205%5D%29%29&cumulative=false&curInstr=233&heapPrimitives=nevernest&mode=display&origin=opt-live.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false" rel="nofollow noreferrer">Code Visualization Link</a>.</p>
<p><strong>EDIT</strong>: I have made some minor changes/improvements in my code. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T13:58:32.393",
"Id": "438606",
"Score": "1",
"body": "This doesn't seem to work for [1,2,3,4,5] for me (but I might not be testing it correctly) (1+2+4+5 = 12, but outputs 9)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T14:03:00.480",
"Id": "438607",
"Score": "0",
"body": "@someone Thanks for replying. Yes, you are right. My bad. let me check."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T14:39:26.957",
"Id": "438611",
"Score": "1",
"body": "The simplest approach I can think of is dynamic programming where dp[current index][number of elements chosen in a row] = highest sum possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T14:53:43.710",
"Id": "438614",
"Score": "0",
"body": "@someone can you provide some general example based on that or psudo-code maybe?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T15:14:37.033",
"Id": "438616",
"Score": "0",
"body": "[Here is some C# code.](https://tio.run/##lVI9T8MwEJ3jX3Fjo5g2TkEMgYmVSkwskQfLcUmk4lTxtSBV/u3hnA/ailLB5Mt77949x6fdjXZ119UWwTWbvZlRVUhQMTuwKKAWHkHNn419wyrvoYJLKLcEW/MB4dtCAoIvJdHrpg0OUBOd5nQ8kIzOJIlZRI5RuS1qnkqiSTZf1fZVbXYmnxjxK5NdYDwLXDr4pRfHn09fLMoGbIOgEM37FgEb8tSbXWnGOYkY3FYKq/lKfc6@QQ5j9jj/q1b8Q5sFbR/xWjZxyUMcs9FLqKI@G5tdbRGnLfQ/W4O71oanLeSBFHZKaKceS46@94pzYJ7tVQtoHD4pZ9zJVkgyYIOPSDksOdxxuKfC8xEmKOuJbKLFKR26xM8uMelvifM@Z/ToRulq3FzUNP0YqN/jl5a4Gepwx6Eedp0QgnzXfQE) You don't have to store all states as they only depend on the previous one (just current and previous are necessary)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T07:50:05.310",
"Id": "438717",
"Score": "0",
"body": "@someone is there a way to understand this code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T11:16:22.797",
"Id": "439396",
"Score": "1",
"body": "Step by step, with practice."
}
] |
[
{
"body": "<p>I don't use Python on a day-to-day basis, so here's a basic improvement (less incredible since you edited your code but still useful). It's pretty straightforward, I just grouped your conditions differently to have less redundances.</p>\n\n<pre><code>def get_max_sum(num, input):\n output_1 = {'skip': True, 'sum': input[0]+input[1], 0: input[0], 1:input[1]}\n output_2 = {'skip': False, 'sum': input[0]+input[2], 0: input[0], 2:input[2]}\n\n main_output = [output_1, output_2]\n\n for i in range(2, num):\n for output in main_output:\n if output.get(i) is not None: #let you save on indentation\n continue\n if output['skip']:\n output['skip'] = False\n continue\n if len(input) > i+1 and input[i] <= input[i+1]: #the special case\n output[i+1] = input[i+1]\n output['sum'] += input[i+1]\n if output.get(i) is not None:\n output['skip'] = True\n else: #all the others\n output[i] = input[i]\n output['sum'] += input[i]\n if output.get(i-1) is not None:\n output['skip'] = True\n\n\n if main_output[0]['sum'] >= main_output[1]['sum']:\n return main_output[0]['sum']\n else:\n return main_output[1]['sum']\n\n\nprint(get_max_sum(8, [3, 2, 3, 2, 3, 5, 1, 3]))\nprint(get_max_sum(5, [10, 3, 5, 7, 3]))\nprint(get_max_sum(5, [10, 1, 5, 7, 3]))\n</code></pre>\n\n<p>As someone pointed in the comment, I'm not sure your code would work on every cases, but I'm here to improve the code, not the solution ^^</p>\n\n<p>Still, consider things like [1, 8, 10, 4, 1] for example.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T15:00:14.727",
"Id": "438615",
"Score": "0",
"body": "Thanks for replying. I haven't tested your code yet. But I have tried above list example and it returns 15, which is I think, correct answer. So far so, my code is working fine. Let see whether we can improve it or not. Main concern for me is, the two dictionary which I initialized in function with some values from the input list."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T15:44:24.100",
"Id": "438619",
"Score": "0",
"body": "@TonyMontana Shouldn't the correct answer be 19 (8+10+1) ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T15:51:08.347",
"Id": "438620",
"Score": "0",
"body": "sorry, it seems I have not cleared this confusion already. The first element of the list must be included in the total sum."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T16:12:43.070",
"Id": "438622",
"Score": "0",
"body": "@Naomis, I have added some examples in the above question. I hope it might clear all confusions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T17:44:22.083",
"Id": "438634",
"Score": "3",
"body": "Since this is Code Review, please explain how your solution is better than the original code, so that we may learn from your thought process. Otherwise this is not a valid answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-11T00:27:47.303",
"Id": "438805",
"Score": "0",
"body": "@200_success : thank you for your feedback, is it better now ?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T14:17:01.513",
"Id": "225830",
"ParentId": "225826",
"Score": "0"
}
},
{
"body": "<p>I don't fully understand your code, but it seems to look only at the presence or absence of the previous element when deciding whether to include the current one, so I constructed a test case and verified that it fails:</p>\n\n<pre><code>print(get_max_sum(6, [10, 10, 0, 0, 10, 10]))\n</code></pre>\n\n<p>should give <code>40</code> but actually gives <code>30</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> if main_output[0]['sum'] >= main_output[1]['sum']:\n return main_output[0]['sum']\n else:\n return main_output[1]['sum']\n</code></pre>\n</blockquote>\n\n<p>doesn't need to be so verbose. Prefer</p>\n\n<pre><code> return max(main_output[0]['sum'], main_output[1]['sum'])\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> output_1 = {'skip': True, 'sum': input[0]+input[1], 0: input[0], 1:input[1]}\n output_2 = {'skip': False, 'sum': input[0]+input[2], 0: input[0], 2:input[2]}\n</code></pre>\n</blockquote>\n\n<p>What you need to keep track of is the <em>current run length</em>, which can be from 0 (previous element not included) to 2 (both previous elements included, so must skip this one). The requirement to include the first element means that a special case is required at the start. So we get</p>\n\n<pre><code> best_by_run_length = [float('-inf'), input[0], float('-inf')]\n for elt in input[1:]:\n best_by_run_length = [\n # Run length 0: don't include elt, preceding run length is unconstrained\n max(best_by_run_length),\n # Run length 1: include elt, preceded by run length of 0\n elt + best_by_run_length[0],\n # Run length 2: include elt, preceded by run length of 1\n elt + best_by_run_length[1]\n ]\n return max(best_by_run_length)\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>print(get_max_sum(8, [3, 2, 3, 2, 3, 5, 1, 3]))\nprint(get_max_sum(5, [10, 3, 5, 7, 3]))\nprint(get_max_sum(5, [10, 1, 5, 7, 3]))\nprint(get_max_sum(5, [1, 2, 3, 4, 5]))\n</code></pre>\n</blockquote>\n\n<p>How do you know that the output is correct? Rather than print the result, it's much more useful to print the comparison of the result against the expected value. Or you could take the testing up a level by using <code>doctest</code> (<a href=\"https://docs.python.org/2/library/doctest.html\" rel=\"nofollow noreferrer\">Python 2</a>, <a href=\"https://docs.python.org/3/library/doctest.html\" rel=\"nofollow noreferrer\">Python 3</a>).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T09:05:36.790",
"Id": "226479",
"ParentId": "225826",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T13:11:19.227",
"Id": "225826",
"Score": "3",
"Tags": [
"python",
"performance"
],
"Title": "Find the best way to get the max sum in a list where sum of three consecutive elements is not allowed"
}
|
225826
|
<p>I was surprised to find that there doesn't seem to be a good "continuous range from <code>start</code> to <code>end</code>" data structure in python. I feel such a structure might be useful. So I made one.</p>
<p>Moreover, from my time answering questions on StackOverflow, a use case that I've seen come up repeatedly is to have a program have differing behavior based on which <em>range</em> of values a given variable falls into. You can normally use <code>dict</code>s to elegantly select different behavior based on the precise value of a range, but if you want to accommodate a whole range of values you basically have to use <code>if</code> statements. So one goal I have for this code is to include it in a <code>RangeDict</code> class that would act kind of like a <code>dict</code> except for each key would be a <code>Range</code> or set of <code>Range</code>s associated with a particular value.</p>
<p>I tried to make the class's interface as similar to an existing data structure (<code>set</code> - a range is, mathematically, similar to a continuous bounded set) as possible. I also wanted the class to be flexible and able to be defined in any reasonale way, hence the large number of branches in the constructor. I also made it so that the class's <code>__str__()</code> method returns a value that can be used directly to construct a new Range. </p>
<p>Most of the error-handling is implicit, to allow as broad a use of the class as possible (so long as <code>start</code> and <code>end</code> can be compared with each other, this class does not care what types they actually are - most non-numeric types will raise errors when compared with each other, which naturally filters out problematic inputs).</p>
<p>The constructor is one of the main things here I hope to get feedback on, as well as "is the documentation acceptable?" and "is this a sensible way to create a data structure like this?".</p>
<hr>
<p>Note that I also have another class I'm not showing yet, called <code>RangeSet</code>. It's just a set-like data structure that contains a set of disjoint ranges all at once. I figured that it should be compatible with a single continuous Range, so I added functionality for that. For now, I'm only interested in reviewing my Range class with respect to other Range objects - <code>RangeSet</code> can have its own review later.</p>
<pre class="lang-py prettyprint-override"><code>class Range:
"""
A class representing a range from a start value to an end value.
The start and end need not be numeric, but they must be comparable.
A Range is immutable, but not strictly so - nevertheless, it should
not be modified directly.
A new Range can be constructed in several ways:
1. From an existing `Range` object
>>> a = Range() # range from -infinity to +infinity
>>> b = Range(a) # copy of a
2. From an iterable representing a range. The first two elements of
the iterable will be taken as start and end respectively.
`start` and `end` may be anything so long as the condition
`start <= end` is True and does not error.
>>> c = Range([3, 5])
>>> d = Range([3, 5], include_start=False, include_end=True)
3. From a string, in the format "[start, end)".
Both '()' (exclusive) and '[]' (inclusive) are valid brackets,
and `start` and `end` must be able to be parsed as floats.
Also, the condition `start <= end` must be True. Brackets
must be present (a ValueError will be raised if they aren't).
If constructing a Range from a string, then include_start and
include_end will be ignored.
>>> e = Range("(-3, 5.5)") # Infers include_start and include_end to both be false
>>> f = Range("[-3, 5.5)") # Infers include_start to be true, include_end to be false
4. From two positional arguments representing `start` and `end`.
`start` and `end` may be anything so long as the condition
`start <= end` is True and does not error. Both `start` and
`end` must be given together as positional arguments; if only
one is given, then the program will try to consider it as an
iterable.
>>> g = Range(3, 5)
>>> h = Range(3, 5, include_start=False, include_end=True)
5. From the keyword arguments `start` and/or `end`. `start` and `end`
may be anything so long as the condition `start <= end` is True and
does not error. If not provided, `start` is set to -infinity by
default, and `end` is set to +infinity by default. If any of the
other methods are used to provide start
and end values for the range, then these keyword arguments will be
ignored.
>>> i = Range(start=3, end=5) # range from 3 to 5
>>> j = Range(start=3) # range from 3 to infinity
>>> k = Range(end=5) # range from -infinity to 5
>>> l = Range(start=3, end=5, include_start=False, include_end=True)
Non-numeric values may be used as arguments, such as dates:
>>> import datetime
>>> m = Range(datetime.date(2016,9,5), datetime.date(2017,3,1))
>>> print(datetime.date(2016,12,31) in m) # True
>>> print(datetime.date(2017,3,15) in m) # False
and strings (using lexicographic comparisons):
>>> n = Range("leaner", "neither")
>>> print("kazoo" in n) # False
>>> print("mouse" in n) # True
>>> print("leader" in n) # False
or any other comparable type.
"""
def __init__(self, *args, **kwargs):
"""
Constructs a new Range from start to end, or from an existing range.
Is inclusive by default (meaning that both bounds are included) but
can be made exclusive by setting include_start and include_end to False.
"""
# process kwargs
start = kwargs.get('start', float('-inf'))
end = kwargs.get('end', float('inf'))
include_start = kwargs.get('include_start', True)
include_end = kwargs.get('include_end', True)
self.include_start = include_start
self.include_end = include_end
# Check how many positional args we got, and initialize accordingly
if len(args) == 0:
# with 0 positional args, initialize from kwargs directly
rng = None
elif len(args) == 1:
# with 1 positional arg, initialize from existing range-like object
if not args[0] and not isinstance(args[0], Range):
raise ValueError("Cannot take a falsey non-Range value as only positional argument")
rng = args[0]
else: # len(args) >= 2:
# with 2 positional args, initialize from given start and end values
start = args[0]
end = args[1]
rng = None
# initialize differently if given a Range vs if given a Start/End.
if rng:
# case 1: construct from Range
if isinstance(rng, Range):
self.start = rng.start
self.end = rng.end
# case 3: construct from String
elif isinstance(rng, str):
pattern = r"(\[|\()\s*([^\s,]+)[,\s]*([^\s,]+)\s*(\]|\))"
match = re.match(pattern, rng)
try:
# check for validity of open-bracket
if match.group(1) == "[":
self.include_start = True
elif match.group(1) == "(":
self.include_start = False
else:
raise AttributeError()
# check for validity of close-bracket
if match.group(4) == "]":
self.include_end = True
elif match.group(4) == ")":
self.include_end = False
else:
raise AttributeError()
# check start and end values
self.start = float(match.group(2))
self.end = float(match.group(3))
except (AttributeError, IndexError):
raise ValueError("Range was given in wrong format. Must be like '(start, end)' "
"where () means exclusive, [] means inclusive")
except ValueError:
raise ValueError("start and end must be numbers")
# case 2: construct from iterable representing start/end
else:
try:
self.start = rng[0]
self.end = rng[1]
except TypeError:
raise ValueError("Given range must be a Range, string, or iterable")
except IndexError:
raise ValueError("Range iterable must contain at least two values")
else:
# case 4 or 5: construct from positional args or kwargs
self.start = start
self.end = end
if start > end:
raise ValueError("start must be less than or equal to end")
# no further initialization should be necessary
def isdisjoint(self, rng):
"""
returns False if this range overlaps with the given range, and True otherwise.
"""
# if RangeSet, return that instead
if isinstance(rng, RangeSet):
return rng.isdisjoint(self)
# convert other range to a format we can work with
try:
if not isinstance(rng, Range):
rng = Range(rng)
except ValueError:
raise TypeError(str(rng) + " is not a range")
# detect overlap
rng_a, rng_b = (self, rng) if self < rng else (rng, self)
return not(rng_a == rng_b or rng_a.end in rng_b or rng_b.start in rng_a)
def union(self, rng):
"""
If this range and the given range overlap, then returns a range that encompasses
both of them. Returns None if the ranges don't overlap.
"""
# if RangeSet, return union of that instead
if isinstance(rng, RangeSet):
return rng.union(self)
# convert other range to a format we can really work with
try:
if not isinstance(rng, Range):
rng = Range(rng)
except ValueError:
raise TypeError("Cannot merge a Range with a non-Range")
# do the ranges overlap?
rng_a, rng_b = (self, rng) if self < rng else (rng, self)
if rng_a.isdisjoint(rng_b):
return None
# merge 'em
new_start = min((rng_a.start, rng_a.include_start), (rng_b.start, rng_b.include_start))
new_end = max((rng_a.end, rng_a.include_end), (rng_b.end, rng_b.include_end))
return Range(start=new_start[0], end=new_end[0], include_start=new_start[1], include_end=new_end[1])
def intersection(self, rng):
"""
Returns a range representing the intersection between this range and the given range,
or None if the ranges don't overlap at all.
"""
# if a RangeSet, then return the intersection of that with this instead.
if isinstance(rng, RangeSet):
return rng.intersection(self)
# convert other range to a format we can work with
try:
if not isinstance(rng, Range):
rng = Range(rng)
except ValueError:
raise TypeError("Cannot overlap a Range with a non-Range")
# do the ranges overlap?
rng_a, rng_b = (self, rng) if self < rng else (rng, self)
if rng_a.isdisjoint(rng_a):
return None
# compute parameters for new intersecting range
new_start = max((rng_a.start, rng_a.include_start), (rng_b.start, rng_b.include_start))
new_end = max((rng_a.end, rng_a.include_end), (rng_b.end, rng_b.include_end))
# create and return new range
return Range(start=new_start[0], end=new_end[0], include_start=new_start[1], include_end=new_end[1])
def difference(self, rng):
"""
Returns a range containing all elements of this range that are not within the
other range, or None if this range is entirely consumed by the other range.
If the other range is entirely consumed by this range, then returns a 2-tuple
of (lower_range, higher_range).
"""
# if a RangeSet, then return the intersection of one of those with this instead.
if isinstance(rng, RangeSet):
return RangeSet((self,)).difference(rng)
# convert other range to a workable format
try:
if not isinstance(rng, Range):
rng = Range(rng)
except ValueError:
raise TypeError("Cannot diff a Range with a non-Range")
# completely disjoint
if self.isdisjoint(rng):
return self
# fully contained
elif self in rng or self == rng:
return None
# fully contained (in the other direction)
elif rng in self:
return (
Range(start=self.start, end=rng.end, include_start=self.include_start, include_end=not rng.include_end),
Range(start=rng.start, end=self.end, include_start=not rng.include_start, include_end=self.include_end)
)
# lower portion of this range
elif self < rng:
return Range(start=self.start, end=rng.start,
include_start=self.include_start, include_end=not rng.include_end)
# higher portion of this range
elif self > rng:
return Range(start=rng.end, end=self.end, include_start=not rng.include_start, include_end=self.include_end)
def symmetric_difference(self, rng):
"""
Returns a 1- or 2-tuple of ranges comprising the parts of self and rng that
do not overlap. Resulting tuples will be sorted from lowest to highest range.
Returns None if the ranges overlap exactly (thus are equal).
"""
# if a RangeSet, then return the symmetric difference of one of those with this instead.
if isinstance(rng, RangeSet):
return rng.symmetric_difference(self)
# convert to range so we can work with it
try:
if not isinstance(rng, Range):
rng = Range(rng)
except ValueError:
raise TypeError("Cannot diff a Range with a non-Range")
# if ranges are equal
if self == rng:
return None
# otherwise, get differences
diff_a = self.difference(rng)
diff_b = rng.difference(self)
# create dummy symmetric difference object
if isinstance(diff_a, tuple):
# diffA has 2 elements, therefore diffB has 0 elements, e.g. (1,4) (2,3) -> (1,2] [3,4)
return diff_a
elif isinstance(diff_b, tuple):
# diffB has 2 elements, therefore diffA has 0 elements, e.g. (2,3) (1,4) -> (1,2] [3,4)
return diff_b
elif diff_a is not None and diff_b is not None:
# diffA has 1 element, diffB has 1 element, e.g. (1,3) (2,4) -> (1,2] [3,4)
return tuple(sorted((diff_a, diff_b)))
elif diff_a is not None:
# diffA has 1 element, diffB has 0 elements, e.g. (1,4) (1,2) -> [2,4)
return diff_a,
else:
# diffA has 0 elements, diffB has 1 element, e.g. (3,4) (1,4) -> (1,3]
return diff_b,
def isempty(self):
"""
Returns True if this range is empty (it contains no values), and False otherwise.
In essence, will only return True if start == end and both ends are exclusive.
"""
return self.start == self.end and not self.include_start and not self.include_end
def copy(self):
""" Returns a copy of this object, similar to calling Range(self) """
return Range(self)
def _above_start(self, item):
if self.include_start:
return item >= self.start
else:
return item > self.start
def _below_end(self, item):
if self.include_end:
return item <= self.end
else:
return item < self.end
def __eq__(self, obj):
"""
Compares the start and end of this range to the other range, along with inclusivity at
either end. Returns True if everything is the same, False otherwise.
"""
try:
return (self.start, self.end, self.include_start, self.include_end) == \
(obj.start, obj.end, obj.include_start, obj.include_end)
except AttributeError:
return False
def __lt__(self, obj):
"""
Used for ordering, not for subranging/subsetting. Compares attributes in
the following order, returning True/False accordingly:
1. start
2. include_start (inclusive < exclusive)
3. end
4. include_end (exclusive < inclusive)
"""
try:
if not isinstance(obj, Range):
obj = Range(obj)
return (self.start, not self.include_start, self.end, self.include_end) < \
(obj.start, not obj.include_start, obj.end, obj.include_end)
except (AttributeError, ValueError, TypeError):
raise TypeError(f"'<' not supported between instances of 'Range' and '{obj.__class__.__name__}'")
def __gt__(self, obj):
"""
Used for ordering, not for subranging/subsetting. Compares attributes in
the following order, returning True/False accordingly:
1. start
2. include_start (inclusive < exclusive)
3. end
4. include_end (exclusive < inclusive)
"""
try:
if not isinstance(obj, Range):
obj = Range(obj)
return (self.start, not self.include_start, self.end, self.include_end) > \
(obj.start, not obj.include_start, obj.end, obj.include_end)
except (AttributeError, ValueError, TypeError):
raise TypeError(f"'<' not supported between instances of 'Range' and '{obj.__class__.__name__}'")
def __ge__(self, obj):
"""
Used for ordering, not for subranging/subsetting. See docstrings for
__eq__() and __gt__().
"""
return self > obj or self == obj
def __le__(self, obj):
"""
Used for ordering, not for subranging/subsetting. See docstrings for
__eq__() and __lt__().
"""
return self < obj or self == obj
def __ne__(self, obj):
"""
See docstring for __eq__(). Returns the opposite of that.
"""
return not self == obj
def __or__(self, other):
"""
Equivalent to self.union(other)
"""
return self.union(other)
def __and__(self, other):
return self.intersection(other)
def __sub__(self, other):
"""
Equivalent to self.difference(other)
"""
return self.difference(other)
def __xor__(self, other):
"""
Equivalent to self.symmetric_difference(other)
"""
return self.symmetric_difference(other)
def __contains__(self, item):
"""
Returns True if the given item is inside the bounds of this range, False if it isn't.
If the given item isn't comparable to this object's start and end objects, then
tries to convert the item to a Range, and returns True if it is completely
contained within this range, False if it isn't.
"""
if isinstance(item, RangeSet):
return all(rng in self for rng in item.ranges())
else:
try:
return self._above_start(item) and self._below_end(item)
except TypeError:
rng_item = Range(item)
return rng_item.start in self and rng_item.end in self
def __len__(self):
""" Returns the size of this range (end - start), irrespective of whether either end is inclusive """
return self.end - self.start
def __hash__(self):
return hash((self.start, self.end, self.include_start, self.include_end))
def __str__(self):
return f"{'[' if self.include_start else '('}{self.start}, {self.end}{']' if self.include_end else ')'}"
def __repr__(self):
return f"range{str(self)}"
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<h3>Design Decision</h3>\n\n<p>You have designed the defaults to be both including the start and end.</p>\n\n<blockquote>\n<pre><code> include_start = kwargs.get('include_start', True)\n include_end = kwargs.get('include_end', True)\n</code></pre>\n</blockquote>\n\n<p>However, for continuous ranges a better default is to exclude the end. Why? Because we cannot expect the values to be discretes (hence, 'continous' range). In continous functions, an included end would need to defined as the excluded end minus some sort of <em>epsilon</em>. This is very tedious and cumbersome practice. </p>\n\n<p>Example in pseudo code: <code>01/01/2000 - 01/01/2001</code> is much cleaner than <code>01/01/2000 - 12/31/2000 23:59:59.999999</code>.</p>\n\n<p>Change your default for the end item to be excluded.</p>\n\n<pre><code> include_start = kwargs.get('include_start', True)\n include_end = kwargs.get('include_end', False)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T17:18:49.580",
"Id": "225836",
"ParentId": "225829",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T13:51:12.507",
"Id": "225829",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"interval"
],
"Title": "Continuous Range class"
}
|
225829
|
<p>A fairly simple program that I tried to write in Common Lisp in order to practice/learn. I'm sure this can be done more elegantly but Lisp's string handling seems to be very werd.</p>
<pre><code>(defun d20 () (+ 1 (random 19)))
(defun initlist (specs)
(let* ((ilist (map 'list #'(lambda (n) `(,(first n) ,(+ (second n) (d20)))) specs))
(sortedilist (sort ilist #'> :key #'second)))
sortedilist))
(defun htmlinitlist (specs)
(apply #'uiop:strcat `("<table><tr><td>&nbsp;</td><td>&nbsp;</td></tr>"
,@(loop for (a b) in (initlist specs) collecting
(format nil "<tr><td>~A</td><td>~A</td></tr><tr><td>&nbsp;</td><td>&nbsp;</td></tr>"
a b))
"</table>")))
(defun htmlinitlists (specs count)
(format nil "~{ ~A~}" (loop for i from 0 to count collecting (htmlinitlist specs))))
</code></pre>
<p>Sample usage from REPL:</p>
<pre><code>(htmlinitlists '(("Elvish" 5) ("Wizgit" 2) ("Alaric" 8) ("Pounder" 6)) 17)
</code></pre>
|
[] |
[
{
"body": "<p><strong>I wouldn't use strings at all. I would write to a stream.</strong></p>\n\n<p>If wished, I would convert the stream to a string.</p>\n\n<pre><code>(defun d20 () (+ 1 (random 19)))\n</code></pre>\n\n<p><code>initlist</code> can be written more compact:</p>\n\n<pre><code>(defun initlist (specs)\n (sort (loop for (a b) in specs collect (list a (+ b (d20))))\n #'> :key #'second))\n</code></pre>\n\n<p>Now we pass a stream to <code>htmlinitlist</code> and write the contents to the stream:</p>\n\n<pre><code>(defun htmlinitlist (specs stream)\n (write-string \"<table><tr><td>&nbsp;</td><td>&nbsp;</td></tr>\" stream)\n (loop for (a b) in (initlist specs) do \n (format stream\n \"<tr><td>~A</td><td>~A</td></tr><tr><td>&nbsp;</td><td>&nbsp;</td></tr>\"\n a b))\n (write-string \"</table>\" stream))\n</code></pre>\n\n<p>If we want to get a string from a stream, we can use <code>with-output-to-string</code>. This binds a stream variable, which we can use and pass around...</p>\n\n<pre><code>(defun htmlinitlists (specs count)\n (with-output-to-string (stream)\n (write-char #\\space stream)\n (loop repeat (1+ count) do (htmlinitlist specs stream))))\n</code></pre>\n\n<p>Alternate version of <code>htmlinitlist</code> using only one <code>FORMAT</code> call:</p>\n\n<pre><code>(defun htmlinitlist (specs stream)\n (format stream\n \"<table><tr><td>&nbsp;</td><td>&nbsp;</td></tr>~\n ~{<tr><td>~A</td><td>~A</td></tr><tr><td>&nbsp;</td><td>&nbsp;</td></tr>~}~\n </table>\"\n (loop for (a b) in (initlist specs) collect a collect b)))\n</code></pre>\n\n<p><strong>Benefit</strong></p>\n\n<p>All the various string operations (which are creating lots of intermediate strings which are immediately garbage) have been replaced with the usual output functions and a stream.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T07:38:39.863",
"Id": "226898",
"ParentId": "225832",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "226898",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T15:54:50.447",
"Id": "225832",
"Score": "1",
"Tags": [
"html",
"formatting",
"dice",
"common-lisp"
],
"Title": "Generating HTML for prerolled d20 RPG initiative tables"
}
|
225832
|
<p>I'm an absolute beginner in programming, and Today I decided to put my knowledge to the test and create a basic c# calculator. I've Done it, but now I'm looking for ways to Make it more shorter and readible. If you Have any suggestions, please give them!</p>
<pre><code>using System;
namespace lol
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hi! What is your name?");
string name = Console.ReadLine();
Console.WriteLine(name + " What do you wanna do");
Console.WriteLine("Type \"+\" for addition");
Console.WriteLine("Type \"-\" for subtraction");
Console.WriteLine("Type \"*\" for multiplication");
Console.WriteLine("Type \"/\" for division");
string operation = Console.ReadLine();
Console.Write("Now, Give me number one: ");
double num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Now give me number two: ");
double num2 = Convert.ToDouble(Console.ReadLine());
if (operation == "+")
{
Console.WriteLine(num1 + num2);
}
else if (operation == "-")
{
Console.WriteLine(num1 - num2);
}
else if (operation == "*")
{
Console.WriteLine(num1 * num2);
}
else
{
Console.WriteLine(num1 / num2);
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T17:14:20.783",
"Id": "438626",
"Score": "1",
"body": "I like your namespace `lol` :-P btw, you write four times _Type X for addition_"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T17:15:42.980",
"Id": "438628",
"Score": "0",
"body": "@t3chbot I'm so Sorry that is a mistake on my part. I'll edit the comment. Thanks for pointing it out!"
}
] |
[
{
"body": "<h2>Compactness</h2>\n\n<ul>\n<li>use a <code>switch</code> statement rather than verbose <code>if-elseif-..</code> statements</li>\n<li>get rid of redundant blank lines</li>\n</ul>\n\n<hr>\n\n<h2>Readability</h2>\n\n<p>Avoid escaping characters.</p>\n\n<blockquote>\n<pre><code>Console.WriteLine(\"Type \\\"+\\\" for addition\");\nConsole.WriteLine(\"Type \\\"-\\\" for subtraction\");\nConsole.WriteLine(\"Type \\\"*\\\" for multiplication\");\nConsole.WriteLine(\"Type \\\"/\\\" for division\");\n</code></pre>\n</blockquote>\n\n<p>You could go with..</p>\n\n<pre><code>Console.WriteLine(\"Type '+' for addition\");\nConsole.WriteLine(\"Type '-' for subtraction\");\nConsole.WriteLine(\"Type '*' for multiplication\");\nConsole.WriteLine(\"Type '/' for division\");\n</code></pre>\n\n<p>Or..</p>\n\n<pre><code>Console.WriteLine(@\"Type \"\"+\"\" for addition\");\nConsole.WriteLine(@\"Type \"\"-\"\" for subtraction\");\nConsole.WriteLine(@\"Type \"\"*\"\" for multiplication\");\nConsole.WriteLine(@\"Type \"\"/\"\" for division\");\n</code></pre>\n\n<hr>\n\n<h2>User Experience</h2>\n\n<p>If you ever wish to design end-user interfaces, you have to work on your lingo. </p>\n\n<p>You're off to a good start:</p>\n\n<blockquote>\n<pre><code>Console.WriteLine(\"Hi! What is your name?\");\n</code></pre>\n</blockquote>\n\n<p>You slip up slightly next (forgot a question mark):</p>\n\n<blockquote>\n<pre><code>Console.WriteLine(name + \" What do you wanna do\");\n</code></pre>\n</blockquote>\n\n<p>But then you start pressuring the end-user. You expect a number, not in a moment, but <code>Now</code>! And you are not asking, you are demanding.</p>\n\n<blockquote>\n<pre><code>Console.Write(\"Now, Give me number one: \");\n</code></pre>\n</blockquote>\n\n<p>Also, one time with a comma and capital after it, and one time the other way around:</p>\n\n<blockquote>\n<pre><code>Console.Write(\"Now give me number two: \");\n</code></pre>\n</blockquote>\n\n<p>The user may also expect this application to crash on:</p>\n\n<ul>\n<li><code>double num1 = Convert.ToDouble(Console.ReadLine());</code></li>\n<li><code>double num2 = Convert.ToDouble(Console.ReadLine());</code></li>\n<li><code>Console.WriteLine(num1 / num2); // when num2 is 0</code></li>\n<li>Any other overflow</li>\n</ul>\n\n<p>And nothing happens when an unknown operator is provided by the user.</p>\n\n<p>The user is not able to verify the results, since the application immediately terminates after the calculation is evaluated.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T17:48:30.087",
"Id": "438637",
"Score": "1",
"body": "Thank you for the review! I'll work on my hospitality a little. I was too excited to work on my first proper program and I forgot the Question marks. And I'm aware about the Bug, but I'm not sure how to fix it. Could you please Explain how to do it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T17:49:00.400",
"Id": "438638",
"Score": "1",
"body": "You may add the thrid alternative with `@\"Type \"\"+\"\" for addition\"`... let's not write a custom format-provider that would add those quotation marks for us just yet ;-P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T17:51:45.697",
"Id": "438639",
"Score": "0",
"body": "The divide by zero bug?: https://docs.microsoft.com/en-us/dotnet/api/system.dividebyzeroexception?view=netframework-4.8"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T17:54:11.103",
"Id": "438641",
"Score": "0",
"body": "@t3chb0t I was thinking of adding string interpolation, but that wouldn't really help readability here :p"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T17:56:10.163",
"Id": "438643",
"Score": "0",
"body": "...only if you made it a loop running over operators and their strings. Otherwise I'm on your side. It's just four strings."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T17:39:18.333",
"Id": "225838",
"ParentId": "225834",
"Score": "3"
}
},
{
"body": "<p>You solution look fine so far (maybe to much empty lines, but that's just peanuts ;)).</p>\n\n<p>If you are intested in a more object oriented approach, I'll show you an alternative solutions. It looks (and is) quite overengineert for such a simple problem - but for real problems it is often a good choice :).</p>\n\n<p>First, abstract the 4 mathematical operations and it's attributes. That allows to define it once and use it gernerally.</p>\n\n<p><strong>Class Operation</strong></p>\n\n<pre><code>public class Operation\n{\n public Operation(string name, string op, Func<double, double, double> action)\n {\n this.Name = name;\n this.Operator = op;\n this.Calc = action;\n }\n\n public string Name { get; }\n public string Operator { get; }\n public Func<double, double, double> Calc { get; } \n}\n</code></pre>\n\n<p>Note that <code>Func<double, double, double></code> is a so called delegate that can handle methods like variables. <code>(a, b) => a + b</code> is a lamda expression which is shorthand for <code>private double Add(a, b) { return a + b; }</code>.</p>\n\n<p><strong>Model definition</strong></p>\n\n<p>Here we define the available operations. </p>\n\n<pre><code>// define the available operations\nvar operations = new Operation[]\n{\n new Operation(\"addition\", \"+\", (a, b) => a + b),\n new Operation(\"subtraction\", \"-\", (a, b) => a - b),\n new Operation(\"multiplication\", \"*\", (a, b) => a * b),\n new Operation(\"division\", \"/\", (a, b) => a / b),\n};\n</code></pre>\n\n<p><strong>Generic processing code</strong></p>\n\n<p>The actually proccing code is generic and uses only the abstractions:</p>\n\n<pre><code>// loop over all operations\nforeach (var o in operations)\n{\n // and print a generic info message\n Console.WriteLine($\"Type \\\"{o.Operator}\\\" for {o.Name}.\");\n}\n\nvar opName = Console.ReadLine();\n// try to get the operation based on the name\nvar op = operations.FirstOrDefault(o => o.Operator == opName);\n\n// print error if operation is not available\nif (op == null)\n{\n Console.Write(\"Invalid Operator!\");\n Environment.Exit(-1);\n}\n\nConsole.Write(\"Now, Give me number one: \");\n// try to parse the input and print an error if number is not valid\nif (!double.TryParse(Console.ReadLine(), out var num1))\n{\n Console.WriteLine(\"Invalid Number!\");\n Environment.Exit(-1);\n}\n\nConsole.Write(\"Now give me number two: \");\nif (!double.TryParse(Console.ReadLine(), out var num2))\n{\n Console.WriteLine(\"Invalid Number!\");\n Environment.Exit(-1);\n}\n\n// use the delegate of the operation to do the actual calculation\nConsole.WriteLine(op.Calc(num1, num2));\n</code></pre>\n\n<p>The nice thing about that approch is that</p>\n\n<ul>\n<li>Any changes to the operations (e.g. adding new ones) does not require to understand the processing code</li>\n<li>The processing code is not redundant (changes has to be done once).</li>\n</ul>\n\n<p>Compare the necessary changes of the following use cases with your solution:</p>\n\n<ul>\n<li>Adding a new operation '%'. How many locations must be adjusted?</li>\n<li>Change the text of the string that \"Type \"[op]\" for [Name]\" How many locations must be adjusted?</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T19:02:29.433",
"Id": "438654",
"Score": "0",
"body": "Thank you for that! It does seem a little Complicated, but that’s probably Because I’m still a beginner. Thanks again! :) I’ll learn from this!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T19:57:36.637",
"Id": "438667",
"Score": "0",
"body": "This isn't necessarily cleaner... and the `for` without `{}` is actually terrible :-P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T19:59:12.990",
"Id": "438668",
"Score": "1",
"body": "It looks like you might have forgotten to include the `Operation` class... where you use lambdas and does not explain them. I bet OP has no idea what this code is about :-\\"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T20:30:18.573",
"Id": "438674",
"Score": "0",
"body": "ups, thanks fo the hint @t3chb0t ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T21:11:42.017",
"Id": "438683",
"Score": "0",
"body": "@t3chb0t I agree with t3chb0t. Since OP is a rookie, perhaps it's best to explain the code step by step. Specially the more advanced parts."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T05:57:51.833",
"Id": "438710",
"Score": "1",
"body": "You are absolutly right. I updated my answer with more explaination."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T18:45:30.183",
"Id": "225843",
"ParentId": "225834",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T17:08:46.777",
"Id": "225834",
"Score": "6",
"Tags": [
"c#",
"beginner",
"console",
"calculator"
],
"Title": "Basic console calculator with four operations"
}
|
225834
|
<p>This code works as is but I'd like to learn if there's any way it could be simplified or cleaner looking.</p>
<p>There are 3 dropdowns. Each dropdown's list of options are based on a single array of options. </p>
<p>If DD1 is set to 'A', DD2 is set to 'B', and DD3 is set to 'C' - while the options are ['A', 'B', 'C', 'D'] - One dropdown cannot select an option that is already in use by another dropdown.</p>
<p>In this situation, for example, DD1 would only allow you to choose from 'A' or 'D' because the other letters are already being used.</p>
<p><strong>Parent</strong></p>
<pre><code><ManageContactOrder options={['A', 'B', 'C', 'D']} order={{1: 'A', 2: 'B', 3: 'C'} action={this.getUpdatedOrder}/>
</code></pre>
<p><strong>Child</strong></p>
<pre><code>class ManageContactOrder extends Component {
constructor(props){
super(props)
let config = this.updateDropdownOptions();
this.state = {
order: config[0],
availableOptions1: config[1],
availableOptions2: config[2],
availableOptions3: config[3]
}
}
updateDropdownOptions(orderPassedIn){
let options = this.props.options;
let order = orderPassedIn ? orderPassedIn : this.props.order;
let availableOptions1 = options.filter(option => !Object.values(order).includes(option));
availableOptions1.push(order[1]);
let availableOptions2 = options.filter(option => !Object.values(order).includes(option));
availableOptions2.push(order[2]);
let availableOptions3 = options.filter(option => !Object.values(order).includes(option));
availableOptions3.push(order[3]);
return [order, availableOptions1, availableOptions2, availableOptions3]
}
onChange = async (e, contactNumber) => {
let selectedValue = e.target.value;
let order = this.state.order;
order[contactNumber] = selectedValue;
let config = this.updateDropdownOptions(order);
this.props.action(order);
this.setState({
order: config[0],
availableOptions1: config[1],
availableOptions2: config[2],
availableOptions3: config[3]
});
}
render() {
const { order, availableOptions1, availableOptions2, availableOptions3 } = this.state;
return (
<>
<DropDown
options={availableOptions1}
name='contact-order-one'
id='contact-order-one'
onChange={e => this.onChange(e, 1)}
fieldValue={order[1]}
data-testid='contact-order-one'
/>
<DropDown
options={availableOptions2}
name='contact-order-two'
id='contact-order-two'
onChange={e => this.onChange(e, 2)}
fieldValue={order[2]}
data-testid='contact-order-two'
/>
<DropDown
options={availableOptions3}
name='contact-order-three'
id='contact-order-three'
onChange={e => this.onChange(e, 3)}
fieldValue={order[3]}
data-testid='contact-order-three'
/>
</>
)
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T17:15:22.617",
"Id": "438627",
"Score": "0",
"body": "So we can assume what you have is working as intended?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T17:29:40.583",
"Id": "438631",
"Score": "0",
"body": "It is working as intended, yes. @πάνταῥεῖ"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T17:35:56.110",
"Id": "438632",
"Score": "0",
"body": "_\"I realize, as it is, the updated values won't be sent back up.\"_ So that's intended?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T17:41:19.867",
"Id": "438633",
"Score": "0",
"body": "Yes. My main focus right now is only maintaining what is happening inside of the child component. @πάνταῥεῖ"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T17:46:33.477",
"Id": "438635",
"Score": "0",
"body": "It sends the new order back up to the parent now. Take a look. Should be less confusing now... @πάνταῥεῖ"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-09T17:13:50.600",
"Id": "225835",
"Score": "0",
"Tags": [
"form",
"react.js",
"jsx"
],
"Title": "Using multiple dropdowns that have a single source of options"
}
|
225835
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.