body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>This is a follow-up question for the previous questions about recursive functions, including <a href="https://codereview.stackexchange.com/q/250743/231235">A Summation Function For Arbitrary Nested Vector Implementation In C++</a>, <a href="https://codereview.stackexchange.com/q/252053/231235">A recursive_count_if Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>, <a href="https://codereview.stackexchange.com/q/252225/231235">A recursive_count_if Function with Specified value_type for Various Type Arbitrary Nested Iterable Implementation in C++</a>, <a href="https://codereview.stackexchange.com/q/252325/231235">A recursive_count_if Function with Automatic Type Deducing from Lambda for Various Type Arbitrary Nested Iterable Implementation in C++</a> and <a href="https://codereview.stackexchange.com/q/252404/231235">A recursive_count_if Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++</a>. In order to test these functions for arbitrary nested iterables, I am trying to implement some arbitrary nested iterable generators to construct nested <code>std::vector</code>s and nested <code>std::array</code>s with the given parameters. The generator for <code>std::array</code> case is named <code>n_dim_array_generator</code> and another generator for <code>std::vector</code> is named <code>n_dim_vector_generator</code>. After trying to use <code>if constexpr</code> syntax in <a href="https://codereview.stackexchange.com/q/252404/231235">the previous question</a>, I found that it is possible to use the similar technique in <code>n_dim_array_generator</code> function and <code>n_dim_vector_generator</code> function.</p>
<p><strong>The usage description</strong></p>
<p>For example, <code>auto test_vector = n_dim_vector_generator<2, int>(1, 3);</code> is expected to create a "test_vector" object which type is <code>std::vector<std::vector<int>></code>. The content of this <code>test_vector</code> should as same as the following code.</p>
<pre><code>std::vector<int> vector1;
vector1.push_back(1);
vector1.push_back(1);
vector1.push_back(1);
std::vector<std::vector<int>> test_vector;
test_vector.push_back(vector1);
test_vector.push_back(vector1);
test_vector.push_back(vector1);
</code></pre>
<p>There are four key part in the usage <code>n_dim_vector_generator<2, int>(1, 3)</code>. The first number <code>2</code> represents the nested layers, the second parameter <code>int</code> represents the type of base elements, the third parameter <code>1</code> represents the input element which would be filled in, and the fourth parameter <code>3</code> represents the element count in each layer.</p>
<p>In the <code>n_dim_array_generator</code> function, the first parameter also represents the nested layers, but the parameter which represents the element count in each layer has been moved into the second one. Then, the third parameter represents the type of base elements and the fourth parameter represents the input element which would be filled in.</p>
<p><strong>The experimental implementation</strong></p>
<p>The experimental implementation of <code>n_dim_vector_generator</code> function and <code>n_dim_array_generator</code> function:</p>
<pre><code>template<std::size_t dim, class T>
auto n_dim_vector_generator(T input, std::size_t times)
{
if (dim < 0)
{
throw std::logic_error("Dimension can not be set less than 0");
}
if constexpr (dim == 0)
{
return input;
}
else
{
std::vector<decltype(n_dim_vector_generator<dim - 1>(input, times))> output;
for (size_t i = 0; i < times; i++)
{
output.push_back(n_dim_vector_generator<dim - 1>(input, times));
}
return output;
}
}
template<std::size_t dim, std::size_t times, class T>
auto n_dim_array_generator(T input)
{
if (dim < 0)
{
throw std::logic_error("Dimension can not be set less than 0");
}
if constexpr (dim == 0)
{
return input;
}
else
{
std::array<decltype(n_dim_array_generator<dim - 1, times>(input)), times> output;
for (size_t i = 0; i < times; i++)
{
output[i] = n_dim_array_generator<dim - 1, times>(input);
}
return output;
}
}
</code></pre>
<p><strong>Test cases</strong></p>
<p>The test cases of <code>n_dim_vector_generator</code> function and <code>n_dim_array_generator</code> function are as below.</p>
<pre><code>// n_dim_vector_generator function usage with recursive_reduce function and recursive_count_if function
auto test_vector1 = n_dim_vector_generator<3, int>(3, 2);
std::cout << "recursive_reduce output: " << recursive_reduce(test_vector1, 0) << std::endl;
std::cout << "recursive_count_if output: " << recursive_count_if<3>(test_vector1, [](auto& i) {return i == 3; }) << std::endl;
// n_dim_array_generator function usage with recursive_reduce function and recursive_count_if function
auto test_array1 = n_dim_array_generator<3, 2, int>(3);
std::cout << "recursive_reduce output: " << recursive_reduce(test_array1, 0) << std::endl;
std::cout << "recursive_count_if output: " << recursive_count_if<3>(test_array1, [](auto& i) {return i == 3; }) << std::endl;
</code></pre>
<p>The output of this test is as follows.</p>
<pre><code>recursive_reduce output: 24
recursive_count_if output: 8
recursive_reduce output: 24
recursive_count_if output: 8
</code></pre>
<p><a href="https://godbolt.org/z/n88s7z" rel="nofollow noreferrer">A Godbolt link is here.</a></p>
<p>All suggestions are welcome.</p>
<p>The summary information:</p>
<ul>
<li><p>Which question it is a follow-up to?</p>
<p><a href="https://codereview.stackexchange.com/q/250743/231235">A Summation Function For Arbitrary Nested Vector Implementation In C++</a>,</p>
<p><a href="https://codereview.stackexchange.com/q/252053/231235">A recursive_count_if Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>,</p>
<p><a href="https://codereview.stackexchange.com/q/252225/231235">A recursive_count_if Function with Specified value_type for Various Type Arbitrary Nested Iterable Implementation in C++</a>,</p>
<p><a href="https://codereview.stackexchange.com/q/252325/231235">A recursive_count_if Function with Automatic Type Deducing from Lambda for Various Type Arbitrary Nested Iterable Implementation in C++</a> and</p>
<p><a href="https://codereview.stackexchange.com/q/252404/231235">A recursive_count_if Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++</a></p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<p>The <code>n_dim_vector_generator</code> function and <code>n_dim_array_generator</code> function are the key part here.</p>
</li>
<li><p>Why a new review is being asked for?</p>
<p>I am not sure if it is a good idea to throw <code>std::logic_error</code> in the situation of <code>Dimension is set less than 0</code>. If there is any further possible improvement, please let me know.</p>
</li>
</ul>
|
[] |
[
{
"body": "<h1>Unnecessary check for <code>dim < 0</code></h1>\n<p>Since <code>dim</code> is a <code>std::size_t</code>, it can never be negative, so this check is redundant.</p>\n<h1>Reserve spaces in vectors</h1>\n<p>If you know what the size of a vector is going to be up front, <code>reserve()</code> space for the elements to avoid unnecessary memory operations.</p>\n<h1>Prefer <code>emplace_back()</code> over <code>push_back()</code> where possible</h1>\n<p>In <code>n_dim_vector_generator()</code> you can use <code>emplace_back()</code> instead of <code>push_back()</code>. It will probably not matter much with an optimizing compiler, but this way you avoid a move operation each time you add an item.</p>\n<h1>Consider using <code>std::fill()</code></h1>\n<p>At least in <code>n_dim_array_generator()</code>, you can use <a href=\"https://en.cppreference.com/w/cpp/algorithm/fill\" rel=\"noreferrer\"><code>std::fill()</code></a> or <a href=\"https://en.cppreference.com/w/cpp/algorithm/fill_n\" rel=\"noreferrer\"><code>std::fill_n()</code></a> to fill the array you created:</p>\n<pre><code>std::array<decltype(n_dim_array_generator<dim - 1, times>(input)), times> output;\nstd::fill(std::begin(output), std::end(output), n_dim_array_generator<dim - 1, times>(input));\nreturn output;\n</code></pre>\n<p>You could also do this with <code>n_dim_vector_generator()</code> if you <code>resize()</code> the vector before filling it, but that causes unnecessary default construction of elements right before they are overwritten again, or you could combine it with <a href=\"https://en.cppreference.com/w/cpp/iterator/back_inserter\" rel=\"noreferrer\"><code>std::back_inserter()</code></a>, like so:</p>\n<pre><code>std::vector<decltype(n_dim_vector_generator<dim - 1>(input, times))> output;\noutput.reserve(times);\nstd::fill_n(std::back_inserter(output), times, n_dim_vector_generator<dim - 1>(input, times));\nreturn output;\n</code></pre>\n<p>Although sadly there is no <code>std::back_emplacer()</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-22T16:15:31.530",
"Id": "252490",
"ParentId": "252488",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "252490",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-22T15:51:05.423",
"Id": "252488",
"Score": "3",
"Tags": [
"c++",
"recursion",
"c++20"
],
"Title": "std::array and std::vector Type Arbitrary Nested Iterable Generator Functions Implementation in C++"
}
|
252488
|
<p>I solved the following question</p>
<blockquote>
<p>You are asked to ensure that the first and last names of people begin
with a capital letter in their passports. For example, alison heck
should be capitalised correctly as Alison Heck.</p>
<p>Given a full name, your task is to capitalize the name appropriately.</p>
<p>Input Format</p>
<p>A single line of input containing the full name, S.</p>
<p>Constraints</p>
<ul>
<li>0 < len(S) < 1000</li>
<li>The string consists of alphanumeric characters and spaces.</li>
</ul>
<p>Note: in a word only the first character is capitalized.</p>
<p>Example 12abc when capitalized remains 12abc.</p>
<p>Output Format:</p>
<p>Print the capitalized string, S.</p>
</blockquote>
<p>Here's my code:</p>
<pre><code>#!/bin/python
import math
import os
import random
import re
import sys
# Complete the solve function below.
def solve(s):
ls = s.split(" ")
new_word = ""
new_name = ""
for word in ls:
if len(word) > 1:
new_word = new_word + word[0].title() + word[1:] + " "
else:
new_word = new_word + word.title() + " "
new_name = new_name.join(new_word)
return new_name
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = raw_input()
result = solve(s)
fptr.write(result + '\n')
fptr.close()
</code></pre>
<p>I think I used a very long approach and would appreciate more efficient techniques to do the same.</p>
<p>The primary problem which I faced is handling arbitrary spaces and hence I went with this approach but the code smells bad. One things I can think of is reducing variables but that wouldn't be very helpful and make it less readable I think</p>
<p>EDIT : The question is this <a href="https://www.hackerrank.com/challenges/capitalize/problem" rel="noreferrer">question</a> from HackerRank however the solution to this problem on the website does not include test cases where capitalize() and title() fail. The failing of these and more methods have also been discussed <a href="https://stackoverflow.com/questions/1549641/how-can-i-capitalize-the-first-letter-of-each-word-in-a-string">here</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-22T18:28:25.617",
"Id": "497536",
"Score": "0",
"body": "provide links to original problems for such challenges"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-22T18:45:38.917",
"Id": "497540",
"Score": "0",
"body": "okk will do @hjpotter92"
}
] |
[
{
"body": "<ul>\n<li>remove the unused <code>import</code>s</li>\n</ul>\n<p>Your code logic is OK but the execution is not good. Try not to overcomplicate it. Take a piece of paper and write the procedure of how a human like YOU would do it, just with a pencil and paper.</p>\n<pre><code>read the names individually... make first character capital if it isn't a digit \n</code></pre>\n<p>Now that you have basic design, become more specific, or in Python terms</p>\n<ul>\n<li><em>read the names individually</em> <code>for word in string.split()</code></li>\n<li><em>make the first character capital</em>: <code>string.title()</code></li>\n<li><em>if it isn't a digit</em> : <code>if not string[0].isdigit()</code></li>\n</ul>\n<blockquote>\n<p>The primary problem which I faced is handling arbitrary spaces<br></p>\n</blockquote>\n<p><code>string.split()</code> will return the same thing, let it be 1 space or 1000 spaces. It does not matter</p>\n<p>Now you have exactly what you need, it is just a matter of putting it together.</p>\n<pre class=\"lang-py prettyprint-override\"><code>for every word in words, capitalize if the first character isn't a digit else do nothing\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code> return " ".join(word.title() if not word[0].isdigit() else word for word in words.split())\n</code></pre>\n<p>Furthermore, using <code>capitalize()</code> will avoid the extra check</p>\n<pre class=\"lang-py prettyprint-override\"><code> return " ".join(word.capitalize() for word in words.split(' '))\n</code></pre>\n<p>EDIT:</p>\n<p>You have to use <code>.split(' ')</code> and NOT <code>.split()</code> since <code>.split()</code> removes <strong>all</strong> the whitespaces.</p>\n<hr />\n<p>As you mentioned, <code>title()</code> and <code>capitalize()</code> fail for scenarios where you pass something like</p>\n<pre><code>ALLISON heck\n</code></pre>\n<p>Output</p>\n<pre><code>Allison Heck\n</code></pre>\n<p>In that case, you need to have extra checks. The best thing to do here is to create another function that specifically capitalizes the first letter</p>\n<p>Here is what I thought of</p>\n<pre class=\"lang-py prettyprint-override\"><code>def cap_first(word):\n return word[:1].upper() + word[1:]\n</code></pre>\n<p>the <code>solve</code> function remains the same</p>\n<pre class=\"lang-py prettyprint-override\"><code>def solve(words):\n return ' '.join(cap_first(word) for word in words.split(' ')\n</code></pre>\n<h2>Benchmarks</h2>\n<p>the latter code is surely more readable and compact, but what is its performance compared to the previous solution?</p>\n<p>I will measure the execution time in the following manner using the <code>time</code> module</p>\n<pre class=\"lang-py prettyprint-override\"><code>for iterations in (10 ** 5,11 ** 5, 10 ** 6, 11 ** 6):\n print(f"\\n{iterations} iteartions\\n")\n\n\n start = time.time()\n for _ in range(iterations): solvenew(names)\n print(f"Time taken for new function: {time.time() - start:.3f} s")\n\n start = time.time()\n for _ in range(iterations): solveoriginal(names)\n print(f"Time taken for original function: {time.time() - start:.3f} s")\n</code></pre>\n<p>Here are the results</p>\n<pre class=\"lang-py prettyprint-override\"><code># Time taken \n#\n# iterations | original | new \n# --------------------------------------\n# 10 ** 6 | 2.553 s | 2.106 s\n# --------------------------------------\n# 11 ** 6 | 6.203 s | 5.542 s\n# --------------------------------------\n# 10 ** 7 | 32.412 s | 24.774 s\n</code></pre>\n<p><a href=\"https://pastebin.com/KU5RA6mZ\" rel=\"noreferrer\">Feel free to try it yourself</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-22T18:53:35.890",
"Id": "497541",
"Score": "0",
"body": "Hey, thanks for the answer I've used s.split(\" \") instead of s.split() which would give different results like take the string 'hey ooo hehehe jeje' the first one gives the result as ['hey', 'ooo', 'hehehe', '', '', '', 'jeje'] while the second gives the result as ['hey', 'ooo', 'hehehe', 'jeje']. I did this so that when I use join the spaces are taken care of else they vanish however I can't understand why use used split()? btw the import files were imported by the website itself I just wrote the function"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-22T18:57:23.980",
"Id": "497544",
"Score": "0",
"body": "okk I also just checked I had made a mistake the code works fine"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-22T18:59:08.053",
"Id": "497545",
"Score": "0",
"body": "I noticed another error with capitalize which I had read about earlier on stackoverflow as well when you use capitalize and say the word is UK it changes it to Uk which is not what we want same with title it also does not handle ' well"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-22T19:00:39.047",
"Id": "497547",
"Score": "0",
"body": "yes it did but it's because they didn't consider those cases I read about it here https://stackoverflow.com/questions/1549641/how-can-i-capitalize-the-first-letter-of-each-word-in-a-string"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-22T19:02:49.660",
"Id": "497549",
"Score": "0",
"body": "Yeah i guess but I'm more concerned about finding the best way to avoid any errors in any sore of case. Should I just remove the hackerrank portion and add that as a footnote instead of the main premise then?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-22T19:06:18.563",
"Id": "497550",
"Score": "0",
"body": "I've updated the question now thanks for the answer though :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-22T19:09:48.247",
"Id": "497552",
"Score": "0",
"body": "yeah i made a mistake sorry man I was focused on a solution which includes those cases I should've mentioned that before i thought about re asking but that would make them too similar"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-22T19:39:23.700",
"Id": "497555",
"Score": "0",
"body": "Thanks for adding this part :)"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-22T18:46:02.997",
"Id": "252495",
"ParentId": "252493",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "252495",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-22T18:08:54.920",
"Id": "252493",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"strings"
],
"Title": "Capitalizing the first letter of every word in a string (with arbitrary spacing)"
}
|
252493
|
<p>I want to create a struct-of-arrays (SOA) database for better cache use but also have a separate interface that gives encapsulation. I am close to the design I think but would like more experienced coding eyes to have a look to critique my design. Here is what I have so far:</p>
<pre class="lang-cpp prettyprint-override"><code>struct OrbitalDataBase {
OrbitalDataBase(std::shared_ptr<FEMDVR> a_radial_grid, std::shared_ptr<AngularGrid> a_angular_grid)
: nbas(a_radial_grid->getNbas()), number_of_lm_pairs_per_orbital(), m_orbital_coefs() {
m_orbitals_coefs.reserve(a_radial_grid->getNbas() * a_angular_grid->getNumChannels());
}
inline void StoreData(const uint32_t &a_ith_orbital,
std::shared_ptr<MOPartialWaveRepresentation> a_MO) {
this->number_of_lm_pairs_per_orbital.push_back(a_MO->getNumChannels());
this->m_orbital_coefs.reserve(a_ith_orbital * nbas *
a_MO->getNumChannels());
for (uint32_t i = 0; i < nbas * a_MO->getNumChannels();
++i) {
this->m_orbital_coefs.push_back(a_MO->getPartialWaveRep(i));
}
}
/* private: */
uint32_t nbas;
std::vector<uint32_t> number_of_lm_pairs_per_orbital;
std::vector<std::complex<double>> m_orbital_coefs;
};
struct OrbitalAccessor {
OrbitalAccessor(const OrbitalDataBase &a_orbital_data)
: orbital_data(a_orbital_data){};
inline std::complex<double> coef(uint32_t ith_orbital, uint32_t i) const {
return this->orbital_data.m_orbital_coefs
[ith_orbital * this->orbital_data.nbas *
this->orbital_data.number_of_lm_pairs_per_orbital[ith_orbital] +
i];
}
private:
const OrbitalDataBase orbital_data;
};
</code></pre>
<p>How this would work is construct the database with the number of orbitals and then in a for-loop, save all the ith_orbital's coefficients in one large array. Something like this</p>
<pre class="lang-cpp prettyprint-override"><code>uint32_t number_of_orbitals = 5;
OrbitalDataBase orb_data_base(number_of_orbitals);
for (uint32_t ith_orbital = 0; ith_orbital < number_of_orbitals < ++ith_orbital)
{
Orbital();
orb_data_base.StoreData(ith_orbital, femdvr_grid, orbital);
}
</code></pre>
<p>The <code>Orbital()</code> function just creates the orbital I want to store. Then the <code>OrbitalAccessor</code> should be able to access these large arrays index with stride <code>ith_orbital</code>. I think I should pass the accessor the created database I want to access in a constructor like</p>
<pre class="lang-cpp prettyprint-override"><code> int which_orbital = 1, int index 4; // example looks at 2nd orbital's 5th coefficient
OrbitalAccessor orb_accessor(orb_data_base);
orb_accessor.coef(which_orbital, index);
</code></pre>
<p>I tried to have the ObitalDataBase member data <code>private</code> but I get</p>
<blockquote>
<p>'m_orbitals_coefs' is a private member of 'OrbitalDataBase'</p>
</blockquote>
<p>so I commented the <code>private:</code> keyword so it will compile. I think they should be private for encapsulation so I'd prefer that if I am correct.</p>
<p>I think a better way would be to have <code>OrbitalAccessor</code> derive the <code>OrbitalDataBase</code> rather than pass it in to a constructor.</p>
<p>UPDATE: I changed the code a little so now the <code>m_orbital_coef</code> has a base vector capacity and resizes if it becomes larger because <code>a_MO->getNumChannels()</code> can be larger than <code>a_angular_grid->getNumChannels()</code>.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-22T20:36:51.517",
"Id": "497559",
"Score": "1",
"body": "if it doesn't compile you have to fix it prior to posting here"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-22T23:37:35.443",
"Id": "497572",
"Score": "0",
"body": "With SOA, do you mean \"Service-oriented architecture\"? Please expand acronyms you use at least once so people know what exactly you are talking about."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T19:56:19.607",
"Id": "497661",
"Score": "1",
"body": "Please do not update the code in your question after receiving answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T20:08:24.657",
"Id": "497662",
"Score": "0",
"body": "@Mast Ah shoot sorry, thank you for the guidance!"
}
] |
[
{
"body": "<p>There is a lot missing from this question, but there is enough code to be able to tell that a lot that could be improved. Here are some ideas for improving your code.</p>\n<h2>Use all of the required <code>#include</code>s</h2>\n<p>All of the <code>#includes</code> for this code are missing in the description. I believe the required list is this:</p>\n<pre><code>#include <complex>\n#include <cstdint>\n#include <memory>\n#include <vector>\n</code></pre>\n<h2>Provide complete code to reviewers</h2>\n<p>This is not so much a change to the code as a change in how you present it to other people. Without the full context of the code and an example of how to use it, it takes more effort for other people to understand your code. This affects not only code reviews, but also maintenance of the code in the future, by you or by others. One good way to address that is by the use of comments. Another good technique is to include test code showing how your code is intended to be used. There is a bit of that in your question, so we'll start from there.</p>\n<h2>Start with the desired interface</h2>\n<p>It's usually very useful to start by imagining how we'd like to use the code before implementing the interface. It appears that there exists some external source of orbital data (I'm guessing <a href=\"https://en.wikipedia.org/wiki/Two-line_element_set\" rel=\"nofollow noreferrer\">TLE</a>) which this code is supposed to read and parse (not shown) and then provide storage and access methods. First, rather than two separate classes, <code>OrbitalDataBase</code> and <code>OrbitalAccessor</code>, it seems clear to me that there should rather be a single <code>OrbitalDataBase</code> and that the accessor should be a member function. That leads to the first simplification:</p>\n<pre><code>std::complex<double> coef(uint32_t ith_orbital, uint32_t i) const {\n return m_orbital_coefs[ith_orbital * nbas * number_of_lm_pairs_per_orbital[ith_orbital] + i];\n}\n</code></pre>\n<h2>Don't write this-></h2>\n<p>Within member functions <code>this-></code> is redundant. It adds visual clutter and does not usually aid in understanding.</p>\n<h2>Use more whitespace for clarity</h2>\n<p>It's very difficult to parse the <code>OrbitalDataBase</code> constructor because it's all run together with very little whitespace. I'd modify it to look more like this:</p>\n<pre><code>struct OrbitalDataBase {\n OrbitalDataBase(std::shared_ptr<FEMDVR> a_radial_grid, std::shared_ptr<AngularGrid> a_angular_grid)\n : nbas(a_radial_grid->getNbas())\n , number_of_lm_pairs_per_orbital()\n , m_orbital_coefs() \n{\n m_orbital_coefs.reserve(a_radial_grid->getNbas() * a_angular_grid->getNumChannels());\n}\n</code></pre>\n<h2>Don't explicitly invoke implied constructors</h2>\n<p>The constructor, reformatted as above, reveals that the default and implied constructors for <code>number_of_lm_pairs_per_orbital</code> and <code>m_orbital_coefs</code> are explicitly called. This is both unnecessary and unhelpful. Simply omit those two lines.</p>\n<h2>Prefer <code>const</code> references to smart pointers</h2>\n<p>If you are passing in data, such as the <code>FEMDVR</code> and <code>AngularGrid</code> in this code, that are used but not altered, this implies <code>const</code>. Further, if we are not sharing ownership, which appears to be the case here, these should be references rather than <code>std::shared_ptr</code>.</p>\n<pre><code>OrbitalDataBase(const FEMDVR& a_radial_grid, const AngularGrid& a_angular_grid)\n : nbas(a_radial_grid.getNbas())\n{\n m_orbital_coefs.reserve(nbas * a_angular_grid.getNumChannels());\n}\n</code></pre>\n<h2>Understand modern use of <code>inline</code></h2>\n<p>Based on how you're using it, it appears that you are abusing the <code>inline</code> keyword to get an effect that the compiler is already going to provide without it. That is the <a href=\"https://en.cppreference.com/w/cpp/language/inline\" rel=\"nofollow noreferrer\"><code>inline</code></a> specifier for functions used to be a request to the compiler to optimize by putting the code inline rather than creating an explicit function call. However, this was only ever a suggestion, and the changing semantics of <code>inline</code> for C++17 and beyond are likely to lead to trouble unless very carefully used. The reason is that, starting with C++17, it tells the compiler that multiple defifinitions are allowed, but if they differ in any way, invoking the function is undefined behavior. For these reasons, you're better off omitting <code>inline</code> in most cases.</p>\n<h2>Rethink your data structures</h2>\n<p>Right now getting a value back uses this rather complex form:</p>\n<pre><code>std::complex<double> coef(uint32_t ith_orbital, uint32_t i) const {\n return m_orbital_coefs[ith_orbital * nbas * number_of_lm_pairs_per_orbital[ith_orbital] + i];\n}\n</code></pre>\n<p>This is very cache unfriendly because it has to look up one value from <code>number_of_lm_pairs_per_orbital</code> and then use that to index into another vector. It may make things more clear and give better performance if instead you defined a <code>struct</code> or <code>class</code> that encapsulated both. The obvious would be this:</p>\n<pre><code>struct Orbital {\n std::vector<std::complex<double>> m_orbital_coefs;\n};\n</code></pre>\n<p>Then <code>OrbitalDataBase</code> could use <code>std::vector<Orbital></code> as its only data member, since the number of coefficients is <code>m_orbital_coefs.size()</code> and <code>nbas</code> is now <code>m_orbital_coefs.size()</code>.</p>\n<p>Even simpler might be this:</p>\n<pre><code>using Orbital = std::vector<std::complex<double>>;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T17:11:18.553",
"Id": "497631",
"Score": "0",
"body": "I am confused with your suggestion for restructuring the data, could you explain a little more? The cache performance is from saving all the orbitals coefficients in one vector strided by nbas * number_of_lm_pairs_per_orbital[ith_orbital], so all of the elements for each orbital are contiguous in memory."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T14:18:04.817",
"Id": "252524",
"ParentId": "252497",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-22T19:42:01.787",
"Id": "252497",
"Score": "3",
"Tags": [
"c++",
"database"
],
"Title": "Creating a struct-of-arrays database with encapsulating interface c++"
}
|
252497
|
<p>I am trying to solve a problem, where we are given an app name, service name, and version number of an api. We need to print the name of app, which is using the latest version for most of the service.</p>
<pre><code>FOR EX -
Mail App, Authentication API, v6
Video Call App, Authentication API, v7
Mail App, Data Storage API, v10
Chat App, Data Storage API, v11
Mail App, Search API, v6
Chat App, Authentication API, v8
Chat App, Presence API, v2
Video Call App, Data Storage API, v11
Video Call App, Video Compression API, v3
</code></pre>
<blockquote>
<p><strong>Answer - Chat App</strong></p>
</blockquote>
<p>Here chat app is using the latest version for Data Storage API, Authentication API & Presence API [As Presence API is used in only one app so its version in itself is the latest]</p>
<p>I have pasted the code below that I have written to solve this problem. How can we solve it better?</p>
<pre><code>import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class Main {
static Map<String, Integer> map = new HashMap<String, Integer>();
static Map<String, List<VersionDetails>> versionDetails = new HashMap<String, List<VersionDetails>>();
static Map<String, Integer> rank = new HashMap<String, Integer>();
public static void main(String[] args) throws IOException {
String inputPath = "input.txt";
String outputPath = "output.txt";
readFile(inputPath);
String appName = sortVersionDetails();
BufferedWriter writer = new BufferedWriter(new FileWriter(outputPath, true));
writer.append(appName);
writer.close();
}
private static String sortVersionDetails() {
Integer max_rank = Integer.MIN_VALUE;
String answer = "";
for (Map.Entry<String, List<VersionDetails>> li : versionDetails.entrySet()) {
String appName = li.getKey();
for (VersionDetails vd : li.getValue()) {
if (vd.version < map.get(vd.apiName)) {
Integer value = rank.get(li.getKey()) - 1;
rank.put(appName, value);
}
}
if (max_rank < rank.get(appName)) {
answer = appName;
max_rank = rank.get(appName);
}
}
return answer;
}
private static void readFile(String path) throws IOException {
File file = new File(path);
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null) {
String arr[] = st.split(",");
String apiName = arr[1];
String applicationName = arr[0];
Integer version = Integer.valueOf((arr[2].trim()).substring(1));
if (!map.containsKey(apiName)) {
map.put(apiName, version);
rank.put(applicationName, 1);
} else {
Integer value = map.get(apiName) > version ? map.get(apiName) : Integer.valueOf(version);
map.put(apiName, value);
}
VersionDetails vd = new VersionDetails(apiName, version);
if (!versionDetails.containsKey(applicationName)) {
List<VersionDetails> li = new LinkedList<VersionDetails>();
li.add(vd);
versionDetails.put(applicationName, li);
} else {
versionDetails.get(applicationName).add(vd);
}
}
br.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
static class VersionDetails {
String apiName;
Integer version;
public VersionDetails(String apiName, Integer version) {
// TODO Auto-generated constructor stub
this.version = version;
this.apiName = apiName;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "[ apiName ] = " + apiName + " ; [ version ] = " + version;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>What you have there is essentially CSV data with three columns. If you added a third field for app name to <code>VersionDetails</code> you could wasily use a CSV reader to read the file and not bother yourself with the mundane task of reading files and parsing text into DAOs.</p>\n<p>There are two separate <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">responsibilities</a> in your code: reading the file and processing the entries. You should separate those into separate classes. Your file reader could provide a <code>Stream<VersionDetails></code> and your entry processor could be a <code>Consumer<VersionDetails></code> that is passed to <code>Stream.forEach(...)</code>.</p>\n<p>Regarding the algorithm, you don't give any reason why the complete result set should be stored in a <code>Map</code> between reading and processing. You might as well just look at the version number and only keep a reference to the <code>VersionDetails</code> with the greatest version number. If you separate the responsibilities like I suggest above, this improvement becomes quite natural.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T06:07:58.980",
"Id": "252504",
"ParentId": "252502",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T04:22:41.017",
"Id": "252502",
"Score": "2",
"Tags": [
"java",
"algorithm",
"collections",
"hash-map"
],
"Title": "Print the App Name Using Latest Version"
}
|
252502
|
<p><a href="https://leetcode.com/problems/group-anagrams/" rel="nofollow noreferrer">Link here</a></p>
<p>I'll include a solution in Python and C++ and you can review one. I'm mostly interested in reviewing the C++ code which is a thing I recently started learning; those who don't know C++ can review the Python code. Both solutions share similar logic, so the review will apply to any.</p>
<hr />
<h2>Problem statement</h2>
<blockquote>
<p>Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.</p>
</blockquote>
<p><strong>Example:</strong></p>
<pre><code>Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
</code></pre>
<p>Both solutions involve creating a mapping from word characters ordered alphabetically to corresponding word and each word encountered that is a match, is added to the corresponding group. And since it was suggested earlier in my previous posts not to rely on leetcode's stats because they are inaccurate, I timed both c++ and python solutions for 1,000,000 runs on the same set of words to see what comes up. Surprisingly, python solution outperforms the c++ solution almost by 2x. The resulting times ~= 10, 20 seconds for python and c++ respectively when run on my i5 2.7 GHZ mbp. Given that both implementations are almost similar, shouldn't c++ be 10x times faster than python?</p>
<p><code>group_anagrams.py</code></p>
<pre><code>from collections import defaultdict
from time import perf_counter
def group(words):
groups = defaultdict(lambda: [])
for word in words:
groups[tuple(sorted(word))].append(word)
return groups.values()
def time_grouping(n, words):
print(f'Calculating time for {n} runs ...')
t1 = perf_counter()
for _ in range(n):
group(words)
print(f'Time: {perf_counter() - t1} seconds')
if __name__ == '__main__':
w = [
'abets',
'baste',
'beats',
'tabu',
'actress',
'casters',
'allergy',
'gallery',
'largely',
]
print(list(group(w)))
time_grouping(1000000, w)
</code></pre>
<p><strong>Results:</strong></p>
<pre><code>[['abets', 'baste', 'beats'], ['tabu'], ['actress', 'casters'], ['allergy', 'gallery', 'largely']]
Calculating time for 1000000 runs ...
Time: 8.801584898000002 seconds
</code></pre>
<p><code>group_anagrams.h</code></p>
<pre><code>#ifndef LEETCODE_GROUP_ANAGRAMS_H
#define LEETCODE_GROUP_ANAGRAMS_H
#include <vector>
#include <string>
std::vector<std::vector<std::string>> get_groups(const std::vector<std::string> &words);
#endif //LEETCODE_GROUP_ANAGRAMS_H
</code></pre>
<p><code>group_anagrams.cpp</code></p>
<pre><code>#include "group_anagrams.h"
#include <algorithm>
#include <chrono>
#include <iostream>
#include <map>
std::vector<std::vector<std::string>>
get_groups(const std::vector<std::string> &words) {
std::map<std::string, std::vector<std::string>> word_groups;
std::vector<std::vector<std::string>> groups;
for (const auto &word: words) {
auto sorted_word = word;
std::sort(sorted_word.begin(), sorted_word.end());
if (word_groups.contains(sorted_word)) {
word_groups[sorted_word].push_back(word);
} else {
word_groups[sorted_word] = {word};
}
}
groups.reserve(word_groups.size());
for (auto const &imap: word_groups)
groups.push_back(imap.second);
return groups;
}
int main() {
std::vector<std::string> words{
"abets", "baste", "beats", "tabu", "actress", "casters", "allergy",
"gallery", "largely"
};
auto groups = get_groups(words);
for (const auto &group: groups) {
for (const auto &word: group)
std::cout << word << ' ';
std::cout << '\n';
}
size_t n_times{1000000};
std::cout << "\nCalculating time for " << n_times << " runs ..." << '\n';
auto t1 = std::chrono::high_resolution_clock::now();
while (n_times > 0) {
get_groups(words);
n_times--;
}
auto t2 = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::seconds>(
t2 - t1).count();
std::cout << duration << " seconds";
}
</code></pre>
<p><strong>Results:</strong></p>
<pre><code>abets baste beats
tabu
actress casters
allergy gallery largely
Calculating time for 1000000 runs ...
22 seconds
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T08:32:39.433",
"Id": "497588",
"Score": "1",
"body": "I think its better to split as 2 quivalent questions, each for specific language."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T08:36:19.903",
"Id": "497589",
"Score": "1",
"body": "About Python's solution, `defaultdict(lambda: [])` can be shorten to `defaultdict(list)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T08:37:19.183",
"Id": "497590",
"Score": "0",
"body": "@hjpotter92 I don't think that is necessary unless there are significant differences between both versions. I've been notified previously by other members of the community and I indicated the same."
}
] |
[
{
"body": "<h2>C++</h2>\n<pre><code> if (word_groups.contains(sorted_word)) {\n word_groups[sorted_word].push_back(word);\n } else {\n word_groups[sorted_word] = {word};\n }\n</code></pre>\n<p><code>contains</code> does a search for the word in <code>word_groups</code>. Then <code>operator[]</code> does that same search a second time.</p>\n<p>We can replace the above with just:</p>\n<pre><code> word_groups[sorted_word].push_back(word);\n</code></pre>\n<p>(<code>operator[]</code> inserts a default-constructed value (i.e. an empty <code>vector<std::string></code>) if it isn't present in the map).</p>\n<hr />\n<p>We don't need to copy the <code>word_groups</code> map into a vector to return it from <code>get_groups()</code>. We can just return the map itself.</p>\n<p>Then in the main function we'd iterate it with:</p>\n<pre><code>for (const auto &group: groups) { // group is a pair (.first is the key, .second is the values)\n for (const auto &word: group.second)\n ...\n</code></pre>\n<hr />\n<p>We don't need to store the string itself in the map, we can store the index of the string in the input vector. (i.e. <code>map<string, vector<std::size_t>></code>).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T09:20:29.230",
"Id": "252511",
"ParentId": "252507",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "252511",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T07:17:30.153",
"Id": "252507",
"Score": "1",
"Tags": [
"python",
"c++",
"programming-challenge"
],
"Title": "Leetcode group anagrams"
}
|
252507
|
<p>Question:
Implement an autocomplete system. That is, given a query string s and a set of all possible query strings, return all strings in the set that have s as a prefix.
For example, given the query string de and the set of strings [dog, deer, deal], return [deer, deal].
Hint: Try preprocessing the dictionary into a more efficient data structure to speed up queries.</p>
<p>What I tried to do:
Implement prefix tree is way to go as researched from internet. So without looking at actual implementation code, I just grabbed the idea and wrote down the code to challenge myself. Of course code is a messy, but will be really appreciated if someone could advice on how it can be improved in terms of efficiency and simplicity.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define ALP_PREFIX 97 //for numeric value of alphabets
typedef struct stTree
{
struct stTree *nLetter[26];
bool isLastChar;
char value;
} stTree;
stTree* createNode(void)
{
stTree *node = malloc(sizeof *node);
node->value = '\0';
node->isLastChar = false;
return node;
}
stTree* insertNode(stTree *currNode, char value, bool isLastChar)
{
if (!currNode->nLetter[value - ALP_PREFIX])
{
stTree *node = malloc(sizeof *node);
node->value = value;
currNode->nLetter[value - ALP_PREFIX] = node;
}
currNode->nLetter[value - ALP_PREFIX]->isLastChar = isLastChar;
return currNode->nLetter[value - ALP_PREFIX];
}
stTree* treeTraverse(char *chars, stTree *Node)
{
stTree *nextNode = Node->nLetter[chars[0] - ALP_PREFIX];
if (nextNode && chars[0] != '\0')
{
return treeTraverse(chars + 1, nextNode);
}
else
return Node;
}
void autoComplete(stTree *Node)
{
for (int i = 0; i < 26; i++)
{
if (Node->nLetter[i])
{
printf("%c", Node->nLetter[i]->value);
if (Node->nLetter[i]->isLastChar)
printf("]");
autoComplete(Node->nLetter[i]);
}
}
printf("\n");
}
int main(void)
{
stTree *rootNode = createNode();
insertNode(insertNode(insertNode(insertNode(rootNode, 'c', false), 'a', false), 'r', false), 't', true);
insertNode(insertNode(insertNode(rootNode, 'c', false), 'a', false), 'r', true);
insertNode(insertNode(insertNode(rootNode, 'c', false), 'a', false), 't', true);
char a[] = "ca";
printf("%c%c->\n", a[0], a[1]);
stTree *lastNode = treeTraverse(a, rootNode);
autoComplete(lastNode);
}
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>ca->
r]t]
t]
</code></pre>
<p>It means, autocompleted words are: car, cart, cat</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T00:08:10.487",
"Id": "497683",
"Score": "0",
"body": "From the wording you've presented, this sounds like either homework or a programming challenge. Please tag it one way or the other, and if it's a challenge, include a link to the original question if possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T06:44:51.687",
"Id": "497702",
"Score": "0",
"body": "@Reinderien it was random challenge I found from internet and I have been implementing those to improve myself on DS and algorithms."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T06:54:09.413",
"Id": "497703",
"Score": "2",
"body": "@Reinderien the question was generated by dailycodingproblem.com"
}
] |
[
{
"body": "<p>I'll only look at the memory vs. speed trade-off.</p>\n<p>Suppose that M is the key size we want to look up, and N is the number of words in the dictionary. If we start with a sorted dictionary, then the prefix can be found with binary search, so that is <code>O(M * log N)</code> lookup cost in terms of the dictionary size. A prefix tree has a lookup cost of <code>O(M)</code>. But the "work" done to actually look things up is trivial, i.e. on modern CPUs there's no cost to doing the character comparisons and such, especially that you could use SIMD intrinsics to speed that up by a lot. The entire cost is in cacheline accesses.</p>\n<p>To speak in concrete terms, let's use the alphanumeric word dictionary from <a href=\"https://github.com/dwyl/english-words\" rel=\"nofollow noreferrer\">https://github.com/dwyl/english-words</a>, on x86-64 (i.e. 8-byte pointer size). Let's also assume that we're wishing to optimize for lookup efficiency (broadly defined).</p>\n<p>First, some general statistics of this dictionary:</p>\n<ul>\n<li>3,494,697 letters</li>\n<li>370,103 words</li>\n<li>1,027,815 nodes in a prefix tree</li>\n<li>3 child nodes average branching factor.</li>\n<li>9 letters median word length (also the average), 31 letters maximum word length</li>\n<li>branching factors (for successive letters looked up):\n1-26, 2-22, 3-8.6, 4-5.1, 5-2.7, 6-1.7, 7-1.1, 8-0.9, 9-0.8</li>\n</ul>\n<p>So, if we stored the dictionary as a simple concatenation of null-terminated C strings, with no other optimizations, it'd take around 4MB of memory. This fits comfortably in the 6MB L3 cache of the CPU I'm trying this on (that cache can hold ~100k cachelines of 64 bytes each, in best case).</p>\n<p>On the other hand, the question's implementation of the prefix tree takes ~220MB of RAM because the nodes are huge: 216 bytes. We'd have hoped that the prefix tree would have "compressed" our data, but instead it expands it by a factor of 55x. Each node fits in 4 cache lines (3.3 really).</p>\n<p>Tree traversal using <code>Node</code> needs to pull up to two cachelines per Node (maybe 1.5 on average): one for the child node pointer, another for the <code>value</code> and the child pointer. Some of those cachelines will have to be misses, since the tree doesn't fit in the cache.</p>\n<p>The L3 cache can fit around 30k nodes. Let's somewhat arbitrarily assume that about 10k of them will be "long lived hot nodes". The product of the first 5 branching factors is ~25k, so we can estimate that about 4 first characters of each word will be nodes that fit in L3. With average word being 9 letters long, we will miss 4-5 additional nodes, or 8-10 additional cachelines. That'd be the real cost of this implementation on this particular data set.</p>\n<p>Now let's say our benchmark will be as follows: take a "lookup string" of all words in random order, concatenated into a long string of zero-terminated words. Iterating such a string is very fast, since the CPU will prefetch everything, so other than some cache pressure, the overhead of using such permuted word stream is very low. We use words from that string as lookup keys, and copy them to an output string as we perform each lookup. An exemplary benchmark takes about 120ms to look up all the 370k words in random order from the prefix tree, constructing the "output string". The function being timed is below, the assert is a no-op in release mode, and the nodes were all allocated from a contiguous memory block.</p>\n<p>I wrote the examples below in C++, to make life a bit easier, but they could all be written in C without any loss of performance.</p>\n<pre><code>auto doLookup(Node *root, const std::string &lookupStream)\n{\n std::string result, word;\n Node *node = root;\n result.clear();\n result.reserve(lookupStream.size());\n for (char ch : lookupStream) {\n if (ch) {\n node = node->children[ch - 'a'];\n word.push_back(ch);\n } else {\n node = root;\n result.append(word);\n result.push_back('\\0');\n word.clear();\n }\n }\n assert(result == lookupStream);\n return std::make_pair(std::move(result), node);\n}\n</code></pre>\n<p>Given this "standard" to compare with, let's do the "next most stupid thing": an equivalent lookup using just the dictionary, with zero-delimited words in ascending order, using a binary search, where each time we "throw a dart" in the dictionary, we have to scan back to find the beginning of the word.</p>\n<p>The function being timed is below. It isn't particularly pretty but it does the job.</p>\n<pre><code>auto doLookup2(const std::string &dictionary, const std::string &lookupStream)\n{\n assert(dictionary.front() == '\\0');\n assert(dictionary.back() == '\\0');\n assert(lookupStream.back() == '\\0');\n std::string result, word;\n result.reserve(lookupStream.size());\n for (char ch : lookupStream) {\n if (ch)\n word.push_back(ch);\n else {\n const char *begin = &dictionary.front(), *end = &dictionary.back();\n const char *prevP = nullptr;\n for (;;) { // binary search\n const char *p = begin + (end - begin) / 2;\n const char *const p0 = p;\n assert(p0 != prevP); // otherwise we didn't find the word\n while (*p)\n --p; // find start of the word\n p ++;\n int const cmp = strcmp(word.data(), p);\n if (cmp == 0) {\n assert(word == p);\n result.append(word);\n result.push_back('\\0');\n word.clear();\n break;\n }\n if (cmp < 0 /* word < p */) {\n end = p0;\n } else { /* word > p */\n begin = p0;\n }\n prevP = p0;\n }\n }\n }\n assert(result == lookupStream);\n return result;\n}\n</code></pre>\n<p>This function takes about 170ms (vs. the tree's 120ms), and trades off 50% longer execution for 55x smaller memory use, although it doesn't find the first word with a given prefix, just some word - then one has to iterate backward. Doing that in the most rudimentary way adds some 10ms to the runtime (I'm not showing it above).</p>\n<p>This trade-off may be acceptable as-is. But either approach could be micro-optimized. Cutting the tree size in half by replacing the node pointers with indices of nodes in the pool cuts about 10ms off the runtime - we don't expect a huge improvement, since the tree still doesn't fit in the cache.</p>\n<p>But the tree approach seems promising, so let's try to reduce memory consumption further. Instead of allocating 26 child node pointers in each node, let's allocate only one, and double the pointer array size whenever we run out of space. There isn't a direct index-to-pointer mapping for child pointers anymore, but instead we can store a bit flag for each character, indicating whether the pointer is present or absent in the array. Furthermore, the leaf nodes can all be stored as stock nodes, since they are identical. The node looks as follows:</p>\n<pre><code>struct TreeNode\n{\n uint32_t activeChildren;\n struct TreeNode *children[1]; // this is a dynamically sized array\n} typedef TreeNode;\n</code></pre>\n<p>The <code>activeChildren</code> member also stores the end-of-word flag - access is provided via accessors.</p>\n<p>This approach reduces the allocated memory size to 15MB, and the lookup benchmark takes about 140ms - only 20ms worse than the "reference" implementation. Only 750k nodes are individually allocated, the remaining 250k are all leaf nodes collected as the single <code>stockLeafNode</code>.</p>\n<p>Retrieval of a child node looks as follows:</p>\n<pre><code>TreeNode **getChildNode(TreeNode *node, char ch)\n{\n ch -= NODE_LOWEST_VALUE;\n uint32_t childrenBits = node->activeChildren;\n if (!bitIsSet(childrenBits, ch))\n return NULL;\n return node->children + numberOfSetBitsBelow(childrenBits, ch);\n}\n</code></pre>\n<p><code>numberOfSetBitsBelow(bits, bit)</code> returns the count of set bits ("1") in the <code>bits</code> paramer, but only the bits in positions lower than bit number <code>bit</code>. E.g. <code>numberOfSetBitsBelow(0xFE, 3) == 2</code>, because below bit 3 only bits 2 and 1 are set.</p>\n<p>Using <code>getChildNode</code>, we have the following prefix lookup:</p>\n<pre><code>TreeNode *findNode(TreeNode *node, const char *word)\n{\n for (char ch = *word++; ch; ch = *word++) {\n TreeNode *nextNode = *getChildNode(node, ch);\n if (!nextNode)\n break;\n node = nextNode;\n }\n return node;\n}\n</code></pre>\n<p>Complete project is at <a href=\"https://github.com/KubaO/stackoverflown/tree/master/questions/cr-prefix-tree-252512\" rel=\"nofollow noreferrer\">https://github.com/KubaO/stackoverflown/tree/master/questions/cr-prefix-tree-252512</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T09:48:13.270",
"Id": "252644",
"ParentId": "252512",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "252644",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T10:01:25.977",
"Id": "252512",
"Score": "4",
"Tags": [
"algorithm",
"c",
"programming-challenge",
"tree"
],
"Title": "Implementing an autocomplete system"
}
|
252512
|
<p>I'd be grateful if you could review my code. Please be as critical towards it as possible and yet indulgent when it comes to asking my first question here.</p>
<p>This is a simple snake game using pygame. I have issues when it comes to classes and not sure if I did it right by putting everything into 1 class and rest as functions. Unfortunately, the best way of learning for me is to use examples :/</p>
<p>Another thing is the snake movement field idea. I have made a tuple list with coordinates across all screen and due to the fact that not all screen is the playable field I have used x and y coordinates to check for example if the snake's head touches the border and should display the game-over message. Any different idea on how to approach it?</p>
<p>Thanks in advance :)</p>
<pre><code>import pygame
import sys
import random
class Game(object):
def __init__(self):
# Config
self.fps = 5
self.resolution = (700, 700)
self.matrix_table = []
for i in range(0, 1280, 20):
for j in range(0, 720, 20):
self.matrix_table.append((i, j))
self.snake_parts_position = [629]
self.snake_movement = 36
self.new_apple_index = random.randint(185, 1074)
while self.matrix_table[self.new_apple_index][0] < 100 or self.matrix_table[self.new_apple_index][1] < 100 or \
self.matrix_table[self.new_apple_index][0] > 580 or self.matrix_table[self.new_apple_index][1] > 580:
self.new_apple_index = random.randint(185, 1074)
self.a = self.matrix_table[self.new_apple_index][0]
self.b = self.matrix_table[self.new_apple_index][1]
self.font_name = pygame.font.match_font('arial')
# Init
pygame.init()
self.display = pygame.display.set_mode(self.resolution)
self.fps_clock = pygame.time.Clock()
self.fps_delta = 0.0
while True:
# handle events like player input
# self.events()
# ticking
self.fps_delta += self.fps_clock.tick() / 1000.0
while self.fps_delta > 1 / self.fps:
self.events()
self.movement()
self.game_over()
self.eating_apple()
self.fps_delta -= 1 / self.fps
# drawing
self.drawing_fill_flip()
def drawing_fill_flip(self):
self.display.fill((0, 0, 0))
self.draw()
pygame.display.flip()
def events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit(0)
elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
sys.exit(0)
elif event.type == pygame.KEYDOWN and event.key == pygame.K_KP_2:
if self.snake_movement == -1:
pass
else:
self.snake_movement = 1
elif event.type == pygame.KEYDOWN and event.key == pygame.K_KP_4:
if self.snake_movement == 36:
pass
else:
self.snake_movement = -36
elif event.type == pygame.KEYDOWN and event.key == pygame.K_KP_6:
if self.snake_movement == -36:
pass
else:
self.snake_movement = 36
elif event.type == pygame.KEYDOWN and event.key == pygame.K_KP_8:
if self.snake_movement == 1:
pass
else:
self.snake_movement = -1
def movement(self):
try:
if len(self.snake_parts_position) > 1:
for i in range(len(self.snake_parts_position) - 1, -1, -1):
if i > 0:
self.snake_parts_position[i] = self.snake_parts_position[i - 1]
elif i == 0:
self.snake_parts_position[0] += self.snake_movement
else:
self.snake_parts_position[0] += self.snake_movement
except:
pass
def draw(self):
try:
for i in self.snake_parts_position:
if i == self.snake_parts_position[0]:
pygame.draw.circle(self.display, (255, 255, 0),
(self.matrix_table[i][0] + 10, self.matrix_table[i][1] + 10), 10, 10)
else:
pygame.draw.circle(self.display, (0, 255, 0), (self.matrix_table[i][0] + 10, self.matrix_table[i][1] + 10), 10, 10)
pygame.draw.circle(self.display, (0, 0, 255), (self.a + 10, self.b + 10), 10, 10)
except:
pass
# dots and brackets
pygame.draw.rect(self.display, (255, 255, 255), pygame.Rect(110, 110, 1, 1))
pygame.draw.lines(self.display, (255, 255, 255), True, [(100, 100), (600, 100), (600, 600), (100, 600)])
for i in range(110, 600, 20):
for j in range(110, 600, 20):
pygame.draw.rect(self.display, (255, 255, 255), pygame.Rect(i, j, 1, 1))
def new_apple(self):
self.new_apple_index = random.randint(185, 1074)
while self.matrix_table[self.new_apple_index][0] < 100 or self.matrix_table[self.new_apple_index][1] < 100 or self.matrix_table[self.new_apple_index][0] > 580 or self.matrix_table[self.new_apple_index][1] > 580 or self.new_apple_index in self.snake_parts_position:
self.new_apple_index = random.randint(185, 1074)
self.a = self.matrix_table[self.new_apple_index][0]
self.b = self.matrix_table[self.new_apple_index][1]
def eating_apple(self):
if self.snake_parts_position[0] == self.new_apple_index:
self.snake_parts_position.append(self.snake_parts_position[-1])
self.new_apple()
# self.fps += 1
def game_over(self):
if self.matrix_table[self.snake_parts_position[0]][0] < 100 or self.matrix_table[self.snake_parts_position[0]][1] < 100 or self.matrix_table[self.snake_parts_position[0]][0] > 580 or self.matrix_table[self.snake_parts_position[0]][1] > 580 :
self.show_go_screen()
if len(self.snake_parts_position) != len(set(self.snake_parts_position)):
self.show_go_screen()
def draw_text(self, surf, text, size, x, y):
font = pygame.font.Font(self.font_name, size)
text_surface = font.render(text, True, (255, 255, 255))
text_rect = text_surface.get_rect()
text_rect.midtop = (x, y)
surf.blit(text_surface, text_rect)
def show_go_screen(self):
self.draw_text(self.display, "GAME OVER!", 64, 350, 300)
self.draw_text(self.display, "Press a key to Continue", 18, 350, 400)
pygame.display.flip()
waiting = True
while waiting:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYUP:
self.__init__()
waiting = False
if __name__ == "__main__":
Game()
</code></pre>
|
[] |
[
{
"body": "<p>Welcome to Code Review!</p>\n<h2>Class definition</h2>\n<p>One of the very first changes in python 3.x was that you no longer need to explicitly declare class as a subclass of <code>object</code>. This declaration is implicit.</p>\n<pre><code>class Game:\n</code></pre>\n<h2>Constants vs attributes</h2>\n<p>A lot of values in the constructor of your class can be extracted as constant parameters. This will also cover the following point about magic numbers.</p>\n<h2><a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">Magic numbers</a></h2>\n<p>There are several instances of magic numbers in your code. For eg.</p>\n<ul>\n<li><code>random.randint(185, 1074)</code></li>\n<li><code>self.new_apple_index][0] < 100</code></li>\n<li><code>self.new_apple_index][0] > 580</code></li>\n<li><code>self.snake_movement == 36</code></li>\n<li>and so on</li>\n</ul>\n<p>Replace those values (where do they even come from?) with consistently and properly named constants. This also applies to the colour tuples in your code.</p>\n<h2>Execution logic in constructor</h2>\n<p>As soon as your game class object gets initialised, the game launches and the class loses its purpose of having <strong>so many</strong> declared parameters. The whole thing could have been achieved as a single script.</p>\n<p>Having defined attributes inside class, and separating logic for your game, it seems more obvious to me that the game would be launched only when I do <code>.start()</code> or <code>.launch()</code> or <code>.run()</code> or equivalent.</p>\n<h2>Redundant conditions/code snippets</h2>\n<p>At several points in your code, you're doing:</p>\n<pre><code>event.type == pygame.KEYDOWN and event.key == <something>\n</code></pre>\n<p>If you're interested only in the <code>KEYDOWN</code> events, perhaps continue your event polling loop on any other event type, and proceed to compare only for the <code>event.key</code> values?</p>\n<p>A rewrite would look something like:</p>\n<pre><code>for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit(0)\n if event.type != pygame.KEYDOWN:\n continue\n if event.key == pygame.K_ESCAPE:\n sys.exit(0)\n elif event.key == pygame.K_KP_2:\n if self.snake_movement == -1:\n pass\n else:\n self.snake_movement = 1\n elif event.key == pygame.K_KP_4:\n if self.snake_movement == 36:\n pass\n else:\n self.snake_movement = -36\n.\n.\n</code></pre>\n<p>A similar is true for the new apple calculation. You have defined a separate function <code>new_apple</code>, yet everything inside is also being done in the constructor.</p>\n<h2>sys.exit vs pygame.quit</h2>\n<p><a href=\"https://www.pygame.org/docs/ref/pygame.html#pygame.quit\" rel=\"nofollow noreferrer\">pygame docs</a> suggest using pygame.quit to uninitialise all open pygame modules, and letting the python script exit naturally. You can also find few more discussions around the <a href=\"https://stackoverflow.com/q/11488122/1190388\">same on stack overflow</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T18:44:02.653",
"Id": "252549",
"ParentId": "252513",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T10:48:47.413",
"Id": "252513",
"Score": "3",
"Tags": [
"python-3.x",
"pygame",
"snake-game"
],
"Title": "Snake using Pygame"
}
|
252513
|
<p><a href="https://leetcode.com/problems/spiral-matrix/" rel="nofollow noreferrer">Link here</a></p>
<p>I'll include a solution in Python and C++ and you can review one. I'm mostly interested in reviewing the C++ code which is a thing I recently started learning; those who don't know C++ can review the Python code. Both solutions share similar logic, so the review will apply to any.</p>
<hr />
<h2>Problem statement</h2>
<blockquote>
<p>Given an m x n matrix, return all elements of the matrix in spiral order.</p>
</blockquote>
<p><strong>Example1:</strong></p>
<p><a href="https://i.stack.imgur.com/1DXGn.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1DXGn.jpg" alt="spiral1" /></a></p>
<pre><code>Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
</code></pre>
<p><strong>Example2:</strong></p>
<p><a href="https://i.stack.imgur.com/ufU7B.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ufU7B.jpg" alt="spiral2" /></a></p>
<pre><code>Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
</code></pre>
<p>For some reason c++ execution time is 3x python's time 10 seconds and 28 seconds for python and c++ respectively, same as my recent <a href="https://codereview.stackexchange.com/questions/252507/leetcode-group-anagrams">post</a> I'm expecting c++ code to be a lot faster, why is it taking so long with both implementations being almost similar as both use the same recursive algorithm.</p>
<p><code>spiral_matrix.py</code></p>
<pre><code>from time import perf_counter
def calculate(matrix):
numbers = []
if not matrix or not matrix[0]:
return numbers
elif isinstance(matrix[0], int):
return numbers + matrix
else:
if len(matrix) == 1:
return numbers + matrix[0]
if len(matrix[0]) == 1:
return numbers + [item.pop() for item in matrix]
numbers += matrix[0][:-1]
numbers += (cols := [*zip(*matrix)])[-1][:-1]
numbers += matrix[-1][::-1][:-1]
numbers += cols[0][::-1][:-1]
if rest := matrix[1:-1]:
return numbers + calculate([item[1:-1] for item in rest])
return numbers
def time_spiral(n, matrix):
print(f'Calculating time for {n} runs ...')
t1 = perf_counter()
for _ in range(n):
calculate(matrix)
print(f'Time: {perf_counter() - t1} seconds')
if __name__ == '__main__':
mtx = [
[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, 30],
[31, 32, 33, 34, 35, 36],
]
print(calculate(mtx))
time_spiral(1000000, mtx)
</code></pre>
<p><strong>Results:</strong></p>
<pre><code>[1, 2, 3, 4, 5, 6, 12, 18, 24, 30, 36, 35, 34, 33, 32, 31, 25, 19, 13, 7, 8, 9, 10, 11, 17, 23, 29, 28, 27, 26, 20, 14, 15, 16, 22, 21]
Calculating time for 1000000 runs ...
Time: 9.450265422000001 seconds
</code></pre>
<p><code>spiral_matrix.h</code></p>
<pre><code>#ifndef LEETCODE_SPIRAL_MATRIX_H
#define LEETCODE_SPIRAL_MATRIX_H
#include <vector>
std::vector<int> get_spiral(const std::vector<std::vector<int>> &matrix);
#endif //LEETCODE_SPIRAL_MATRIX_H
</code></pre>
<p><code>spiral_matrix.cpp</code></p>
<pre><code>#include "spiral_matrix.h"
#include <chrono>
#include <iostream>
static void
add_borders(size_t start_width, size_t start_height, std::vector<int> &numbers,
const std::vector<std::vector<int>> &matrix) {
for (size_t i{0}; i < start_width - 1; ++i) {
numbers.push_back(matrix[0][i]);
}
for (size_t i{0}; i < start_height - 1; ++i) {
numbers.push_back(matrix[i][start_width - 1]);
}
for (size_t i{start_width - 1}; i > 0; --i) {
numbers.push_back(matrix[start_height - 1][i]);
}
for (size_t i{start_height - 1}; i > 0; --i) {
numbers.push_back(matrix[i][0]);
}
}
static std::vector<std::vector<int>> get_rest(size_t start_width, size_t start_height,
const std::vector<std::vector<int>> &matrix) {
std::vector<std::vector<int>> rest;
for (size_t i{1}; i < start_height - 1; ++i) {
std::vector<int> row;
for (size_t j{1}; j < start_width - 1; ++j) {
row.push_back(matrix[i][j]);
}
rest.push_back(row);
}
return rest;
}
std::vector<int> get_spiral(const std::vector<std::vector<int>> &matrix) {
std::vector<int> numbers;
if (matrix.empty() || matrix[0].empty())
return numbers;
if (matrix.size() == 1)
return matrix[0];
if (matrix[0].size() == 1) {
for (auto i: matrix)
numbers.push_back(i[0]);
return numbers;
}
auto start_width = matrix[0].size();
auto start_height = matrix.size();
add_borders(start_width, start_height, numbers, matrix);
auto rest = get_rest(start_width, start_height, matrix);
auto next_result = get_spiral(rest);
numbers.insert(numbers.end(), next_result.begin(), next_result.end());
return numbers;
}
int main() {
std::vector<std::vector<int>> matrix{{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, 30},
{31, 32, 33, 34, 35, 36}};
auto result = get_spiral(matrix);
for (int num: result)
std::cout << num << ' ';
size_t n_times{1000000};
std::cout << "\nCalculating time for " << n_times << " runs ..." << '\n';
auto t1 = std::chrono::high_resolution_clock::now();
while (n_times > 0) {
get_spiral(matrix);
n_times--;
}
auto t2 = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::seconds>(
t2 - t1).count();
std::cout << duration << " seconds";
}
</code></pre>
<p><strong>Results:</strong></p>
<pre><code>1 2 3 4 5 6 12 18 24 30 36 35 34 33 32 31 25 19 13 7 8 9 10 11 17 23 29 28 27 26 20 14 15 16 22 21
Calculating time for 1000000 runs ...
28 seconds
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T17:36:03.750",
"Id": "497637",
"Score": "0",
"body": "Which options are you using for compilation ? With -O3 and -ffast-math, I get the result in 839 ms ! I paid attention to use the intermediate output of the function, to be sure that the optimiser was not cancelling everything"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T17:41:14.370",
"Id": "497639",
"Score": "0",
"body": "@Damien I'm not sure of that because I run the code in the editor (clion) I also tried from the command line: `g++ spiral_matrix.cpp --std c++2a -o spiral_matrix` I then run the executable file and get the same results. How can I check what you're asking for?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T17:43:21.483",
"Id": "497640",
"Score": "0",
"body": "Just use `g++ -O3 -ffast-math spiral_matrix.cpp --std c++2a -o spiral_matrix` for compiling"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T17:55:05.260",
"Id": "497641",
"Score": "0",
"body": "@Damien It's down from 24 seconds to 5 seconds, isn't this still slow? I'm running this on my i5 mbp. What are these flags? and how can I adjust editor settings accordingly? is there some kind of documentation to these things?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T18:00:12.420",
"Id": "497642",
"Score": "0",
"body": "I have a i7. You can get details about these options at official gcc documention, for example, [here](https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html). For compilation, I always use a command line, or a makefile (linux)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T18:09:40.933",
"Id": "497646",
"Score": "0",
"body": "@Damien Here's the current [makefile](https://drive.google.com/file/d/1uztupo4wJ_G8Z9iglCk3H0wtMA7ekPTU/view?usp=sharing) which is auto-generated by clion if you want to check. And I'll check the docs, thanks but still I'm not sure what should / shouldn't be modified as I'm still new to these things."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T18:15:24.017",
"Id": "497647",
"Score": "0",
"body": "I am only using home-made makefile. I don't know clion. I guess the compilation options must be modified by a menu, cannot help on it, sorry."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T18:16:42.223",
"Id": "497648",
"Score": "0",
"body": "np, thanks anyway"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T00:55:29.783",
"Id": "497684",
"Score": "0",
"body": "@Damien First of all, it is not floating point code, so --fast-math makes no difference. Secondly, never use -O3 by default. It does not guarantee faster code than -O2 optimized (I've seen several counterexamples) , and there is higher chance to hit a bug in the compiler."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T02:35:54.887",
"Id": "497692",
"Score": "0",
"body": "@llkhd so what do you suggest to improve performance?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T05:35:47.650",
"Id": "497698",
"Score": "0",
"body": "@Ilkhd My makefile use these options by default. I have worked on time critical simulation chains for decades (telecommunications) and always found O3 is faster, I made the test regularly as I read also regularly that O3 is not necessarly better. I never met the case where O3 was slower and never met a compiler bug. I guess it depends on the type of programmes. Effectively I always work with float numbers. My colleagues made the same conclusion. In short, you have to measure each time"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T05:58:32.137",
"Id": "497701",
"Score": "0",
"body": "@Damien I read the documentation, and it looks like O1 O2 and O3 are levels of optimization but it's unclear to me when it's appropriate / wrong to use any of them"
}
] |
[
{
"body": "<p>Just briefly:</p>\n<p>The C++ version explicitly creates many new matrix objects and vectors. The python version is probably much more efficient behind the scenes.</p>\n<p>To improve the performance of the C++ version (without changing the algorithm itself) we could:</p>\n<ul>\n<li><p>Create a single <code>vector<int></code> for the results, and pass it by reference to <code>get_spiral</code>. We can add to it with <code>push_back</code> or <code>insert</code>.</p>\n</li>\n<li><p>Instead of copying a subsection of the matrix, we could adjust and pass a simple bounds struct to the next recursive call:</p>\n<pre><code>struct bounds { std::size_t x, y, w, h; };\n</code></pre>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T16:41:39.930",
"Id": "252538",
"ParentId": "252514",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "252538",
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T11:16:14.823",
"Id": "252514",
"Score": "0",
"Tags": [
"python",
"c++",
"programming-challenge"
],
"Title": "Leetcode spiral matrix"
}
|
252514
|
<blockquote>
<h3>NOTE</h3>
<p>The script relies on <a href="https://pypi.org/project/ruamel.yaml/" rel="nofollow noreferrer">ruamel-yaml</a> and <a href="https://pypi.org/project/requests/" rel="nofollow noreferrer">requests</a> packages
available on pypi.</p>
</blockquote>
<p>I wrote a script which goes over the pack file details as specified by the <a href="https://github.com/lambtron/emojipacks" rel="nofollow noreferrer">emojipacks</a> project, and downloads (and saves) to the local drive. It downloads the files as threads, and saves to disk with the shutil's <code>copyfileobj</code> method.</p>
<p>Feel free to nitpick each and everything which could be improved.</p>
<pre><code>from argparse import ArgumentParser
from pathlib import Path
from shutil import copyfileobj
from threading import Thread
import requests
import ruamel.yaml as YAML
yaml = YAML.YAML(typ="safe")
DOWNLOAD_DIR: str = "emojis"
def download_file(url: str, filename: str, parent: Path):
"""
Downloads the file from `url` and saves to `filename` inside the `parent` directory.
"""
suffix = url.split(".")[-1]
if suffix in ("png", "jpg", "gif", "jpeg"):
filename = f"{filename}.{suffix}"
path = Path(parent / filename)
with requests.get(url, stream=True) as response:
with path.open(mode="wb") as f:
copyfileobj(response.raw, f)
def create_download_thread(url: str, name: str, path: Path) -> Thread:
thread = Thread(target=download_file, args=(url, name, path))
thread.start()
return thread
def main(dir_path: str, download_dir: str):
path = Path(dir_path)
threads = []
if not path.is_dir():
return
for yaml_file in path.glob("*.yaml"):
data = yaml.load(yaml_file)
emoji_dir = Path(download_dir) / data["title"]
emoji_dir.mkdir(parents=True, exist_ok=True)
for emoji in data["emojis"]:
names = [emoji.get("name"), *emoji.get("aliases", [])]
src = emoji.get("src")
threads += [create_download_thread(src, name, emoji_dir) for name in names]
for thread in threads:
thread.join()
if __name__ == "__main__":
parser = ArgumentParser(description="Download emojipacks to specified directory!")
parser.add_argument(
"directory",
nargs="+",
help="Directory(ies) with yaml for the emojipack specifications.",
)
parser.add_argument(
"-p",
"--download-path",
help="Directory where emojis will be downloaded.",
default=DOWNLOAD_DIR,
)
args = parser.parse_args()
for path in args.directory:
main(path, args.download_path)
</code></pre>
<p>The script was created because the project emojipacks itself is no longer maintained and the authentication system has been updated from slack. The downloaded emojis are then bulk uploaded to slack using another utility <a href="https://github.com/smashwilson/slack-emojinator" rel="nofollow noreferrer">slack-emojinator</a>.</p>
<hr />
<h2>EDIT</h2>
<p>Since this point was raised in the answer(s), <a href="https://github.com/lambtron/emojipacks#emoji-yaml-file" rel="nofollow noreferrer">the yaml specification is</a>:</p>
<blockquote>
<p>Also note that the yaml file must be indented properly and <strong>formatted
as such</strong>:</p>
<pre><code>title: food emojis:
- name: apple
src: http://i.imgur.com/Rw0Vlda.png
- name: applepie
src: http://i.imgur.com/g4RU1fM.png
</code></pre>
<p>..with the src pointing to an image file. According to Slack:</p>
<p>[...]</p>
<p>It is possible to give multiple names to a single emoji using yaml
such as:</p>
<pre><code>title: octicons emojis:
- name: pr
aliases:
- pullrequest
- mergerequest
src: https://i.imgur.com/rhwNxfc.png
</code></pre>
<p><sub>emphasis mine</sub></p>
</blockquote>
|
[] |
[
{
"body": "<h2>Parametrization</h2>\n<p><code>DOWNLOAD_DIR</code> is being used as a default for a command-line argument. This is surprising, since at first glance one would assume that this global constant is simply being used as the download directory value itself. It's less clutter and more obvious if you simply remove this global and write the string literal beside the <code>default</code> kwarg.</p>\n<h2>More pathlib</h2>\n<p>You're already using it, but you can benefit from it more. Rather than making a <code>Path()</code> here:</p>\n<pre><code>path = Path(parent / filename)\n</code></pre>\n<ol>\n<li><p>Use <code>urllib.parse.urlparse</code> to get you a <code>ParseResult</code> with a path component, since it's a more thorough and safe parsing method than bare <code>split</code> and you only care about <code>path</code></p>\n</li>\n<li><p>Call <code>path.rsplit('/', 1)[-1]</code> - not <code>split</code> - on the path component to get the filename-like</p>\n</li>\n<li><p>Make a <code>Path</code> from the result</p>\n</li>\n<li><p>If you deeply care about image-likes, then check <code>mypath.suffix</code> for <code>.png</code>, etc.</p>\n</li>\n<li><p>Use <code>/</code> as you are now.</p>\n</li>\n</ol>\n<h2>Set membership</h2>\n<pre><code>if suffix in ("png", "jpg", "gif", "jpeg"):\n</code></pre>\n<p>should use a set for speed, and also because it more closely matches your meaning. Also, pathlib will need leading dots:</p>\n<pre><code>if suffix in {'.png', '.jpg', '.gif', '.jpeg'}:\n</code></pre>\n<h2>Noisy failure</h2>\n<pre><code>if not path.is_dir():\n return\n</code></pre>\n<p>does not help the user understand why the script quit with no message. Raise some kind of error here.</p>\n<h2>Fail-safe list construction</h2>\n<p>The first part of this expression:</p>\n<pre><code>[emoji.get("name"), *emoji.get("aliases", [])]\n</code></pre>\n<p>will not do what you want. If there is no <code>'name'</code>, a <code>None</code> will be inserted rather than nothing. A more "naive" approach that will actually work is:</p>\n<pre><code>names = emoji.get('aliases', [])\nname = emoji.get('name')\nif name is not None:\n names.append(name)\n</code></pre>\n<p>Order probably doesn't matter to you since you had been kicking off threads all at once.</p>\n<p>Somewhat-related: is this -</p>\n<pre><code>src = emoji.get("src")\n</code></pre>\n<p>actually optional? I doubt it. Currently you require that it be an actual URL. Either use <code>[]</code> if you want this to keep being fatal, or:</p>\n<pre><code>src = emoji.get("src")\nif src is not None:\n create_download_thread ...\n</code></pre>\n<h2>List append of a comprehension</h2>\n<pre><code> threads += [create_download_thread(src, name, emoji_dir) for name in names]\n</code></pre>\n<p>creates a temporary list only to throw it away again once it's been appended. The following will use the generator but not materialize it to a temporary list:</p>\n<pre><code>threads.extend(create_download_thread(src, name, emoji_dir) for name in names)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T15:09:22.400",
"Id": "497616",
"Score": "0",
"body": "1. I do have `download-path` cli param. 2. I am extracting `suffix` from the download url, because almost all the links do not return `Content-Disposition` header in response. 3. I was thinking of validating against `name` and `src` data, but the emojipack yaml requires those fields to be present, the only optional candidate is `aliases`. 4. `.extend` and noisy failures do make sense. I'll add those."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T15:14:19.557",
"Id": "497617",
"Score": "0",
"body": "Re. 1, I still think some improvement can be had, but I've edited my answer for nuance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T15:15:26.823",
"Id": "497618",
"Score": "1",
"body": "Re. 2: I know that you're extracting the suffix from the URL; my proposal is that you continue to do that but using slightly more robust parsing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T15:17:08.843",
"Id": "497619",
"Score": "1",
"body": "Re. 3: if those fields are required to be present, then do not `get` at all; use direct indexing `[ ]` - because the lack of those fields should be more of a surprise; fail as early as possible rather than filling your data with `None`s."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T13:36:32.727",
"Id": "252521",
"ParentId": "252515",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T11:22:48.330",
"Id": "252515",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"multithreading"
],
"Title": "Bulk slack emoji downloader"
}
|
252515
|
<p>I am new to Python and coding in general, and I would like feedback on this program that I wrote. It simulates a tennis game, based on a players "serv chance" (how likely it is that a player will win the ball). I primarily want feedback directed at how well my program executes the standard tennis rules, but general feedback is also welcome.</p>
<p>EDIT:
Forgot the txt-file. Just copy-paste this into a txt:</p>
<pre><code>One,0,0,0.5
Two,0,0,0.5
</code></pre>
<p>The file is structed as: Name, Won Games, Played Games, Serv Chance</p>
<pre class="lang-py prettyprint-override"><code>import random
from typing import List
class Players: #define class players
ratio = 0
def __init__(self, name, winningProb, wonGames, playedGames):
self.name = name
self.winningProb = winningProb
self.wonGames = wonGames
self.playedGames = playedGames
if playedGames == 0:
self.ratio = 0
else:
self.ratio = self.wonGames/self.playedGames
self.score = 0
def showPlayerInfo(self):
print(self.name, self.wonGames, self.playedGames, self.winningProb)
def playerInfo(self, position):
return [str(position), self.name, str(self.wonGames), str(self.playedGames), str(self.winningProb)]
def getWinningProb(self):
return self.winningProb
def getScore(self):
return self.score
def setScore(self, score):
self.score = score
def getName(self):
return self.name
def getWonGames(self):
return self.wonGames
def getPlayedGames(self):
return self.playedGames
def isInt(s):
try:
int(s)
return True
except ValueError:
return False
def readPlayers(): #reads data from "players.txt" and stores it in player
fil = open("players.txt","r")
data = fil.read()
n = data.count(",")
fil.close()
if n > 5:
txtinfo = open("players.txt", "r")
players = []
for row in txtinfo:
infoPlayers = row.split(",")
players.append(Players(infoPlayers[0], float(infoPlayers[3]), int(infoPlayers[1]), int(infoPlayers[2])))
txtinfo.close
return players
else:
print("players.txt does not seem to exist or contains unreasonable data.")
raise SystemExit(0)
def playersSortedWithBoardPlacement(players):
playersSorted = sorted(players, key=lambda x: x.ratio, reverse = True)
return playersSorted
def prettyPrint(headers: List[str], data: List[List[str]], separator: str = " ") -> None:
columnWidth = [len(s) for s in headers]
for row in data:
cwidth = [len(s) for s in row]
columnWidth = [max(ow, cw) for ow, cw in zip(
columnWidth, cwidth)]
prints = [headers] + data
for row in prints:
# Pad the data in each cell to the correct width
row_print = [cell.ljust(cwid) for cwid, cell in zip(columnWidth, row)]
print(separator.join(row_print))
def displayPlayersList(players):
print()
h = ["Placement", "Name", "Won", "Played", "winningProb"]
resultatList = []
position = 1
for i in players:
resultatList.append(i.playerInfo(position=position))
position += 1
prettyPrint(h, resultatList)
def choosePlayers(players):
chosenPlayers = []
counter = 0
print()
print("Choose two players from the players list by entering their board placement in integer.")
x = input("Enter player number for 1st player. ")
while (not isInt(x)) or int(x) > len(players) or int(x) <= 0:
x = input("Wrong input. Please enter player number again ")
x = int(x)
chosenPlayers.append(players[x-1])
y = input("Enter player number for 2nd player. ")
while (not isInt(y)) or int(x)==int(y) or int(y) > len(players) or int(y) <= 0:
y = input("Wrong input. Please enter player number again ")
y = int(y)
chosenPlayers.append(players[y-1])
return chosenPlayers
#returns playerNumber if it won
def isWonTheBall(servingPlayer):
x = random.uniform(0, 1)
if 0<x and x<servingPlayer.getWinningProb():
return True
return False
def checkGameWinner(players):
if players[0].getScore() == 4 and players[1].getScore() <= 2:
return 1
if players[1].getScore() == 4 and players[0].getScore() <= 2:
return 2
if players[1].getScore() > 2 and players[0].getScore() > 2:
if players[1].getScore() >= players[0].getScore()+2:
return 2
elif players[0].getScore() >= players[1].getScore()+2:
return 1
return 0
def playGame(players, displayBoardPerBall, displayBoardPerGame, flag, pauseAfterBalls):
ballCounter = 0
while True:
if flag == 1:
flag = 2
if isWonTheBall(players[0]):
players[0].setScore(players[0].getScore() + 1)
else:
players[1].setScore(players[1].getScore() + 1)
elif flag == 2:
flag == 1
if isWonTheBall(players[1]):
players[1].setScore(players[1].getScore() + 1)
else:
players[0].setScore(players[0].getScore() + 1)
ballCounter += 1
if displayBoardPerBall:
print("\nBall scores until now")
print(players[0].name, players[0].getScore())
print(players[1].name, players[1].getScore())
print()
if pauseAfterBalls == ballCounter:
ballCounter = 0
nothing = input("Game Paused. Enter Any Letter To Continue.")
#whoWon stores 0 if nobody won
whoWon = checkGameWinner(players)
if whoWon!=0:
print("\n\nPlayer",whoWon+1,"won this game.")
players[0].setScore(0)
players[1].setScore(0)
return whoWon
if players[0].getScore() == 3 and players[1].getScore() == 3:
print("\nDEUCE!!\n")
def whoWillServeFirst():
return random.randint(1,2)
def isEven(num):
if num%2==0:
return True
else:
return False
def isOdd(num):
if num%2!=0:
return True
else:
return False
def playSet(players, displayBoardPerBall, displayBoardPerGame, pauseAfterBalls, pauseAfterGames):
player1Wins = 0
player2Wins = 0
gameCounter = 0
counter = 1
unflag = 0
#this flag tells who will serve first in the first game
flag = whoWillServeFirst()
#flag is odd server i.e 1,3,5. Unflag is even server i.e 2,4,6
if flag == 1:
unflag = 2
else:
unflag == 1
while True:
print("\nGame #",counter,"starts now.")
counter+=1
gameCounter += 1
if isEven(gameCounter):
server = unflag
elif isOdd(gameCounter):
server = flag
x = playGame(players, displayBoardPerBall, displayBoardPerGame, server, pauseAfterBalls)
if x == 1:
player1Wins += 1
elif x == 2:
player2Wins += 2
if displayBoardPerGame:
print("\nGame scores until now")
print(players[0].name, player1Wins)
print(players[1].name, player2Wins)
gameCounter += 1
if gameCounter == pauseAfterGames:
gameCounter = 0
nothing = input("Set Paused. Enter Any Letter To Continue.")
#once a player has won 6 games and is at least 2 games ahead, they wins the match
if player1Wins > 5 and player1Wins >= player2Wins+2:
return 1
elif player2Wins > 5 and player2Wins >= player1Wins+2:
return 2
def play3Sets(players, displayBoardPerBall, displayBoardPerGame, pauseAfterBalls, pauseAfterGames):
player1Wins = 0
player2Wins = 0
counter = 1
while True:
print("\nSet #", counter, "starts now.")
x = playSet(players, displayBoardPerBall, displayBoardPerGame, pauseAfterBalls, pauseAfterGames)
if x == 1:
player1Wins += 1
elif x == 2:
player2Wins += 1
print("\nSet scores until now")
print(players[0].name, player1Wins)
print(players[1].name, player2Wins)
#winning 2 sets first wins you the match
if player1Wins >= 2:
return players[0]
elif player2Wins >= 2:
return players[1]
def updateTextFiles(winner, players, totalPlayers):
f = open("players.txt", "w")
i = 0
playerString = []
for ele in totalPlayers:
if ele.getName() == winner.getName():
playerString.append(str(ele.getName()+','+str(int(ele.getWonGames()+1))+','+str((int(ele.getPlayedGames())+1))+','+str(ele.getWinningProb()) +'\n'))
elif ele.getName() == players[0].getName() or ele.getName()==players[1].getName():
playerString.append(str(ele.getName()+','+str(ele.getWonGames())+','+str((int(ele.getPlayedGames())+1))+','+str(ele.getWinningProb())+'\n'))
else:
playerString.append(str(ele.getName()+','+str(ele.getWonGames())+','+str(ele.getPlayedGames())+','+str(ele.getWinningProb())+'\n'))
i+=1
f.writelines(playerString)
def play():
print("WELCOME! The tennis simulation is about to start.\n")
totalPlayers = readPlayers()
totalPlayers = playersSortedWithBoardPlacement(totalPlayers)
displayPlayersList(totalPlayers)
#choosing players who'll play the game
players = choosePlayers(totalPlayers)
print("\n")
while True:
flag = input("Do you want to view the scoreboards after every ball?(y/n) ")
if flag == 'y' or flag == 'Y':
displayBoardPerBall = True
print("Displays result after every ball.")
break
if flag == 'n' or flag == 'N':
displayBoardPerBall = False
print("Does NOT display result after every ball.")
break
print("Wrong input.")
flag =''
while True:
flag = input("Do you want to view the scoreboards after every game?(y/n) ")
if flag == 'y' or 'Y':
displayBoardPerGame = True
print("Displays result after every game.")
break
if flag == 'n' or 'N':
displayBoardPerGame = False
print("Does NOT display result after every ball.")
break
print("Wrong input.")
while True:
try:
x = int(input("After how many *balls* do you want to pause the game? (Range 1-4). Enter 0 to continue without pausing. "))
if x == 0:
pauseAfterBalls = float('inf')
break
if x>0 and x<5:
pauseAfterBalls = x
break
print("Wrong input. Try again.")
except ValueError:
print("Wrong input. Try again.")
while True:
try:
x = int(input("After how many *games* do you want to pause the game? (Range 1-4). Enter 0 to continue without pausing. "))
if x == 0:
pauseAfterGames = float('inf')
break
if x>0 and x<5:
pauseAfterGames = x
break
print("Wrong input. Try again.")
except ValueError:
print("Wrong input. Try again.")
winner = play3Sets(players, displayBoardPerBall, displayBoardPerGame, pauseAfterBalls, pauseAfterGames)
updateTextFiles(winner, players, totalPlayers)
newResult = readPlayers()
print("\n\nCongratulations player", winner.name, "\nYou won the match.\n")
displayPlayersList(newResult)
play()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T11:33:55.050",
"Id": "497603",
"Score": "0",
"body": "`No such file or directory: 'players.txt'`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T12:11:20.843",
"Id": "497604",
"Score": "0",
"body": "Edited post, sorry for the inconvenience."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T12:15:49.047",
"Id": "497605",
"Score": "0",
"body": "no problem, we all forget things"
}
] |
[
{
"body": "<h2>Listing members</h2>\n<pre><code>def playerInfo(self, position): \n return [str(position), self.name, str(self.wonGames), str(self.playedGames), str(self.winningProb)]\n</code></pre>\n<p>This method's name is misleading. It seems like you're making an attempt at tabular output, which is reasonable; but you're going about it in a somewhat awkward way. You're probably better off calling this something like <code>as_row</code>, and omitting position since it has nothing to do with the class instance. You can append this externally; this loop:</p>\n<pre><code>resultatList = []\nposition = 1\nfor i in players:\n resultatList.append(i.playerInfo(position=position)) \n position += 1\n\nprettyPrint(h, resultatList) \n</code></pre>\n<p>can become</p>\n<pre class=\"lang-py prettyprint-override\"><code>result_list = []\n\nfor position, player in enumerate(players, 1):\n result_list.append([str(position), *player.as_row()])\n\npretty_print(headers, result_list)\n</code></pre>\n<h2>Getters</h2>\n<p>All of these:</p>\n<pre><code>def getWinningProb(self):\n return self.winningProb\ndef getScore(self):\n return self.score\ndef setScore(self, score):\n self.score = score\ndef getName(self):\n return self.name\ndef getWonGames(self):\n return self.wonGames\ndef getPlayedGames(self):\n return self.playedGames\n</code></pre>\n<p>need to be deleted. This isn't Java - there is no enforced public or private, and the convention is that if a member is set without a leading underscore, it's simply publicly accessible.</p>\n<h2>Is-integer</h2>\n<p>For your purposes, this entire method <code>isInt</code> can be replaced with <code>str.isnumeric()</code>. But you don't even need that; this loop:</p>\n<pre><code>x = input("Enter player number for 1st player. ")\nwhile (not isInt(x)) or int(x) > len(players) or int(x) <= 0:\n x = input("Wrong input. Please enter player number again ")\nx = int(x)\n</code></pre>\n<p>can be</p>\n<pre><code>while True:\n try:\n x = int(input("Enter player number for 1st player. "))\n if 0 <= x < len(players):\n break\n except ValueError:\n pass\n\n print('Wrong input.')\n</code></pre>\n<h2>Safe file closing</h2>\n<pre><code>fil = open("players.txt","r")\ndata = fil.read()\nn = data.count(",")\nfil.close()\n</code></pre>\n<p>will leave a file handle dangling if <code>read</code> or <code>count</code> throw an exception. The solution is to use a <code>with</code> context manager:</p>\n<pre><code>with open('players.txt') as fil:\n data = fil.read()\n\nn = data.count(',')\n</code></pre>\n<p>You re-open it as <code>txtinfo</code> - don't do this; simply keep the existing <code>fil</code> open and move your player info parsing code within the <code>with</code> block. You'll probably need to seek to the beginning after your <code>read()</code> call.</p>\n<h2>Exiting</h2>\n<pre><code> raise SystemExit(0)\n</code></pre>\n<p>is a very strange way of saying</p>\n<pre><code>exit(0)\n</code></pre>\n<p>and you should probably just do the latter.</p>\n<h2>Grammar, PEP8</h2>\n<p><code>isWonTheBall</code> should just be <code>won_the_ball</code>. CamelCase is discouraged in favour of lower_snake_case for method and variable names.</p>\n<h2>Combined inequalities</h2>\n<pre><code>if 0<x and x<servingPlayer.getWinningProb():\n</code></pre>\n<p>can be</p>\n<pre><code>if 0 < x < serving_player.get_winning_prob():\n</code></pre>\n<h2>isEven</h2>\n<p>Use boolean expression values directly:</p>\n<pre><code>def isEven(num):\n if num%2==0:\n return True\n else:\n return False\n</code></pre>\n<p>can be</p>\n<pre><code>def is_even(num: int) -> bool:\n return num%2 == 0\n</code></pre>\n<p>Also note the use of signature type hints.</p>\n<p>There's a lot more, but this should get you a start.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T18:46:16.193",
"Id": "497650",
"Score": "1",
"body": "it is post id 252525 :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T19:01:33.510",
"Id": "497651",
"Score": "0",
"body": "@hjpotter92 ha, neat. I was particularly proud when I accidentally filed ticket #33333 at work a few months back."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T09:25:31.273",
"Id": "497717",
"Score": "0",
"body": "Incredible detailed answer! Thank you. I haven't had a chance to go through it just yet, but will do asap."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T14:27:17.730",
"Id": "252525",
"ParentId": "252516",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T11:31:09.300",
"Id": "252516",
"Score": "4",
"Tags": [
"python-3.x"
],
"Title": "Tennis simulation"
}
|
252516
|
<p>This is my 2nd shot at dynamic memory allocation. This project is for practice purposes. So many things were considered whilst writing this minimal project.</p>
<ol>
<li>I considered using placement new to dynamically allocate memory, this would be optimal for large objects. I finally resolved to restrict user of my class to c++ built-in types</li>
<li>I considered having commutative arithmetic operators. I finally decided that <code>2 + mat</code> makes no sense</li>
<li>I considered supporting range checking, after much consideration, I decided that users of my class should be more careful :-)</li>
<li>I considered making <code>co_factor</code>, <code>det</code>, <code>transpose</code>, <code>swap</code>, <code>valid_dim</code> member-functions. I finally decided that those functions do not need access to <code>elem_</code> so I removed them from the interface.</li>
</ol>
<p>The following are some areas I hope to get reviews on and as such improve upon.</p>
<ol>
<li>Design</li>
<li>Performance</li>
<li>Ease of use</li>
</ol>
<p>Note: The code is a little large.</p>
<h2>Matrix.h</h2>
<pre><code>
#ifndef MATRIX_H_
#define MATRIX_H_
#include <algorithm>
#include <cstdlib>
#include <initializer_list>
#include <iostream>
namespace mat
{
template<typename T>
void swap(T& a, T& b);
bool valid_dim(int row, int column);
template<class T>
class Matrix
{
public:
explicit Matrix(int row = 1, int column = 1, const T& val = {})
: row_{row}, column_{column}
{
if(!valid_dim(row_, column_))
throw std::invalid_argument("Exception: Invalid row and column in constructor");
elem_ = new T[ row_ * column_];
for(size_t i = 0; i != size(); ++i )
elem_[i] = val;
}
Matrix(int row, int column, std::initializer_list<T> list)
: row_{row}, column_{column}
{
if(!valid_dim(row_, column_))
throw std::invalid_argument("Exception: Invalid row and column in constructor");
if(list.size() != size())
throw std::runtime_error("Exception: Intializer list argument does not match Matrix size in constructor");
elem_ = new T[ row_ * column_];
int i = 0;
for(const auto& item : list)
{
elem_[i] = item;
++i;
}
}
Matrix(const Matrix& M)
: row_{M.row_}, column_{M.column_}, elem_{new T[ row_ * column_]}
{
std::copy(M.elem_, M.elem_+size(), elem_);
}
Matrix& operator=(const Matrix& M)
{
if(row_ != M.row_ || column_ != M.column_)
throw std::runtime_error("Exception: Unequal size in Matrix=");
row_ = M.row_;
column_ = M.column_;
std::copy(M.elem_, M.elem_ + size(), elem_);
return *this;
}
Matrix(Matrix&& M) noexcept
: row_{0}, column_{0}, elem_{nullptr}
{
swap(row_, M.row_);
swap(column_, M.column_);
swap(elem_, M.elem_);
}
Matrix& operator=(Matrix&& M) noexcept
{
swap(row_, M.row_);
swap(column_, M.column_);
swap(elem_, M.elem_);
return *this;
}
~Matrix() { delete [] elem_; }
T& operator()(const int i, const int j) { return elem_[i * column_ + j]; } // Note: no range checking
const T& operator()(const int i, const int j) const { return elem_[i * column_ + j]; }
size_t size() const { return row_ * column_; }
size_t row() const { return row_; }
size_t column() const { return column_; }
Matrix& operator+=(const Matrix& rhs)
{
Matrix res = (*this) + rhs;
*this = res;
return *this;
}
Matrix& operator-=(const Matrix& rhs)
{
Matrix res = (*this) - rhs;
*this = res;
return *this;
}
Matrix& operator*=(const Matrix& rhs)
{
Matrix res = (*this) * rhs;
*this = res;
return *this;
}
Matrix& operator+=(const double rhs)
{
Matrix res = (*this) + rhs;
*this = res;
return *this;
}
Matrix& operator-=(const double rhs)
{
Matrix res = (*this) - rhs;
*this = res;
return *this;
}
Matrix& operator*=(const double rhs)
{
Matrix res = (*this) * rhs;
*this = res;
return *this;
}
Matrix& operator/=(const double rhs)
{
Matrix res = (*this) / rhs;
*this = res;
return *this;
}
Matrix operator+(const Matrix& rhs)
{
if(row_ != rhs.row_ || column_ != rhs.column_)
throw std::runtime_error("Exception: Unequal size in Matrix+");
Matrix res(row_, column_, 0.0);
for(size_t i = 0; i != size(); ++i)
{
res.elem_[i] = elem_[i] + rhs.elem_[i];
}
return res;
}
Matrix operator-(const Matrix& rhs)
{
if(row_ != rhs.row_ || column_ != rhs.column_)
throw std::runtime_error("Exception: Unequal size in Matrix-");
Matrix res(row_, column_, 0.0);
for(size_t i = 0; i != size(); ++i)
{
res.elem_[i] = elem_[i] - rhs.elem_[i];
}
return res;
}
Matrix operator*(const Matrix& rhs)
{
if(row_ != rhs.column_ )
throw std::runtime_error("Exception: Unequal size in Matrix*");
Matrix res(rhs.row_, column_, 0.0);
for(int i = 0; i != rhs.row_; ++i)
{
for(int j = 0; j != column_; ++j)
{
for(int k = 0; k != row_; ++k)
{
res(i, j) += rhs(i, k) * this->operator()(k, j);
}
}
}
return res;
}
Matrix operator+(const double rhs)
{
Matrix res(row_, column_, 0.0);
for(size_t i = 0; i != size(); ++i)
res.elem_[i] = elem_[i] + rhs;
return res;
}
Matrix operator-(const double rhs)
{
Matrix res(row_, column_, 0.0);
for(size_t i = 0; i != size(); ++i)
res.elem_[i] = elem_[i] - rhs;
return res;
}
Matrix operator*(const double rhs)
{
Matrix res(row_, column_, 0.0);
for(size_t i = 0; i != size(); ++i)
res.elem_[i] = elem_[i] * rhs;
return res;
}
Matrix operator/(const double rhs)
{
Matrix res(row_, column_, 0.0);
for(size_t i = 0; i != size(); ++i)
res.elem_[i] = elem_[i] / rhs;
return res;
}
private:
int row_;
int column_;
T *elem_;
};
template<typename T>
inline void swap(T& a, T& b)
{
const T tmp = std::move(a);
a = std::move(b);
b = std::move(tmp);
}
inline bool valid_dim(int row, int column) { return (row >= 1 || column >= 1); }
template<typename T>
Matrix<T> transpose(const Matrix<T>& A)
{
Matrix<T> res(A.column(), A.row(), 0.0);
for(size_t i = 0; i != res.row(); ++i)
{
for(size_t j = 0; j != res.column(); ++j)
{
res(i, j) = A(j, i);
}
}
return res;
}
template<typename T>
Matrix<T> co_factor(const Matrix<T>& A, size_t p, size_t q)
{
if(p >= A.row() || q >= A.column())
throw std::invalid_argument("Exception: Invalid argument in cofactor(int, int)");
if(A.row() != A.column())
throw std::runtime_error("Exception:Unequal row and column in co_factor(int, int)");
Matrix<T> res(A.row() - 1, A.column() - 1);
size_t a = 0, b = 0;
for(size_t i = 0; i != A.row(); ++i)
{
for(size_t j = 0; j != A.column(); ++j)
{
if(i == p || j == q)
continue;
res(a, b++) = A(i, j);
if(b == A.column() - 1)
{
b = 0;
a++;
}
}
}
return res;
}
template<typename T>
double det(const Matrix<T> A)
{
if(A.row() != A.column())
throw std::runtime_error("Exception:Unequal row and column in det()");
if(A.row() == 2)
{
return ( A(0,0) * A(A.row()-1,A.row()-1) ) - ( A(0,1) * A(A.row()-1,A.row()-2) );
}
int sign = 1, determinant = 0;
for(size_t i = 0; i != A.row(); ++i)
{
Matrix<T> co_fact = co_factor(A, 0, i);
determinant += sign * A(0, i) * det(co_fact);
sign = -sign;
}
return determinant;
}
}
#endif
</code></pre>
<h2>main.cpp</h2>
<pre><code>#include <iostream>
#include "Matrix.h"
using namespace mat;
template<typename T>
void display(const T& A)
{
for(size_t i = 0; i != A.row(); ++i)
{
for(size_t j = 0; j != A.column(); ++j)
{
std::cout << A(i, j) << " ";
}
std::cout << '\n';
}
}
int main()
{
Matrix<double> my_mat1(2,2, {1,2,3,4});
Matrix<double> my_mat2(2,2, {5,6,7,8});
std::cout << "\nDisplay matrix: \n";
display(my_mat1);
std::cout << '\n';
display(my_mat2);
std::cout << "\nAddition: \n";
display(my_mat1 + my_mat2);
std::cout << "\nSubtraction: \n";
display(my_mat2 - my_mat1);
std::cout << "\nMultiplication: \n";
display(my_mat1 * my_mat2);
std::cout << "\nInplace Addition: \n";
my_mat1 += my_mat2;
display(my_mat1);
std::cout << "\nInplace Subtraction: \n";
my_mat1 -= my_mat2;
display(my_mat1);
std::cout << "\nInplace Multiplication: \n";
my_mat1 *= my_mat2;
display(my_mat1);
std::cout << "\nTranspose: \n";
display(transpose(my_mat2));
std::cout << "\nAdding 2 to my_mat1: \n";
my_mat1 += 2;
display(my_mat1);
Matrix<int> my_mat3 {4,4,
{
1,0,2,-1,
3,0,0,5,
2,1,4,-3,
1,0,5,0
}};
Matrix<double> co_factor_mat = co_factor(my_mat1, 0, 0);
std::cout << "\nCofactor: \n";
display(co_factor_mat);
std::cout << "Determinant of matrix: " << det(my_mat3) << std::endl;
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>Use an unsigned type for rows and columns (probably <code>std::size_t</code>).</li>\n<li>Creating a size 1 matrix as the default (empty constructor args) probably isn't useful behavior. We could have an ordinary default constructor creating a zero-sized matrix.</li>\n<li><code>valid_dim</code> is wrong (<code>||</code> should be <code>&&</code>) and unnecessary if we use an unsigned type for rows and columns. (There's nothing wrong with allocating a zero size array in C++, or we could set <code>elem_</code> to <code>nullptr</code>).</li>\n<li>We can use <code>std::fill</code> in the value constructor and <code>std::copy</code> in init list constructor.</li>\n<li>It's strange to prevent assignment from a different sized matrix (and very unexpected for the user for it to throw). We should just resize the matrix if necessary.</li>\n<li>We can provide an <code>at(i,j)</code> function that does size checking (similar to the standard library containers).</li>\n<li>We'd normally implement the binary math operators (<code>+</code>, <code>-</code>, etc.) using the math-assignment operators (<code>+=</code>, <code>-=</code>, etc.); the opposite of how they are implemented above. (The assignment versions can modify the values in place).</li>\n<li><code>2.0 * m</code> is as reasonable as <code>m * 2.0</code> - we should implement that too. Usually we'd implement binary math operators as free functions using <code>+=</code>, <code>-=</code> etc. where possible (and it's only one more line of code where we can't).</li>\n<li><code>swap</code> can't <code>std::move</code> out of the <code>const</code> <code>tmp</code> variable - it'll always copy.</li>\n<li>Note that we don't need to write a custom <code>swap</code> function - <code>std::swap</code> will do exactly the same thing by default.</li>\n<li>There are quite a lot of other useful functions we could implement (c.f. the standard library containers): <code>empty()</code>, <code>clear()</code>, <code>resize()</code>, <code>data()</code>, iterators (<code>begin()</code>, <code>rbegin()</code>, etc.), <code>operator==</code> and <code>operator!=</code>.</li>\n<li>I guess this is an exercise in manual memory management, but we really should use <code>std::vector</code> for storage! Implementing everything becomes much easier.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T14:01:47.483",
"Id": "497742",
"Score": "0",
"body": "Keeping unsigned for rows and columns might lead to conversion from -1 to 4294967295. This might not be what the user expected."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T16:40:58.800",
"Id": "497762",
"Score": "1",
"body": "Well... that's how unsigned arithmetic works in C++, and we have to assume the user has a basic level of competency in the language. (It's how all the standard library containers do things, so it's at least consistent)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T22:06:02.970",
"Id": "252564",
"ParentId": "252517",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "252564",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T12:03:28.820",
"Id": "252517",
"Score": "4",
"Tags": [
"c++",
"performance",
"object-oriented",
"reinventing-the-wheel",
"memory-management"
],
"Title": "Matrix template Class"
}
|
252517
|
<h3>Project</h3>
<p>I've created a puzzle site with automatically generated sudokus.</p>
<p>For more information on Sudokus, please see the <a href="https://en.wikipedia.org/wiki/Sudoku" rel="nofollow noreferrer">wikipedia article</a>.</p>
<h3>The code</h3>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const GRID_SIZE = 9;
const REMOVE = 50;
let solution = createArray(9, 9);
let textIsVisible = false;
window.addEventListener('load', function() {
initialize();
});
document.getElementById('submit').addEventListener('click', function() {
let elements = document.getElementsByTagName('input');
let k = 0;
for(let i = 0; i < 9; i++) {
for(let j = 0; j < 9; j++) {
let value = parseInt(elements[k].value);
if(value !== solution[i][j]) {
textIsVisible = true;
$('#text').text('That\'s not the correct solution!');
return;
}
k++;
}
}
textIsVisible = true;
$('#text').text('Correct!');
});
document.getElementById('reset').addEventListener('click', function() {
initialize();
});
function initialize() {
textIsVisible = false;
$('#text').text('');
let elements = document.getElementsByTagName('input');
for(let i = 0; i < elements.length; i++) {
elements[i].classList.add('focus');
elements[i].removeAttribute('readonly');
elements[i].classList.remove('bold');
elements[i].addEventListener('click', function() {
$('#text').text('');
});
}
let sudoku = generate();
solveSudoku(sudoku, 0);
showSudoku(elements, sudoku);
}
function generate() {
//Fill with zeros
let sudoku = createArray(9, 9);
for(let i = 0; i < 9; i++) {
for (let j = 0; j < 9; j++) {
sudoku[i][j] = 0;
}
}
//Add ten random numbers
for(let i = 0; i < 10; i++) {
sudoku = addNumber(sudoku);
}
/*
* Add random numbers in the first row in addition to random numbers
* in addition to random numbers on random positions
*/
sudoku[0][1] = legalNumbers(sudoku, 0, 1);
sudoku[0][4] = legalNumbers(sudoku, 0, 4);
sudoku[0][7] = legalNumbers(sudoku, 0, 7);
//Solve sudoku
solveSudoku(sudoku, 0);
for(let i = 0; i < 9; i++) {
for (let j = 0; j < 9; j++) {
sudoku[i][j] = solution[i][j];
}
}
/*
* Remove elements so that sudoku still has unique solution
*/
let i = 0;
while(i < REMOVE) {
let row = Math.floor(Math.random() * 9);
let col = Math.floor(Math.random() * 9);
if(sudoku[row][col] !== 0) {
let cache = sudoku[row][col];
sudoku[row][col] = 0;
if(solveSudoku(sudoku, 0) !== 1) {
/*
* Go one step back if sudoku doesn't have unique solution
* anymore
*/
sudoku[row][col] = cache;
}
else {
i++;
}
}
}
return sudoku;
}
function createArray(rows, cols) {
const array = new Array(rows);
for (let i = 0; i < cols; i++) {
array[i] = new Array(cols);
}
return array;
}
function addNumber(sudoku) {
/*
* Find random position to add number
*/
let row = Math.floor(Math.random() * 9);
let col = Math.floor(Math.random() * 9);
/*
* Add random, but legal number
*/
sudoku[row][col] = legalNumbers(sudoku, row, col);
return sudoku;
}
function solveSudoku(sudoku, count) {
for(let i = 0; i < GRID_SIZE; i++) {
for (let j = 0; j < GRID_SIZE; j++) {
/*
* Only empty fields will be changd
*/
if(sudoku[i][j] === 0) {
/*
* Try all numbers between 1 and 9
*/
for(let n = 1; n <= GRID_SIZE && count < 2; n++) {
/*
* Is number n safe?
*/
if(checkRow(sudoku, i, n) && checkColumn(sudoku, j, n) && checkBox(sudoku, i, j, n)) {
sudoku[i][j] = n;
let cache = solveSudoku(sudoku, count);
/*
* new solution found
*/
if(cache > count) {
count = cache;
/*
* Save new solution
*/
for(let k = 0; k < GRID_SIZE; k++) {
for(let l = 0; l < GRID_SIZE; l++) {
if(sudoku[k][l] !== 0) {
solution[k][l] = sudoku[k][l];
}
}
}
sudoku[i][j] = 0;
}
/*
* Not a solution, go one step back
*/
else {
sudoku[i][j] = 0;
}
}
}
/*
* No other solution found
*/
return count;
}
}
}
/*
* found another solution
*/
return count + 1;
}
function showSudoku(elements, sudoku) {
let k = 0;
for(let i = 0; i < GRID_SIZE; i++) {
for(let j = 0; j < GRID_SIZE; j++) {
if(sudoku[i][j] > 0) {
elements[k].value = sudoku[i][j];
elements[k].setAttribute('readonly', 'true');
elements[k].classList.remove('focus');
elements[k].classList.add('bold');
}
else {
elements[k].value = '';
}
k++;
}
}
}
/*
* Helper functions
*/
function checkRow(sudoku, row, n) {
for(let i = 0; i < GRID_SIZE; i++) {
if(sudoku[row][i] === n) {
return false;
}
}
return true;
}
function checkColumn(sudoku, col, n) {
for(let i = 0; i < GRID_SIZE; i++) {
if(sudoku[i][col] === n) {
return false;
}
}
return true;
}
function checkBox(sudoku, row, col, n) {
row = row - row % 3;
col = col - col % 3;
for(let i = row; i < row + 3; i++) {
for(let j = col; j < col + 3; j++) {
if(sudoku[i][j] === n) {
return false;
}
}
}
return true;
}
function legalNumbers(sudoku, row, col) {
let array = [];
for(let i = 1; i <= 9; i++) {
if(checkRow(sudoku, row, i) && checkColumn(sudoku, col, i) && checkBox(sudoku, row, col, i)) {
array.push(i);
break;
}
}
return array[Math.floor(Math.random() * array.length)];
}
function isNumber(elem, e) {
if(elem.value.length !== 0) {
return false;
}
let id = e.key;
let string = '123456789';
for(let i = 0; i < string.length; i++) {
if(string.charAt(i) === id) {
return true;
}
}
return false;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link rel='stylesheet' type='text/css' href='fonts/baloo/stylesheet.css'>
<link rel='stylesheet' type='text/css' href='fonts/open-sans/stylesheet.css'>
<link rel='shortcut icon' href='logo.svg'/>
<script src='jquery.js'></script>
<title>Sudoku</title>
<style>
/*
* Font sizes
*/
html {
font-size: 18px;
}
p {
font-size: 1em;
}
h1 {
font-size: 1.8em;
}
h3 {
font-size: 1.42em;
}
/*
* 'Fork me on GitHub'-image
*/
#fork {
position: absolute;
width: 160px;
height: 160px;
top: 0;
border: 0;
right: 0;
}
/*
* Main style
*/
body {
font-family: 'open-sans',sans-serif;
font-weight: normal;
line-height: 1.65;
margin-top: 30px;
}
.inner {
width: 350px;
margin: 0 auto;
}
/*
* Sudoku field container
*/
.sudoku {
line-height: 34px;
text-align: center;
}
.mainContainer {
display: inline-block;
}
.container {
line-height: 36px;
}
h1 {
font-family: 'balooregular', serif;
font-weight: normal;
color: #00410B;
}
/*
* Input fields main style
*/
input {
border: none;
text-align: center;
font-size: 1em;
width: 30px;
height: 30px;
float: left;
border-right: 2px solid black;
border-bottom: 2px solid black;
}
/*
* Don't show arrow buttons inside input fields
*/
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
display: none;
}
input[type=number] {
-moz-appearance:textfield;
}
input:focus, button:focus {
outline: none;
}
/*
* Input field additional border styles
*/
.left {
border-left: 2px solid black;
}
.right {
border-right: 2px solid red;
}
.top {
border-top: 2px solid black;
}
.bottom {
border-bottom: 2px solid red;
}
/*
* Given numbers will be bold
*/
.bold {
font-weight: bold;
font-size: 1em;
}
/*
* Fields that user has to fill out
* will be LightGray on focus
*/
.focus:focus {
background: LightGray;
}
/*
* Style of buttons
*/
button {
border: 1px solid black;
border-radius: 5px;
padding: 10px;
width: 40%;
text-align: center;
transition: 0.3s ease;
margin: 20px 5% 30px;
float: left;
}
button:hover {
color: #FFFFF0;
background: #00410B;
}
/*
* links
*/
a {
color: #2B823A;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
/*
* Responsive
*/
@media (max-width: 650px) {
#fork {
display: none;
}
}
@media (max-width: 350px) {
html {
font-size: 16px;
}
.inner {
width: 100%;
}
}
@media (max-width: 330px) {
.sudoku {
line-height: 24px;
text-align: center;
}
.container {
line-height: 26px;
}
input {
border: none;
text-align: center;
font-size: 1em;
width: 20px;
height: 20px;
float: left;
border-right: 2px solid black;
border-bottom: 2px solid black;
}
}
</style>
</head>
<body>
<a href='https://github.com/philippwilhelm/Sudoku' id='fork'><img alt='' src='fork.png'></a>
<div class='inner'>
<h1>Sudoku</h1>
<div class='sudoku'>
<div class='mainContainer'>
<div class='container'>
<input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='left top'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='top'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='right top'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='notLeft top'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='top'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='right top'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='notLeft top'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='top'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='top'/><br>
</div>
<input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='left'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class=''/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='right'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='notLeft'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class=''/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='right'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='notLeft'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class=''/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class=''/><br>
<input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='bottom left'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='bottom'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='right bottom'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='notLeft bottom'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='bottom'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='right bottom'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='notLeft bottom'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='bottom'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='bottom'/><br>
<input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='left'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class=''/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='right'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='notLeft'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class=''/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='right'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='notLeft'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class=''/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class=''/><br>
<input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='left'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class=''/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='right'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='notLeft'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class=''/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='right'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='notLeft'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class=''/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class=''/><br>
<input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='bottom left'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='bottom'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='right bottom'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='notLeft bottom'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='bottom'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='right bottom'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='notLeft bottom'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='bottom'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='bottom'/><br>
<input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='left'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class=''/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='right'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='notLeft'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class=''/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='right'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='notLeft'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class=''/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class=''/><br>
<input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='left'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class=''/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='right'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='notLeft'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class=''/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='right'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='notLeft'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class=''/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class=''/><br>
<input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='left'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class=''/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='right'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='notLeft'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class=''/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='right'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class='notLeft'/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class=''/><input maxlength='1' onkeypress='return isNumber(this, event)' type='number' min='0' max='9' value='0' class=''/><br>
</div>
</div>
<button id='submit'>Submit</button><button id='reset'>New Game</button>
<span id='text'></span>
<script src='sudoku_generator.js'></script>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
<h3>Question</h3>
<p>All suggestions are welcome. The html-file only is a minimal working example, so it is not really worth reviewing.</p>
|
[] |
[
{
"body": "<p>I suggest writing code in functional style instead of excessive usage of loops. This will make your code more concise (you can reduce code for your solution by half) and readable. I rewrote a few of your functions to give an idea of what I mean:</p>\n<pre><code>const range = (from, to) => [...Array(to - from + 1).keys()].map((i) => i + from);\n\nconst checkRow = (sudoku, row, n) => range(0, GRID_SIZE - 1).every((x) => sudoku[row][x] !== n);\nconst checkColumn = (sudoku, col, n) => range(0, GRID_SIZE - 1).every((x) => sudoku[x][col] !== n);\n\nconst combine = (arr1, arr2) => arr1.reduce((result, x) => result.concat(arr2.map((y) => [x, y])), []);\n\nconst boxCells = (row, col) => {\n row = row - row % 3;\n col = col - col % 3;\n return combine(range(row, row + 2), range(col, col + 2));\n}\n\nconst checkBox = (sudoku, row, col, n) => boxCells(row, col).every(([r, c]) => sudoku[r][c] !== n);\n\nconst legalNumbers = (sudoku, row, col) => {\n const valid = (x) => checkRow(sudoku, row, x) && checkColumn(sudoku, col, x) && checkBox(sudoku, row, col, x);\n return range(1, 9).find(valid);\n}\n\nconst isNumber = (elem, { key }) => elem.value === '' && '123456789'.split('').includes(key);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T15:57:57.747",
"Id": "252533",
"ParentId": "252518",
"Score": "3"
}
},
{
"body": "<p><strong>Always use <code>const</code> when possible</strong> - only use <code>let</code> when you <a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">want to warn other readers of the code</a> that the variable name may be reassigned. If something won't be reassigned, make it clear to readers that they don't have to worry about that by using <code>const</code> instead of <code>let</code>.</p>\n<p><strong>Anonymous callback wrappers around a single function are superfluous</strong>, at least in almost all cases - just pass the <em>single function</em> as the callback instead (see below).</p>\n<p><strong>Prefer DOMContentLoaded over <code>load</code></strong> - <code>load</code> waits for <em>all resources</em> to completely finish downloading, including possibly heavyweight images. Better to make the page interactive as soon as the DOM is populated, instead of waiting for sub-resources to finish.</p>\n<pre><code>window.addEventListener('DOMContentLoaded', initialize);\n</code></pre>\n<p>Or, since you're using jQuery, you could also do:</p>\n<pre><code>$(initialize);\n</code></pre>\n<p><strong>jQuery or vanilla DOM methods?</strong> At the moment, you're using jQuery for <em>only one purpose</em> - to call <code>.text</code>, to set the text of elements. This is odd: jQuery is a big library, and element text can be set easily by simply using <code>textContent</code>, no library required. If you <em>do</em> want to make this into a jQuery project (which I wouldn't recommend, since it doesn't seem to be accomplishing anything useful at the moment), it would be more stylistically consistent to use jQuery whenever you're using DOM manipulation.</p>\n<p><strong><code>textIsVisible</code> doesn't do anything</strong> You reference it 4 times, but always to <em>assign</em> to it, never to <em>read</em> from it - might as well remove it entirely.</p>\n<p><strong>Prefer array methods and iterators</strong> over <code>for</code> loops that require manual iteration and have no abstraction. For example, given:</p>\n<pre><code>let elements = document.getElementsByTagName('input');\nfor(let i = 0; i < elements.length; i++) {\n elements[i].classList.add('focus');\n // do lots of other stuff with elements[i]\n</code></pre>\n<p>Unless you need to use the index somewhere other than to reference <code>elements[i]</code>, it would make more sense to write <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"noreferrer\">DRY</a> and more abstract code with an iterator. It's shorter too:</p>\n<pre><code>for (const element of elements) {\n element.classList.add('focus');\n // do lots of other stuff with element\n</code></pre>\n<p>Aleksei's answer shows how to use array methods with other parts of the code too.</p>\n<p><strong>Condense class names</strong> Since the cells will always have exactly 1 of 2 classes, <code>focus</code> or <code>bold</code>, consider using just a single class instead that you toggle on and off - perhaps <code>focus</code>. For example, instead of:</p>\n<pre><code>.bold {\n font-weight: bold;\n font-size: 1em;\n}\n</code></pre>\n<p>use</p>\n<pre><code>.container > input {\n font-weight: bold;\n font-size: 1em;\n}\n</code></pre>\n<p>whose rules get overridden by a <code>.container > .focus</code> rule below.</p>\n<p><strong>Don't reassign a variable to the same object you already have a reference to</strong>. That is:</p>\n<pre><code>sudoku = addNumber(sudoku);\n</code></pre>\n<p>should be</p>\n<pre><code>addNumber(sudoku);\n</code></pre>\n<p><strong>Use comments to describe why, or what <em>if</em> what isn't obvious</strong> - for example:</p>\n<pre><code>// Go one step back if sudoku doesn't have unique solution anymore\n</code></pre>\n<p>is good, whereas</p>\n<pre><code>//Solve sudoku\nsolveSudoku(sudoku, 0);\n</code></pre>\n<p>doesn't communicate anything useful.</p>\n<p><strong>solveSudoku</strong> is somewhat confusing: it returns a value that often isn't used by callers, and reassigns the solution into a variable completely disconnected from the caller. For example:</p>\n<pre><code>let sudoku = generate();\nsolveSudoku(sudoku, 0);\nshowSudoku(elements, sudoku);\n</code></pre>\n<p>The purpose of <code>solveSudoku</code> is mysterious until you read the function to find out what its side-effects are. Functions are easiest to make sense of at a glance when they're pure, or at least not too impure. Here, consider <em>returning the value</em> from <code>solveSudoku</code> and using it, eg:</p>\n<pre><code>const sudoku = generate();\nsolution = solveSudoku(sudoku, 0).solution; // with `numUniqueSolutions` as the other property in the object\nshowSudoku(elements, sudoku);\n</code></pre>\n<p>That makes a lot more sense at a glance. You could go further and avoid the reassignment of the <code>solution</code> variable at all, but that would require some significant refactoring.</p>\n<p>The above approach also makes it much clearer what sort of value <code>solveSudoku</code> is returning: <code>numUniqueSolutions</code> (This isn't obvious at a glance from your current implementation of <code>solveSudoku</code>)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T17:50:59.160",
"Id": "252545",
"ParentId": "252518",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "252545",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T12:15:58.407",
"Id": "252518",
"Score": "3",
"Tags": [
"javascript",
"sudoku"
],
"Title": "Sudoku Game with automatically generated Sudokus"
}
|
252518
|
<p>I am a beginner in Python-3. I was solving a level 2 challenge in Google Foobar. Given an initial amount of items (LAMBs) I have to distribute it among individuals, who are ranked according to seniority, while adhering to the following rules:</p>
<ol>
<li>The junior most individual gets 1 Lamb</li>
<li>An immediately senior individual can't get more than twice their juniors lambs, otherwise the junior will rebel</li>
<li>A senior individual can't get less lambs than the sum of their 2 previous juniors, otherwise the senior will rebel</li>
<li>In case lambs are leftover and adding a senior does not violate any previous rules, they must be added.</li>
</ol>
<p>The goal is to find the difference between how many individuals can be paid if we pay the minimum amount to each (stingy) and the maximum amount to each (generous). I noticed that stingy condition resembles a Fibonacci sequence and the generous condition is sum of powers of 2. My code is as follows:</p>
<pre class="lang-py prettyprint-override"><code>from math import log2
def solution(total_lambs)
return (stingy(total_lambs) - generous(total_lambs))
def stingy(total_lambs)
if (total_lambs == 1): # from condition 1 at least 1 individual gets paid
return 1
elif (total_lambs == 2): # from condition 2 and 4 the most each can is 1
return 2
else:
ind, total, x0, x1 = 2, 2, 1, 1 # no. individuals, sum of Fib seq, intial Fib nos.
while (total <= total_lambs):
x0, x1 = x1, x0 + x1 # advancing the Fib seq
total = total + x1 # total is the sum of lambs paid
if (total > total_lambs):
return ind
else:
ind = ind + 1
def generous(total_lambs):
if (total_lambs == 1):
return 1
if (total_lambs == 2):
return 2
else:
ind = int(log2(capital + 1)) # typecasting to int removes decimals
if (total_lambs - 2**n + 1 >= 2**(n - 1) + 2**(n - 2)): # condition 2, 3 and 4
return ind + 1
else:
return ind
</code></pre>
<p>Please suggest improvements wherever possible.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T13:06:50.110",
"Id": "497607",
"Score": "2",
"body": "Great first question!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T13:07:11.853",
"Id": "497608",
"Score": "3",
"body": "Can you provide a link to the original question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T00:58:07.860",
"Id": "497685",
"Score": "0",
"body": "@reinderien I unfortunately submitted my response before i saved the original question so i can't copy it verbatim. However, it is available online if you search foobar Lovely lucky LAMBs."
}
] |
[
{
"body": "<h2>Early-returns</h2>\n<p>else-after-return is redundant, so your <code>stingy</code> is equivalent to</p>\n<pre class=\"lang-py prettyprint-override\"><code> if (total_lambs == 1): # from condition 1 at least 1 individual gets paid\n return 1\n if (total_lambs == 2): # from condition 2 and 4 the most each can is 1\n return 2\n\n ind, total, x0, x1 = 2, 2, 1, 1 # no. individuals, sum of Fib seq, intial Fib nos.\n while (total <= total_lambs):\n x0, x1 = x1, x0 + x1 # advancing the Fib seq\n total = total + x1 # total is the sum of lambs paid\n if (total > total_lambs): \n return ind\n ind = ind + 1\n</code></pre>\n<h2>Return parens</h2>\n<p>You have a mix of this style:</p>\n<pre><code>return 1\n</code></pre>\n<p>and this style:</p>\n<pre><code>return (stingy(total_lambs) - generous(total_lambs))\n</code></pre>\n<p>the latter not needing outer parens. Probably best to go with the non-parenthetical style. The same is true of</p>\n<pre><code>while (total <= total_lambs):\n</code></pre>\n<h2>In-place addition</h2>\n<pre><code>total = total + x1\nind = ind + 1\n</code></pre>\n<p>can be</p>\n<pre><code>total += x1\nind += 1\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T01:00:43.597",
"Id": "497686",
"Score": "0",
"body": "Thank you. As you mentioned in another comment, what can be a good name for storing Fibonnacci numbers?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T01:01:42.963",
"Id": "497687",
"Score": "0",
"body": "A good name? For which variable?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T01:09:14.143",
"Id": "497689",
"Score": "0",
"body": "Storage of the Fibonacci numbers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T01:25:40.550",
"Id": "497690",
"Score": "1",
"body": "Oh, you mean `x0` and `x1`. `prev` and `current` maybe?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T13:57:31.117",
"Id": "252523",
"ParentId": "252519",
"Score": "3"
}
},
{
"body": "<p>apart from the improvements mentioned above, for the stingy function you can also reduce the amount of code by using a list with the last 2 fibonacci members, and integrating the initial conditions into the logic</p>\n<pre><code>def stingy(total_lambs):\n paid = 0\n previous = [1, 0]\n while total_lambs > 0:\n paid += 1\n previous = [sum(previous), previous[0]]\n total_lambs -= previous[0]\n return paid\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T17:03:46.210",
"Id": "497629",
"Score": "1",
"body": "Ish. Overall this is a good suggestion, but framing this as a list doesn't make sense. Just have two variables."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T17:05:04.613",
"Id": "497630",
"Score": "0",
"body": "In other words, keep the OP's `x0`, `x1`, possibly with better names."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T01:06:21.970",
"Id": "497688",
"Score": "0",
"body": "Thanks, i will keep this structure in mind for future coding. I framed my function in this way as the rule 3 in original question had an explanation that it is not applicable if only upto 2 individuals get paid. So I did not think of this elegant way."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T16:45:12.890",
"Id": "252539",
"ParentId": "252519",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "252523",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T12:20:23.500",
"Id": "252519",
"Score": "1",
"Tags": [
"beginner",
"python-3.x",
"programming-challenge"
],
"Title": "Google foobar level 2 challenge"
}
|
252519
|
<p>The problem I am trying to solve:</p>
<blockquote>
<p>Given a string, split the string into two substrings at every possible point. The rightmost substring is a suffix. The beginning of the string is the prefix. Determine the lengths of the common prefix between each suffix and the original string. Sum and return the lengths of the common prefixes. Return an array where each element 'i' is the sum for the string 'i'. Example:</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/1YC6H.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1YC6H.png" alt="Example table" /></a></p>
<p>My Solution:</p>
<pre><code>def commonPrefix(l):
size=len(l) #Finding number of strings
sumlist=[] #Initializing list that'll store sums
for i in range(size):
total=0 #Initializing total common prefixes for every string
string=l[i] #Storing each string in string
strsize=len(string) #Finding length of each string
for j in range(strsize):
suff=string[j:] #Calculating every suffix for a string
suffsize=len(suff) #Finding length of each suffix
common=0 #Size of common prefix for each length
for k in range(suffsize):
if(string[k]==suff[k]):
common=common+1
else:
break #If characters at equal positions are not equal, break
total=total+common #Update total for every suffix
sumlist.append(total) #Add each total in list
return sumlist #Return list
</code></pre>
<p>My solution takes up a lot of time, I need help with optimizing it.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T14:56:07.557",
"Id": "497614",
"Score": "3",
"body": "Welcome to CodeReview! Please indicate the original source of this question - homework or online challenge - ideally with a link. Also, your title needs to indicate what you're actually doing, e.g. \"Finding a common prefix\"."
}
] |
[
{
"body": "<p>You can do with a list comprehension and the string <code>find</code> function</p>\n<pre><code>def common_prefix(l):\n return [\n len(l[:i]) or len(l) if l[i:].find(l[:i]) == 0 else 0\n for i in range(len(l))\n ]\n</code></pre>\n<p>Your code did not throw a good solution for the string given though</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T17:05:51.597",
"Id": "252540",
"ParentId": "252526",
"Score": "0"
}
},
{
"body": "<h2>Second for loop</h2>\n<p>Your second loop will only iterate once, because <code>string</code> is only 1 character long:</p>\n<pre class=\"lang-py prettyprint-override\"><code>string = l[i]\n</code></pre>\n<p>I think you meant to slice here.</p>\n<h2>Incrementing an <code>int</code></h2>\n<p>You can use the <code>+=</code> operator to increment an integer:</p>\n<pre class=\"lang-py prettyprint-override\"><code>x = 0\n\nfor i in range(3):\n x += 1\n</code></pre>\n<h2><code>str.startswith</code></h2>\n<p>For the most part, you can use <code>str.startswith</code> to check if the suffix starts with the prefix (other than the case where prefix is <code>''</code>):</p>\n<pre class=\"lang-py prettyprint-override\"><code>prefix, suffix = 'a', 'abc'\n\nsuffix.startswith(prefix)\nTrue\n</code></pre>\n<p>This is a bit more idiomatic than slicing from position <code>i</code> or <code>j</code> to compare with a prefix</p>\n<h2>Creating your prefix and suffix</h2>\n<p>When generating your prefix and suffix, slice once, and you can keep your code down to one loop:</p>\n<pre class=\"lang-py prettyprint-override\"><code>for i in range(len(l)):\n # Generate your prefix and suffix here\n prefix, suffix = l[:i], l[i:]\n\n # rest of code\n</code></pre>\n<h2>Instead of a counter, use an if statement</h2>\n<p>For actually tabulating your results, you can use an if statement, paired with the <code>str.startswith</code> logic to cut down on your second loop.</p>\n<p>Furthermore, it appears from the example that if the prefix is an empty string, you append the length of the suffix. This can go in the <code>if str.startswith</code> bit because <code>'anystr'.startswith('')</code> will return <code>True</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>results = []\n\n# Start your loop\nfor i in range(len(mystring)):\n # Create your prefix and suffix based on slice point\n prefix, suffix = mystring[:i], mystring[i:]\n\n # check str.startswith here\n if suffix.startswith(prefix):\n # You can use a ternary if block in the append to cover the\n # empty string case\n results.append(len(prefix) if prefix else len(suffix))\n else:\n results.append(0)\n</code></pre>\n<p>The ternary operator will result in either the left side if the predicate is truthy, otherwise the right side</p>\n<pre class=\"lang-py prettyprint-override\"><code>x = 'a' if True else 'b'\n\nx\n'a'\n\nx = 'a' if False else 'b'\nx\n'b'\n\nx = 'a' if '' else 'b'\n\nx\n'b'\n</code></pre>\n<p>Empty strings are falsey.</p>\n<h1>Style</h1>\n<h2>Naming Conventions</h2>\n<p>Method names should be <code>snake_case</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def some_method_name():\n # do things\n</code></pre>\n<h2>Spacing</h2>\n<p>There should be a space between a name, the equals sign, and a value:</p>\n<pre class=\"lang-py prettyprint-override\"><code># instead of this\nsome_value=3\n\n# do this\nsome_value = 3\n</code></pre>\n<p>The exception to this is with keyword arguments in a function</p>\n<pre class=\"lang-py prettyprint-override\"><code>def f(key='value'):\n return None\n\n# No extra spaces here\nf(key=1)\n</code></pre>\n<h2>Be careful about name shadowing</h2>\n<p><code>string</code> is the name of a module, so watch out for cases where you might acidentally name a variable something that you may import (or users of your code might import). Not a huge deal in this case, but certainly something to watch out for. Note that this accounts mostly for common modules and functions, both built-in and 3rd party like <code>string</code>, <code>pandas</code>, <code>math</code>, <code>sum</code>, etc.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T18:20:44.163",
"Id": "252547",
"ParentId": "252526",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T14:28:04.683",
"Id": "252526",
"Score": "0",
"Tags": [
"python",
"performance",
"programming-challenge"
],
"Title": "Finding a common prefix"
}
|
252526
|
<p>I would appreciate some feedback on this single price grid component project completed using HTML and CSS.</p>
<p>I am trying to recreate the content shown by this image: <a href="https://res.cloudinary.com/practicaldev/image/fetch/s--FzGw2rbZ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/3y0bhisv135j7979dk3m.jpg" rel="nofollow noreferrer">https://res.cloudinary.com/practicaldev/image/fetch/s--FzGw2rbZ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/3y0bhisv135j7979dk3m.jpg</a></p>
<p>HTML file</p>
<pre><code><html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>Price Grid</title>
</head>
<body>
<div class="container">
<div class="description">
<h2>Join our community</h2>
<h3>30-day, hassle-free money back guarantee</h3>
<h3>Gain access to our full library of tutorials along with expert code reviews.
<br>Perfect for any developers who are serious about honing their skills.
</h3>
</div>
<div class="pricing">
<h3>Monthly Subscription</h3>
<h2>$29 per month</h2>
<h2>Full access for less than $1 a day</h2>
<button>Sign up</button>
</div>
<div class="featuredContent">
<h2>Why us?</h2>
<ul>
<li>Tutorials by industry experts</li>
<li>Peer & expert code review</li>
<li>Coding exercises</li>
<li>Access to our GitHub repos</li>
<li>Community forum</li>
<li>Flashcard decks</li>
<li>New videos every week</li>
</ul>
</div>
</div>
</body>
</html>
</code></pre>
<p>CSS File</p>
<pre><code>html {
margin: 0;
padding: 0;
font-family: 'Abel', sans-serif;
}
body {
background-color: rgb(230, 230, 230);
}
.container {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
width: 800px;
height: 500px;
border: 20px solid rgb(20, 148, 20);
border-radius: 25px;
}
.description {
padding: 20px;
text-align: left;
background-color: rgb(255, 255, 255);
}
.pricing {
position: relative;
float: left;
top: 5.5%;
height: 55%;
width: 50%;
color: white;
background-color: rgb(43, 179, 177);
text-align: center;
}
.featuredContent {
position: relative;
float: right;
top: 5.45%;
color: rgb(255, 255, 255);
background-color: rgb(74, 190, 189);
height: 55%;
width: 50%;
}
.featuredContent h2 {
text-align: center;
}
.featuredContent ul {
position: relative;
list-style: none;
left: 20%;
}
</code></pre>
|
[] |
[
{
"body": "<h1>HTML</h1>\n<p>Several elements are marked up as headlines, although they certainly aren't ones:</p>\n<ul>\n<li><p>The text "Gain access..." in the description element should be two(!) paragraphs. (Don't use <code><br></code> to create paragraph-like line breaks.)</p>\n<pre><code><p>Gain access to our full library of tutorials along with expert code reviews.</p>\n<p>Perfect for any developers who are serious about honing their skills.</p> \n</code></pre>\n</li>\n<li><p>"$29 per month" and "Full access..." in pricing shouldn't be headlines either - especially not <code>h2</code>s after a <code>h3</code>. Also the price ("$29") itself needs to be markuped separately, since it's highlighted compared to the rest of the line. For example:</p>\n<pre><code><div class="price"><strong>$29</strong> per month</div>\n<p>Full access for less than $1 a day</p>\n</code></pre>\n</li>\n<li><p>"Why us?" looks identical and is structurally identical to the headline "Monthly Subscription" in pricing, so it should have the same headline level.</p>\n</li>\n</ul>\n<p>The "button" "Sign up" functionally looks more like a link, than a <code><button></code>. (Buttons are primarily used to submit forms, which this is not.)</p>\n<p>The class names are too generic and so can collide with other classes used on the site. Instead of <code>container</code> something like <code>price-component</code> would be more appropriate. And for the inner components either use a child/descendant selector in the CSS so that the rules only apply to your component:</p>\n<pre><code>.price-component > .description\n</code></pre>\n<p>Or use a CSS naming scheme (such as BEM) to create a unique class names for the inner components such as <code>price-component__description</code>.</p>\n<h1>CSS</h1>\n<p>Avoid absolute positioning. Centering the price component like that is only appropriate, if it's only used as a modal dialog, that covers the rest of the content of the page and the screen shot doesn't seem to indicate that. In order to "just" center it, use CSS grid or flex.</p>\n<p>Also the use of relative positioning isn't appropriate. On those floats it is strange. It just creates a gap where there shouldn't be one and lets the elements overlap the bottom border. And on the list use either a left-margin or just a general padding on the featuredContent element.</p>\n<p>Float is not appropriate for layout any more. This component is the perfect example for a grid layout.</p>\n<p>Hard coding the width and height in pixels makes the component unresponsive to the screen and font size. For the max-width use relative units such as <code>rem</code> and don't set the height at all, letting it resize dynamically based on the content size. Also consider an alternative media query based layout for smaller screen sizes where it would be too wide.</p>\n<p>Don't center all the text. For one, it contradicts the screen shot, but more importantly centered text is difficult to read.</p>\n<p>Example: <a href=\"https://jsfiddle.net/vjr2ogpq/\" rel=\"nofollow noreferrer\">https://jsfiddle.net/vjr2ogpq/</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T16:05:14.400",
"Id": "497759",
"Score": "0",
"body": "Thanks so much and such a beautiful design you've made."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T13:57:35.580",
"Id": "252592",
"ParentId": "252529",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "252592",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T15:11:45.140",
"Id": "252529",
"Score": "2",
"Tags": [
"html",
"css"
],
"Title": "Single price grid component (HTML & CSS Project)"
}
|
252529
|
<p>I'm learning C# and after watching the course and get the basics I decided to write a small project. It's a guessing game where a player can:</p>
<ol>
<li>guess (of course): that will subtract his/her energy rest: that will</li>
<li>recovery his/her energy but take out some time take a hint: get a</li>
<li>hint about the current puzzle but it takes out some time dice roll:</li>
<li>get random a positive or a negative effect
It does all the tasks it has to do, it's all about code review. I will be grateful for all suggestions for optimization of solutions/other solutions, good practices (writing, commenting on the code) and everything else that you think may help me in the future.</li>
</ol>
<p>PS: As I wrote above, it's my first C# project. Before, I wrote some simple and small projects in other technologies/languages.</p>
<p>It contains: Main program, Hero class, Puzzle class</p>
<p><strong>Main program</strong></p>
<pre><code>using System;
namespace GuessingGame
{
class Program
{
static void Main(string[] args)
{
Start();
}
static void Start()
{
bool playerAreDumb = true;
while (playerAreDumb == true)
{
Console.WriteLine("");
Console.WriteLine("================================================");
Console.WriteLine("Hello in Guessing Game");
Console.WriteLine("Type \"s\" to start a new game");
Console.WriteLine("");
Console.Write("What do you want to do: ");
string playerInput = Console.ReadLine();
switch (playerInput)
{
case "s":
playerAreDumb = false;
StartNewGame();
break;
default:
Console.WriteLine("Well yea... try again ok?");
Console.WriteLine("...");
Console.WriteLine("...");
Console.WriteLine("...");
break;
}
}
}
static void StartNewGame()
{
// Introduction
Console.WriteLine("You started a new game");
Console.WriteLine("...");
Console.WriteLine("...");
Console.WriteLine("...");
Console.WriteLine("Hello Hero! You forgot to wear your plot armor and some random snake bites you. You will die in 24 hours.");
Console.WriteLine("Yea well that's all. Good luck!");
bool gameOver = false;
while (gameOver == false)
{
/*Game loop
In the beginning, the player will see hero condition, then I'll show all of the activities that he/she can do.
Depending on his/her input I'll start the method. On the end I'll check if he/she is still alive. If yes another loop will happen */
Console.WriteLine("");
Console.WriteLine("================================================");
CheckHeroCondition();
Console.WriteLine("Type \"s\" to try to solve the puzzle");
Console.WriteLine("Type \"r\" to rest");
Console.WriteLine("Type \"h\" to get a hint");
Console.WriteLine("Type \"l\" to try your luck");
Console.WriteLine("");
Console.Write("What do you want to do: ");
string playerInput = Console.ReadLine();
switch (playerInput)
{
case "s":
TryToSolvePuzzle();
break;
case "r":
Rest();
break;
case "h":
GetHint();
break;
case "l":
DiceRoll();
break;
default:
Console.WriteLine("Well yea... try again ok?");
break;
}
// Everytime when energy or timeLeft is changed, Hero.alive can change. If that happens, the game is over and player loses
if (Hero.Alive == false) { gameOver = true; }
// If player solves a puzzle, whichPuzzle is incremented. If WhichPuzzle returns 4 it means that the player solved all of the puzzles
if (Puzzle.WhichPuzzle == 4) { gameOver = true; }
Console.ReadLine();
}
}
static void CheckHeroCondition()
{
int heroEnergy = Hero.Energy;
int heroTimeLeft = Hero.TimeLeft;
int[] heroStatuesCounters = Hero.StatusesCounters;
string messageFirstLine; // line for energy and timeLeft
string messageSecondLine = ""; // line for statues counters
messageFirstLine = "Hero energy: " + heroEnergy + "%, Hero time left: " + heroTimeLeft + " hours";
string statusMessagePart = "";
/* I'll skip i=0 because the first status counter is for AHA Moment and I use this counter only to
determine what I should do if AHA Moment happens again in DiceRoll */
// heroStatuesCounters.Length-1 -> I'll use i to go through the entire array. The returned length will be greater than the last index
for (int i = 1; i <= heroStatuesCounters.Length - 1; i++)
{
/* messageSecondLine should look like e.g. "Motivation (2), Dizzines (4)"
first I need to check if a status is active (counter is not equal to 0), than write down the name of the status and add its counter*/
if (heroStatuesCounters[i] != 0)
{
switch (i)
{
case 1:
statusMessagePart = "Motivation";
break;
case 2:
statusMessagePart = "Narcolepsy";
break;
case 3:
statusMessagePart = "Effective antidote";
break;
case 4:
statusMessagePart = "Slow moves";
break;
case 5:
statusMessagePart = "Dizziness";
break;
case 6:
statusMessagePart = "Exhaustion";
break;
case 7:
statusMessagePart = "Student syndrome";
break;
}
// I'll need to remove the comma after the last status
messageSecondLine = messageSecondLine + statusMessagePart + " (" + heroStatuesCounters[i] + "), ";
}
}
Console.WriteLine(messageFirstLine);
// removing comma on the end of the message and showing second line of message (if variable is "" there are no active effects)
if (messageSecondLine != "")
{
messageSecondLine = messageSecondLine.Substring(0, messageSecondLine.Length - 2); // -2 -> because I need to remove: ", "
Console.WriteLine(messageSecondLine);
}
}
static void TryToSolvePuzzle()
{
/* Statues that may effect that action
Motivation - extra energy after guessing the puzzle
Effective antidote - more time after guessing the puzzle
Dizziness - failed guessing may return a modified result of valid chars */
int[] statusesCounters = Hero.StatusesCounters;
Console.Write("Your guess: ");
string playerGuess = Console.ReadLine();
/* Puzzle.CheckPlayerGuess returns counter of valid chars in player's guess.
If method returns >= 0 it means that the player's guess is not the correct answer.
If method returns -1 it means that the player has given the correct answer. */
int validCharsCounter;
validCharsCounter = Puzzle.CheckPlayerGuess(playerGuess);
if (validCharsCounter == -1)
{
PlayerSolvedPuzzle();
}
else
{
Random rnd = new Random();
// Dizziness - failed guessing may return a modified result of valid chars
// Dizziness counter is the sixth one
if (statusesCounters[5] != 0)
{
// 1+1 -> Random.Next excludes maxValue (2 argument)
int counterChange = rnd.Next(-1, 1 + 1); // number that will determine if and how the counter will be modified
validCharsCounter = validCharsCounter + counterChange;
// if validCharsCounter was equal to 0 before being modified, after modifying it may be equal to -1
if (validCharsCounter == -1) { validCharsCounter = 0; }
}
Console.WriteLine("It's not the correct answer. In your guess " + validCharsCounter + " chars were on the right place");
// subtracting energy
// -20+1 -> Random.Next excludes maxValue (2 argument)
int lostEnergy = rnd.Next(-30, -20 + 1); // the amount of energy that the player will lose after that guess
string messageLostEnergy = Convert.ToString(lostEnergy); // e.g. -25
messageLostEnergy = messageLostEnergy.Substring(1); // I'll cut the "-"
Console.WriteLine("You lost " + messageLostEnergy + "% energy after that guess");
Hero.ChangeEnergy(lostEnergy);
}
// statuses counters change
// Motivation counter is the second one
if (statusesCounters[1] != 0) { statusesCounters[1]--; }
// Effective antidote counter is the fourth one
if (statusesCounters[3] != 0) { statusesCounters[3]--; }
// Dizziness counter is the sixth one
if (statusesCounters[5] != 0) { statusesCounters[5]--; }
}
static void PlayerSolvedPuzzle()
{
/*if player solves a puzzle, whichPuzzle is incremented.
If WhichPuzzle returns 4 it means that the player has solved all of the puzzles */
if (Puzzle.WhichPuzzle != 4)
{
Console.WriteLine("Congratulation! You solved the puzzle!");
Hero.PlayerSolvedPuzzle();
}
else
{
Console.WriteLine("Congratulation! You solved all of the puzzles!");
Console.WriteLine("");
Console.WriteLine("For that achievement, the medic in your village has finally let you out from his basement and healed you.");
Console.ReadLine();
Console.WriteLine("I think you should report him somewhere...");
Console.ReadLine();
Console.WriteLine("Anyway good job :3 I hope that you enjoyed it");
}
}
static void Rest()
{
/* Statues that may effect that action
Narcolepsy - chance that rest will not give you energy */
/* While resting, the player can recover between 30 and 50 energy but he/she will lose 2 or 3 hours.
In addition, he/she has a 1% chance to sleep for 8 hours -> this may happen only if the player has more than 8 hours left
First, I'll check if he/she has more than 8 hours left. If yes, I'll check if long nap will happen.
If no, I'll check amount of hours that player will lose. After that, I'll check the amount of energy that the player will recover*/
int[] statusesCounters = Hero.StatusesCounters;
Random rnd = new Random();
int chance;
// 2+1 -> Random.Next excludes maxValue (2 argument)
chance = rnd.Next(1, 2 + 1); // chance == 1 -> player will not restore energy
//Narcolepsy counter is the third one
if (chance == 1 && statusesCounters[2] != 0) // chance needs to be equal to 1 and Narcolepsy needs to be active
{
Console.Write("Because of narcolepsy you don't feel better after trying to rest.");
}
else
{
// adding energy
if (Hero.Energy >= 100)
{
Console.Write("Well you're already full of the energy.");
}
else
{
int recoveredEnergy;
// Exhaustion - resting will give only half energy
// Exhaustion counter is the seventh one
if (statusesCounters[6] != 0)
{
// 25+1 -> Random.Next excludes maxValue (2 argument)
recoveredEnergy = rnd.Next(15, 25 + 1); // the amount of energy that the player will recover after that rest
}
else
{
// 50+1 -> Random.Next excludes maxValue (2 argument)
recoveredEnergy = rnd.Next(30, 50 + 1); // the amount of energy that the player will recover after that rest
}
// checking to see if the player should get more energy than possible (energy > 100 after Hero.ChangeEnergy)
int energy = Hero.Energy;
if (energy + recoveredEnergy > 100)
{
// e.g. the hero has 90 energy and recoveredEnergy = 20 -> 90 + 20 = 110 > 100
recoveredEnergy = 100 - energy; // e.g. -> recoveredEnergy = 100 - 90 = 10
}
Hero.ChangeEnergy(recoveredEnergy);
Console.Write("You have rested and you restored " + recoveredEnergy + "% of the energy!");
}
}
// substract time
// 100+1 -> Random.Next excludes maxValue (2 argument)
chance = rnd.Next(1, 100 + 1); // chance == 1 -> long nap
if (Hero.TimeLeft > 8 && chance == 1) // may happen only if the player has more than 8 hours and chance will be equal to 1
{
Hero.ChangeTimeLeft(-8);
Console.Write(" But you fell asleep and slept for 8 hours. " +
"After that \"long nap\" you're not even sure in which solar system you're.");
}
else
{
int timeCost;
// Student syndrome - resting and taking a hint will take the maximum possible amount of time
// Student syndrome counter is the eighth one
if (statusesCounters[7] != 0)
{
timeCost = -3;
}
else
{
// -2+1 -> Random.Next excludes maxValue (2 argument)
timeCost = rnd.Next(-3, -2 + 1); // number that will determine how much time will this action cost
}
// Slow moves - resting and taking a hint will take more time
// Slow moves counter is the fifth one
if (statusesCounters[4] != 0)
{
// -1+1 -> Random.Next excludes maxValue (2 argument)
int extraTimeCost = rnd.Next(-3, -1 + 1);
timeCost = timeCost + extraTimeCost;
}
string messageTimeCost = Convert.ToString(timeCost); // e.g. -2
messageTimeCost = messageTimeCost.Substring(1); // I'll cut the "-"
Console.WriteLine(" But it costed you " + messageTimeCost + " hours.");
Hero.ChangeTimeLeft(timeCost);
}
// statuses counters change
//Narcolepsy counter is the third one
if (statusesCounters[2] != 0) { statusesCounters[2]--; }
// Slow moves counter is the fifth one
if (statusesCounters[4] != 0) { statusesCounters[4]--; }
// Exhaustion counter is the seventh one
if (statusesCounters[6] != 0) { statusesCounters[6]--; }
// Student syndrome counter is the eighth one
if (statusesCounters[7] != 0) { statusesCounters[7]--; }
}
static void GetHint()
{
/* Statues that may effect that action
Slow moves - rest and taking hint will take more time */
/* Player can get up to 3 hints. In addition, he/she has a 10 % chance to get a secret hint.
First, I'll check if he/she will get the secret hint or the usual hint. After, that he/she will lose some time.
At the end, I'll check if he/she didn't already get all of the hints. */
int[] statusesCounters = Hero.StatusesCounters;
string hint = "";
Random rnd = new Random();
// 10+1 -> Random.Next excludes maxValue (2 argument)
int chance = rnd.Next(1, 10 + 1); // chance == 1 -> secret hint
if (chance == 1)
{
hint = Puzzle.GiveSecretHint();
}
else
{
hint = Puzzle.GiveHint();
}
// checking if he/she didn't already get all of the hints.
if (hint != "You already know everything that you need! Take a nap or something.")
{
Console.WriteLine(hint);
int timeCost;
// Student syndrome - resting and taking hint will take the maximum possible amount of time
// Student syndrome counter is the eighth one
if (statusesCounters[7] != 0)
{
timeCost = -4;
}
else
{
// -2+1 -> Random.Next excludes maxValue (2 argument)
timeCost = rnd.Next(-4, -1 + 1); // number that will determine how much time will this action cost
}
// Slow moves - resting and taking a hint will take more time
// Slow moves counter is the fifth one
if (statusesCounters[4] != 0)
{
// -1+1 -> Random.Next excludes maxValue (2 argument)
int extraTimeCost = rnd.Next(-3, -1 + 1);
timeCost = timeCost + extraTimeCost;
}
string messageTimeCost = Convert.ToString(timeCost); // e.g. -2
messageTimeCost = messageTimeCost.Substring(1); // I'll cut the "-"
Console.WriteLine("That action costed you " + messageTimeCost + " hours.");
Hero.ChangeTimeLeft(timeCost);
}
else
{
Console.WriteLine(hint);
Rest();
}
// statuses counters change
// Slow moves counter is the fifth one
if (statusesCounters[4] != 0) { statusesCounters[4]--; }
}
static void DiceRoll()
{
Random rnd = new Random();
//6+1 -> Random.Next excludes maxValue (2 argument)
int dice = rnd.Next(1, 6 + 1);
switch (dice)
{
case 1:
/* AHA Moment: The player will get a hint about answer's length.
If the player already got this hint once he/she, will get the exact length */
// correctCounter1 -> 1 because it's the first case
int correctCounter1 = 0; // AHA Moment counter it's the first one
int ahaMomentCounter = Hero.StatusesCounters[correctCounter1];
if (ahaMomentCounter == 0)
{
/*I need a number between the puzzle answer length -2 and the puzzle answer length
for example, if the answer is 5 chars long, then hint may be: (3,5), (4,6), (5,7)*/
int answerLength = Puzzle.GiveAnswerLength();
int substractedAnswerLength = answerLength - 2;
// if the answer has only 3 or 4 chars I don't want to show hint: 1-3 or 2-4
if (substractedAnswerLength < 3) { substractedAnswerLength = 3; }
// answerLength + 1 -> Random.Next excludes maxValue (2 argument)
int setBeginning = rnd.Next(substractedAnswerLength, answerLength + 1);
int setEnd = setBeginning + 2;
Console.WriteLine("AHA Moment: The answer for the current puzzle has between " + setBeginning + " and " + setEnd + " chars");
Hero.ChangeStatusesCounters(correctCounter1, 1);
}
else if (ahaMomentCounter == 1)
{
int answerLength = Puzzle.GiveAnswerLength();
Console.WriteLine("AHA Moment: The answer for the current puzzle has " + answerLength + " chars");
Hero.ChangeStatusesCounters(correctCounter1, 1);
}
else
{
Console.WriteLine("Really? 1 on a dice roll this many times?");
Console.ReadLine();
Console.WriteLine("Okay... I'll give you one more hour for that");
if (Hero.TimeLeft < 24)
{
Hero.ChangeTimeLeft(1);
}
else
{
Console.WriteLine("OHH FOR FUCK'S SAKE! Seriously you already have the maximum amount of time left...");
Console.ReadLine();
Console.WriteLine("You know what...");
Console.ReadLine();
Console.WriteLine("You die: A pebble fell on your head and killed you");
Console.ReadLine();
Console.WriteLine("...");
Console.WriteLine("...");
Console.WriteLine("...");
Console.ReadLine();
Console.WriteLine(":c");
Console.ReadLine();
Console.WriteLine("Nah, just joking. Keep playing :3");
}
}
break;
case 2:
/*Refreshment: The player will get 100 energy. If he/she already has 100 energy a positive or a negative effect will happen:
Motivation - if the player will solve a puzzle in the next few guesses he/she will have more energy at the beginning of the next puzzle
Narcolepsy - the chance that resting will not give the player energy*/
if (Hero.Energy < 100)
{
Hero.ChangeEnergy(100); // I can only add/substract energy so now I'm sure that the player will have 100 energy
Console.WriteLine("Refreshment: You're full of energy!");
}
else // hero has 100 energy or more, so I'll check if Motivation or Narcolepsy happens
{
// 2+1 -> Random.Next excludes maxValue (2 argument)
int refreshmentChance = rnd.Next(1, 2 + 1);
if (refreshmentChance == 1) // refreshmentChance == 1 -> Motivation
{
// Currently I have 4 puzzles (0-3). If the current puzzle is the last one, this status will not give the player anything
if (Puzzle.WhichPuzzle == 3)
{
Console.WriteLine("You should get a bonus for the the next puzzle but it's the last one," +
" so the only thing that I can do is wishing you luck!");
}
else
{
// correctCounter2 -> 2 because it's the second case
int correctCounter2 = 1; // Motivation counter is the second one
Hero.ChangeStatusesCounters(correctCounter2, 2);
int motivationCounter = Hero.StatusesCounters[correctCounter2];
if (motivationCounter == 1)
{
Console.WriteLine("Motivation: If you will solve the puzzle in the next" +
" attempt you will get 150% energy at the beginning of the next puzzle.");
}
else
{
Console.WriteLine("Motivation: If you will solve the puzzle in the next " + motivationCounter +
" attempts you will get 150% energy at the beginning of the next puzzle.");
}
}
}
else // refreshmentChance == 2 -> Narcolepsy
{
// correctCounter2 -> 2 because it's the second case
int correctCounter2 = 2; //Narcolepsy counter is the third one
Hero.ChangeStatusesCounters(correctCounter2, 1);
int narcolepsyCounter = Hero.StatusesCounters[correctCounter2];
if (narcolepsyCounter == 1)
{
Console.WriteLine("Narcolepsy: Within the next rest there is a 50% chance that you will not get any energy.");
}
else
{
Console.WriteLine("Narcolepsy: Within the next " + narcolepsyCounter +
" rests its a 50% chance that you will not get any energy.");
}
}
}
break;
case 3:
/*Immune reaction: The player will get 24 hours. If he/she already has 24 hours, a positive or a negative effect will happen:
Effective antidote - if the player will solve a puzzle in the next few guesses he/she will have more time at the beginning of the next puzzle
Slow moves - resting and taking a hint will take more time*/
if (Hero.TimeLeft < 24)
{
Hero.ChangeTimeLeft(24); // I can only add/substract energy so now I'm sure that the player will have 24 hours left
Console.WriteLine("Immune reaction: You have 24 hours left again!");
}
else // hero has 24 hours or more so I'll check if Effective antidote or Slow moves happens
{
// 2+1 -> Random.Next excludes maxValue (2 argument)
int immuneReactionChance = rnd.Next(1, 2 + 1);
if (immuneReactionChance == 1) // immuneReactionChance == 1 -> Effective antidote
{
// Currently I have 4 puzzles (0-3). If the current puzzle is the last one this status will not give the player anything
if (Puzzle.WhichPuzzle == 3)
{
Console.WriteLine("You should get a bonus for the next puzzle, but it's the last one," +
" so the only thing that I can do is wishing you luck!");
}
else
{
// correctCounter3 -> 3 because it's the third case
int correctCounter3 = 3; // Effective antidote counter is the fourth one
Hero.ChangeStatusesCounters(correctCounter3, 2);
int effectiveAntidoteCounter = Hero.StatusesCounters[correctCounter3];
if (effectiveAntidoteCounter == 1)
{
Console.WriteLine("Effective antidote: If you will solve the puzzle in the next" +
" attempt you will have 36 hours at the beginning of the next puzzle.");
}
else
{
Console.WriteLine("Effective antidote: If you will solve the puzzle in the next " + effectiveAntidoteCounter +
" attempts you will have 36 hours at the beginning of the next puzzle.");
}
}
}
else // immuneReactionChance == 2 -> Slow moves
{
// correctCounter3 -> 3 because it's the third case
int correctCounter3 = 4; // Slow moves counter is the fifth one
Hero.ChangeStatusesCounters(correctCounter3, 1);
int slowMovesCounter = Hero.StatusesCounters[correctCounter3];
if (slowMovesCounter == 1)
{
Console.WriteLine("Slow moves: Within the next resting or taking a hint you will lose bettwen 1 and 3 more hours.");
}
else
{
Console.WriteLine("Slow moves: Within the next " + slowMovesCounter +
" rests and taking hints you will lose bettwen 1 and 3 more hours.");
}
}
}
break;
case 4:
// Dizziness - failed guessing may return a modified result of valid chars
// correctCounter4 -> 4 because it's the fourth case
int correctCounter4 = 5; // Dizziness counter is the sixth one
Hero.ChangeStatusesCounters(correctCounter4, 2);
int dzizzinessCounter = Hero.StatusesCounters[correctCounter4];
if (dzizzinessCounter == 1)
{
Console.WriteLine("Dizziness: Within the next guessing, you may get a hint about valid characters, modified by -1 or +1.");
}
else
{
Console.WriteLine("Dizziness: Within the next " + dzizzinessCounter +
" guesses, you may get a hint about valid characters, modified by -1 or +1.");
}
break;
case 5:
// Exhaustion - resting will give only half energy
// correctCounter5 -> 5 because it the fifth case
int correctCounter5 = 6; // Exhaustion counter is the seventh one
Hero.ChangeStatusesCounters(correctCounter5, 2);
int exhaustionCounter = Hero.StatusesCounters[correctCounter5];
if (exhaustionCounter == 1)
{
Console.WriteLine("Exhaustion: Within the next rest, you will recover only half of the energy.");
}
else
{
Console.WriteLine("Exhaustion: Within the next " + exhaustionCounter +
" rests, you will recover only half of the energy.");
}
break;
case 6:
/* Mobile games - The player will lose 6 hours. If he/she has less than 7 hours another status will happen
Student syndrome - resting and taking a hint will take the maximum possible amount of time */
if (Hero.TimeLeft > 6)
{
Hero.ChangeTimeLeft(-6);
Console.WriteLine("You played on your phone and lost 6 hours,");
Console.ReadLine();
Console.WriteLine("You have also run out of battery so you cannot use it now,");
Console.ReadLine();
Console.WriteLine("Seriously, you could use it in many other good ways,");
Console.ReadLine();
Console.WriteLine("In the future, perhaps you should think twice before you do something like this.");
}
else
{
// correctCounter6 -> 6 because it's the sixth case
int correctCounter6 = 7; // Student syndrome counter is the eighth one
Hero.ChangeStatusesCounters(correctCounter6, 2);
int studentSyndromeCounter = Hero.StatusesCounters[correctCounter6];
if (studentSyndromeCounter == 1)
{
Console.WriteLine("Student syndrome: The next rest or taking a hint will take the maximum possible amount of time.");
}
else
{
Console.WriteLine("Student syndrome: The next " + studentSyndromeCounter +
" rests and taking hints will take the maximum possible amount of time.");
}
}
break;
}
}
}
}
</code></pre>
<p><strong>Hero Class</strong></p>
<pre><code>using System;
namespace GuessingGame
{
static class Hero
{
private static int energy = 100; // hero have 100% energy at the beginning
private static int timeLeft = 24; // hero have 24h time left at the beginning
private static int[] statusesCounters = // hero doesn't have any active status at the beginning
{
0, // AHA Moment - Player will get hint about answer's length
0, // Motivation - extra energy after guessing the puzzle
0, // Narcolepsy - chance that rest will not give you energy
0, // Effective antidote - more time after guessing the puzzle
0, // Slow moves - resting and taking hint will take more time
0, // Dizziness - failed guessing may return a modified result of valid chars
0, // Exhaustion - resting will give only half energy
0 // Student syndrome - resting and taking hint will take the maximum possible amount of time
};
private static bool alive = true; // the flag that changes if the player loses
public static void ChangeTimeLeft(int timeChangeAmount)
{
timeLeft = timeLeft + timeChangeAmount;
if (timeLeft >= 24) { timeLeft = 24; } //hero should not have more than 24 hours except for Effective antidote status
if (timeLeft <= 0) { HeroDie("time"); }
}
public static void ChangeEnergy(int energyChangAmount)
{
energy = energy + energyChangAmount;
if (energy >= 100) { energy = 100; } //hero should not have more than 100 energy except for Motivation status
if (energy <= 0) { HeroDie("energy"); }
}
public static void ChangeStatusesCounters(int whichStatus, int counterChangeAmount)
{
try
{
/* Question: can I block the passing of some parameters in the method? Just as the compiler will show an error
if it tries to enter int into a parameter that should be a string, is it possible to block the passing of an argument
of the appropriate type, but, for example, greater than X?*/
statusesCounters[whichStatus] = statusesCounters[whichStatus] + counterChangeAmount;
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine("WTF Hero.ChangeStatusesCounters: " + e.Message);
}
}
public static void HeroDie(string reason)
{
alive = false;
if (reason == "time")
{
Console.WriteLine("You die: The venom killed you :c");
}
else if (reason == "energy")
{
Console.WriteLine("You die: You died of exhaustion :c");
}
else
{
Console.WriteLine("Amm... to be honest I don't know why you're here");
Console.WriteLine("Hmm... OK");
Console.ReadLine();
Console.WriteLine("You die: A pebble fell on your head and it killed you");
Console.ReadLine();
Console.WriteLine("...");
Console.WriteLine("...");
Console.WriteLine("...");
Console.ReadLine();
Console.WriteLine(":c");
}
}
public static void PlayerSolvedPuzzle()
{
/* after solving a puzzle the player will not get extra energy (unless motivation status is active),
but he/she will get more time*/
if (statusesCounters[1] != 0) // second counter is Motivation counter
{
energy = 150;
Console.WriteLine("After that success, you feel full of energy! You have 150% energy now.");
}
Console.WriteLine("After solving that puzzle, an antidote appears in the room where you are. " +
"It temporarily helps your body to fight the venom.");
if (statusesCounters[3] != 0) // fourth counter is Effective antidote counter
{
timeLeft = 36;
Console.WriteLine("That antidote was really effective. You have 36 hours instead of 24 hours to solve the next puzzle!");
} else
{
if (TimeLeft < 24)
{
timeLeft = 24;
Console.WriteLine("You have 24 hours to solve the next puzzle");
}
}
// AHA Moment counter needs to be reset so player can get this again for the next puzzle
statusesCounters[0] = 0;
}
public static int Energy
{
get { return energy; }
}
public static int TimeLeft
{
get { return timeLeft; }
}
public static int[] StatusesCounters
{
get { return statusesCounters; }
}
public static bool Alive
{
get { return alive; }
}
}
}
</code></pre>
<p><strong>Puzzle Class</strong></p>
<pre><code>using System;
namespace GuessingGame
{
static class Puzzle
{
private static string[] answers = { "egg", "sleeping", "cat", "addiction"};
private static string[] secretHints =
{"Have you had breakfast today?",
"Although many would like to hug Keanu Reeves, this puzzle is about hugging his friend handing out pills to people.",
"Let's face it, Jerry was the bad guy.",
"How often did your mom tell you that playing games are unhealthy for you?" };
private static string[,] hints = {
{"You need to break it before you can use it.", // hints for first puzzle
"A container without hinges, lock or a key, yet a golden treasure lies inside.",
"It is not unusual and yet philosophers were fascinated with the chronological relationship between this and its creator." },
{"If someone asks you if you are doing this at this moment, you cannot answer truthfully.", // hints for second puzzle
"It seems to shorten your life. However, if you gave it up, you would really shorten your life.",
"You do it every day, but you never see yourself doing it."},
{"You wanted to get rid of rodents, and now you get them as gifts.", // hints for third puzzle
"Most people love it or hate it - rarely something in the middle.",
"Why do you need an owl or a toad when you can have it?"},
{"Pavlov could call it conditioning, but many will call it a different way.", // hints for fourth puzzle
"It always starts innocently and often also enjoyable.",
"Habits are good, unless you become their slave."} };
private static int whichPuzzle = 0; // which puzzle is currently being solved
private static int whichHint = 0; // which hint WILL be given
public static string GiveHint()
{
/*If the player is given the same hint, he/she gets nothing -> After the last hint, instead of getting another one,
the player will rest*/
if (whichHint <= 2)
{
whichHint++;
if (whichHint == 3) // Player will get now the third and the last hint, so he/she should know that the next one will not be given
{
Console.WriteLine("It's the last hint. You'll not get another one!");
}
// 'whichHint - 1' because I need to increment the counter before return
return "Your hint: " + hints[whichPuzzle, whichHint - 1];
} else
{
return "You already know everything that you need! Take a nap or something.";
}
}
public static string GiveSecretHint()
{
/*If the player is given the secret hint again, he/she gets nothing -> After getting it once, it will be replaced with an empty
string and the usual hint will be given when the secret hint is drawn again*/
if (secretHints[whichPuzzle] != "")
{ // first time
string secretHint = "Wild secret hint appeared :O " + secretHints[whichPuzzle];
secretHints[whichPuzzle] = "";
return secretHint;
} else
{ // not first time
return GiveHint();
}
}
public static int CheckPlayerGuess(string playerGuess)
{
/* first method checks if playerGuess is the correct answer
yes -> player solved the puzzle
no -> if the char on a specific position in the answer for the current puzzle, and the player's guess is the same,
validCharsCounter will be increment */
/* if method return >= 0 it means that the player's guess is not the correct answer.
* If method return -1 it means that the player has given the correct answer */
string currentAnswer = answers[whichPuzzle];
if (currentAnswer == playerGuess)
{
whichPuzzle++;
whichHint = 0;
return -1;
}
int validCharsCounter = 0;
// playerGuess.Length-1 -> I'll use i to go through the entire array. The returned length will be greater than the last index
for (int i = 0; i <= playerGuess.Length-1; i++)
{
try
{
if (currentAnswer[i] == playerGuess[i]) { validCharsCounter++; }
}
catch (IndexOutOfRangeException)
{
break;
}
}
return validCharsCounter;
}
public static int GiveAnswerLength()
{
return answers[whichPuzzle].Length;
}
public static int WhichPuzzle
{
get { return whichPuzzle; }
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T15:22:32.780",
"Id": "497620",
"Score": "3",
"body": "It may be easier for you in this way -> https://github.com/GravityCat190/Advanced-Guessing-Game"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T21:21:16.763",
"Id": "497668",
"Score": "4",
"body": "_bool playerAreDumb = true_ - never hath truer words been writ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T21:52:41.197",
"Id": "497962",
"Score": "1",
"body": "`Console.WriteLine(\"================================================\");` I rarely meet someone who knows that this line can be rewritten with pretty useful `string` constructor. Take it `Console.WriteLine(new string('=', 46));`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T22:09:18.490",
"Id": "497966",
"Score": "0",
"body": "Nice game, try the typewriter feature `private static void TypeWrite(string s) { foreach (char c in s) { Console.Write(c.ToString()); if (!Console.KeyAvailable) Thread.Sleep(50); } if (Console.KeyAvailable) Console.ReadKey(true); }`."
}
] |
[
{
"body": "<p>Welcome to C# :)</p>\n<h2>The good parts</h2>\n<ul>\n<li>In general, I like how you name your variables</li>\n<li>A lot of explanatory comments - it's good to explain why certain things are implemented the way they are. However, the necessity to write many comments points to possible improvements.</li>\n</ul>\n<h2>Possible improvements</h2>\n<h3>Encapsulate related stuff</h3>\n<p>You may notice that your methods are quite long and sometimes noisy. Also, quite some code under some of the <code>case</code> statements - e.g. <a href=\"https://github.com/GravityCat190/Advanced-Guessing-Game/blob/69265145b1d28fc6aae05fddf10797d2454c2957/GuessingGame/GuessingGame/Program.cs#L412\" rel=\"noreferrer\">Program.cs line 412</a>.</p>\n<p>You could start by identifying and grouping some chunks into separate methods, to <strong>improve readability</strong> - code is read way more often than written. For example, the user prompts:</p>\n<pre><code>Console.WriteLine("You started a new game");\nConsole.WriteLine("...");\nConsole.WriteLine("...");\nConsole.WriteLine("...");\n</code></pre>\n<p>This can be grouped into a new method <code>PromptNewGame()</code></p>\n<pre><code>// new method\nprivate void PromptNewGame()\n{\n Console.WriteLine("You started a new game");\n Console.WriteLine("...");\n Console.WriteLine("...");\n Console.WriteLine("...");\n}\n\n// use it in program.cs\n// ...\nPromptNewGame();\n// ...\n</code></pre>\n<p>As a next step, maybe you want to group all prompt-related code together in a separate class with many methods like this: <code>UserPrompts.PrintSomeInstructions()</code>. You do this already with some functionality (<code>Hero</code>, <code>Puzzle</code>), but not everywhere.</p>\n<p>In general I would move most of the methods out of the <code>Program</code> class into a new <code>Game</code> class. That class can host the whole flow of the game - <code>StartNewGame()</code>, <code>TryToSolvePuzzle()</code> etc.</p>\n<p>In <code>Program</code> you would then only call <code>Game.StartNewGame()</code>.</p>\n<p>Another example:</p>\n<pre><code>Random rnd = new Random();\n//6+1 -> Random.Next excludes maxValue (2 argument)\nint dice = rnd.Next(1, 6 + 1);\n\n// maybe put all of that into a separate method and call it like this - readability improved\nint dice = RollTheDice();\n</code></pre>\n<h3>See if you can get rid of "magic" integers and strings</h3>\n<p>You have many places like this - <code>case "s"</code>, <code>case 5:</code>, <code>statusesCounters[3]</code>, <code>Hero.Energy >= 100</code>. This makes your code less readable and can cause difficulties if you need to add/change some of these values.</p>\n<p>There are multiple techniques to avoid this:</p>\n<ul>\n<li>one of the simplest ones - capture some of those numbers into <code>const</code>s</li>\n</ul>\n<pre><code>private const int MAX_ENERGY = 100;\n\n// and use it everywhere in the code...\nif (Hero.Energy >= MAX_ENERGY) ...\n</code></pre>\n<p>Here as well, you might discover that there are related constants and they may be grouped int a separate class, e.g. <code>GameParameters</code>. This will declutter the class where the logic using those constants is implemented.</p>\n<ul>\n<li>use <code>enum</code>s</li>\n</ul>\n<p>One example could be HeroStatus (if I understand the game correctly :)):</p>\n<pre><code>public enum HeroState\n{\n Motivation,\n Narcolepsy,\n SlowMoves,\n // and others...\n}\n\n// then you can use it in a Dictionary to track `statusesCounters`:\nstatic class Hero\n {\n // other stuff... \n private static Dictionary<HeroState, int> statusesCounters = new Dictionary<HeroState, int>()\n {\n { HeroState.Motivation, 0 },\n { HeroState.Narcolepsy, 0 },\n { HeroState.SlowMoves, 0 }\n }; // P.S. This can be even automated by iterating through the enum values\n\n// then use it elsewhere without the need for extra comments\nif (statusesCounters[HeroState.Motivation] != 0)\n{\n ...\n}\n</code></pre>\n<ul>\n<li>use polymorphism (sub-classes) - this can be a bit more advanced, but feel free to google <em>"replace switch-case with polymorphism"</em></li>\n</ul>\n<h3>Misc</h3>\n<ul>\n<li>Make use of string interpolation</li>\n</ul>\n<pre><code>// this...\nConsole.WriteLine("That action costed you " + messageTimeCost + " hours.");\n\n// ... can be replaced with this\n Console.WriteLine($"That action costed you {messageTimeCost} hours."); // notice the $ sign\n</code></pre>\n<ul>\n<li>Take a look at the <code>foreach</code> statement. Often you won't need the <code>for</code> loops and the code will be easier to read</li>\n</ul>\n<p>In general you can achieve a lot by doing these small incremental refactorings. Don't take it as a strict rule, but if you see that your method or class starts becoming a long one with hundreds of lines, you may want to look at encapsulating related code into separate methods/classes.</p>\n<p>Happy coding!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T11:56:56.010",
"Id": "497733",
"Score": "0",
"body": "Thanks! I checked \"String interpolation\" and it'll be super helpful so I'll use it for sure. I'll also look more about enums and Polymorphism. \nYou have right about \"magic\" integers and strings -> the fact that I have to comment on it already shows that I should change it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T13:02:01.740",
"Id": "497737",
"Score": "1",
"body": "Great first review!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T22:34:55.483",
"Id": "498197",
"Score": "1",
"body": "@GravityCat if you're fine with the review, you may mark the answer as accepted."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T11:18:51.003",
"Id": "252584",
"ParentId": "252530",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "252584",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T15:13:26.413",
"Id": "252530",
"Score": "9",
"Tags": [
"c#",
"beginner"
],
"Title": "C# Advanced guessing game"
}
|
252530
|
<p>I have this code that:</p>
<ol>
<li>Clears my worksheet from row 12 and onward in Workbook A</li>
<li>Opens a new file Workbook B</li>
<li>Copys the sheet to my Workbook A. and Close Workbook B</li>
<li>Renames sheet in Workbook A</li>
<li>Transfers data from New Sheet to another Tab.</li>
</ol>
<p>This seems to take me 10 minutes+, it is roughly 35k Rows.</p>
<p>Is there a faster way of doing this?</p>
<p>Thanks.</p>
<pre><code> Sub Mainsub()
Worksheets("Main Data").Rows("12:" & Rows.Count).ClearContents
'Copy data from the CM File to Template
Application.ScreenUpdating = False
'Open CM file
Set MainDataCM = Workbooks.Open(Sheets("Input").Range("B16") & Sheets("Input").Range("B19"))
'Copy main data tab to EPM file workbook
MainDataCM.Sheets("Main Data").Copy After:=ThisWorkbook.Sheets(1)
'Close CM Comm file
MainDataCM.Close SaveChanges:=False
Application.ScreenUpdating = True
Sheets("Main Data (2)").Name = "CM_MainData"
Worksheets("CM_MainData").Visible = False
'Read the CM_MainData tab and copy the required columns in the MainData tab
Dim k As Long
k = Sheets("CM_MainData").Range("A1", Sheets("CM_MainData").Range("A1").End(xlDown)).Rows.Count
Debug.Print (k)
i = 12
j = 2
While j <= k
Sheets("Main Data").Range("A" & i) = Sheets("CM_MainData").Range("A" & j)
Sheets("Main Data").Range("B" & i) = Sheets("CM_MainData").Range("B" & j)
Sheets("Main Data").Range("C" & i) = Sheets("CM_MainData").Range("C" & j)
Sheets("Main Data").Range("D" & i) = Sheets("CM_MainData").Range("D" & j)
Sheets("Main Data").Range("E" & i) = Sheets("CM_MainData").Range("E" & j)
Sheets("Main Data").Range("F" & i) = Sheets("CM_MainData").Range("F" & j)
Sheets("Main Data").Range("G" & i) = Sheets("CM_MainData").Range("G" & j)
Sheets("Main Data").Range("H" & i) = Sheets("CM_MainData").Range("H" & j)
Sheets("Main Data").Range("I" & i) = Sheets("CM_MainData").Range("I" & j)
Sheets("Main Data").Range("J" & i) = Sheets("CM_MainData").Range("J" & j)
Sheets("Main Data").Range("K" & i) = Sheets("CM_MainData").Range("K" & j)
Sheets("Main Data").Range("L" & i) = Sheets("CM_MainData").Range("L" & j)
Sheets("Main Data").Range("M" & i) = Sheets("CM_MainData").Range("M" & j)
Sheets("Main Data").Range("N" & i) = Sheets("CM_MainData").Range("N" & j)
Sheets("Main Data").Range("O" & i) = Sheets("CM_MainData").Range("O" & j)
Sheets("Main Data").Range("P" & i) = Sheets("CM_MainData").Range("P" & j)
i = i + 1
j = j + 1
Wend
Worksheets("Input").Activate
Worksheets("Input").Select
MsgBox "Step 1 Completed"
End Sub
</code></pre>
|
[] |
[
{
"body": "<p>Seems like instead of transferring, Copying the Data and using ThisWorkbook was able to get the job done easily.</p>\n<pre><code>Sub Mainsubtwo()\n\nCall Reset\nWorksheets("Main Data").Rows("12:" & Rows.Count).ClearContents\n\n\nApplication.ScreenUpdating = False\nApplication.DisplayAlerts = False\n\n'Open CM file\nSet MainDataCM = Workbooks.Open(Sheets("Input").Range("B16") & Sheets("Input").Range("B19"))\n\nWith Sheets("Main Data")\nlastrow = Sheets("Main Data").Range("A" & .Rows.Count).End(xlUp).Row\nSheets("Main Data").Range("A2:P" & lastrow).Copy\nEnd With\n'Paste into this workbook\nThisWorkbook.Sheets("Main Data").Range("A12").PasteSpecial xlPasteValues\n\n\n'Close CM file\nMainDataCM.Close SaveChanges:=False\nApplication.ScreenUpdating = True\nApplication.DisplayAlerts = True\n\nWorksheets("Input").Activate\nWorksheets("Input").Select\n\nMsgBox "Step 1 Completed"\n\n\nEnd Sub\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T21:27:54.650",
"Id": "252561",
"ParentId": "252531",
"Score": "1"
}
},
{
"body": "<h2>Copy a Range From One File to Another</h2>\n<ul>\n<li><p><code>s</code> - Source (read from), <code>d</code> - Destination (written to)</p>\n</li>\n<li><p>The code is still far from perfect but may be more educational for you to primarily understand the 'concept' of qualifying the objects:</p>\n<pre><code>Dim wb As Workbook: Set wb = ThisWorkbook ' continue using 'wb'\nDim ws As Worksheet: Set ws = wb.Worksheets("Sheet1") ' continue using 'ws'\nDim fCell As Range: Set fCell = ws.Range("A2") ' continue using 'fCell'\nDim lCell As Range: Set lCell = ws.Cells(ws.Rows.Count, "A").End(xlUp)\nDim rg As Range: Set rg = ws.Range(fCell, lCell) ' continue using 'rg'\n</code></pre>\n<p>etc. (it's for a one-column range)</p>\n</li>\n<li><p>Copying by assignment is by far the most efficient way to copy values (only):</p>\n<pre><code>Dim srg As Range: Set srg = Range("A1:D10")\nDim dCell As Range: Set dCell = Range("F1")\ndCell.Resize(srg.Rows.Count, srg.Columns.Count).Value = srg.Value\n</code></pre>\n<p>If you additionally do...</p>\n<pre><code>Dim drg As Range: Set drg = dCell.Resize(srg.Rows.Count, srg.Columns.Count)\nDebug.Print drg.Address(0, 0)\n</code></pre>\n<p>then the result (the address of the Destination Range) printed in the <code>Immediate window</code> will be <code>F1:I10</code>.</p>\n</li>\n</ul>\n<p><strong>The Code</strong></p>\n<pre class=\"lang-vb prettyprint-override\"><code>Option Explicit\n\nSub CopyMainData()\n \n ' Create a reference to the Destination Workbook.\n Dim dwb As Workbook: Set dwb = ThisWorkbook ' workbook containing this code\n \n ' Retrieve Source Workbook Path and Name.\n Dim swbPath As String, swbName As String\n With dwb.Worksheets("Input")\n swbPath = .Range("B16").Value\n swbName = .Range("B19").Value\n End With\n \n Application.ScreenUpdating = False\n \n ' Declare the Source Workbook variable.\n Dim swb As Workbook\n \n ' Check if a workbook with the same name as the name of the Source Workbook\n ' is already open. If so, close it saving any changes (or not?).\n On Error Resume Next\n Set swb = Workbooks(swbName)\n On Error GoTo 0\n If Not swb Is Nothing Then\n swb.Close SaveChanges:=True\n End If\n \n ' Attempt to open the Source Workbook.\n On Error Resume Next\n Set swb = Workbooks.Open(swbPath & swbName)\n On Error GoTo 0\n If swb Is Nothing Then\n MsgBox "The Workbook doesn't exist."\n Exit Sub\n End If\n \n ' If you feel that the previous two code blocks (scenarios)\n ' are not necessary (ridiculous) then replace them with:\n 'Set swb = Workbooks.Open(swbpath & swbName)\n \n ' The 'Call' keyword is considered deprecated.\n Reset ' Reset what? e.g. 'ResetData' or 'ResetMain' are better names.\n \n ' Create a reference to the Source Range.\n Dim srg As Range\n With swb.Worksheets("Main Data")\n Dim sLastRow As Long: sLastRow = .Range("A" & .Rows.Count).End(xlUp).Row\n Set srg = .Range("A2:P" & sLastRow)\n End With\n ' Maybe this would be more appropriate (make sure to test it):\n' With swb.Worksheets("Main Data").Range("A1").CurrentRegion\n' Set srg = .Resize(.Rows.Count - 1).Offset(1)\n' End With\n \n ' Calculate the rows count of the (same-sized) ranges.\n Dim rCount As Long: rCount = srg.Rows.Count\n \n ' Using the reference to the Destination First Row Range ('A12:P12')...\n With dwb.Worksheets("Main Data").Range("A12").Resize(, srg.Columns.Count)\n ' Create a reference to the Destination Range.\n Dim drg As Range: Set drg = .Resize(rCount)\n ' Copy the values of the Source Range to the Destination Range\n ' by 'assignment'.\n drg.Value = srg.Value\n ' Create a reference to the Destination Clear Range, the range\n ' below the Destination Range.\n Dim dcrg As Range\n Set dcrg = .Resize(dws.Rows.Count - .Row - rCount + 1).Offset(rCount)\n ' Clear the contents of the Destination Clear Range\n dcrg.ClearContents\n End With\n \n ' Save and close.\n swb.Close SaveChanges:=False\n 'dwb.Save\n \n Application.ScreenUpdating = True\n \n MsgBox "Main data copied."\n\nEnd Sub\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-05T23:28:17.437",
"Id": "262703",
"ParentId": "252531",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T15:25:50.367",
"Id": "252531",
"Score": "2",
"Tags": [
"vba",
"excel"
],
"Title": "VBA, Transferring of Data from one File to another"
}
|
252531
|
<p>I have been developing software drivers for the mcu peripherals in C++. My approach how to implement the drivers is following.</p>
<p>Each peripheral has its software driver modeled by C++ class with its interface</p>
<p>Peripheral.h</p>
<pre><code>#include <cinttypes>
#include "DriversCfg.h"
class Peripheral {
public:
Peripheral(const PeripheralCfg& peripheral_cfg, uint32_t base_address);
void enable();
void toggleReset();
bool isEnabled();
private:
struct ControlReg
{
uint32_t enable_bit: 1;
uint32_t reset_bit: 1;
uint32_t cfg_bit_01: 1;
uint32_t cfg_bit_02: 1;
uint32_t cfg_bit_03: 1;
};
struct PeripheralRegs
{
volatile ControlReg control_reg;
};
PeripheralRegs* regs;
};
</code></pre>
<p>and its implementation</p>
<p>Peripheral.cpp</p>
<pre><code>#include <new>
#include "Peripheral.h"
Peripheral::Peripheral(const PeripheralCfg& peripheral_cfg, uint32_t base_address) {
regs = new (reinterpret_cast<void*>(base_address)) PeripheralRegs;
regs->control_reg.cfg_bit_01 = static_cast<uint32_t>(peripheral_cfg.cfg_bit_1);
regs->control_reg.cfg_bit_02 = static_cast<uint32_t>(peripheral_cfg.cfg_bit_2);
regs->control_reg.cfg_bit_03 = static_cast<uint32_t>(peripheral_cfg.cfg_bit_3);
}
void Peripheral::enable()
{
regs->control_reg.enable_bit = 1;
}
bool Peripheral::isEnabled()
{
return ((regs->control_reg.enable_bit) != 0);
}
void Peripheral::toggleReset()
{
if(regs->control_reg.reset_bit)
{
regs->control_reg.reset_bit = 0;
}
else
{
regs->control_reg.reset_bit = 1;
}
}
</code></pre>
<p>Each peripheral has fixed part of its configuration i.e. part of configuration which is not changeable during run-time</p>
<p>PeripheralCfg.h</p>
<pre><code>enum class FunctionUsage
{
kNotUsed,
kUsed
};
struct PeripheralCfg
{
FunctionUsage cfg_bit_1;
FunctionUsage cfg_bit_2;
FunctionUsage cfg_bit_3;
};
</code></pre>
<p>There is a "container" containig the fixed part of the configuration for all the peripherals</p>
<p>DriversCfg.h</p>
<pre><code>#include "PeripheralCfg.h"
struct DriversCfg
{
PeripheralCfg periph_cfg_01 = {FunctionUsage::kAdcNotUsed, FunctionUsage::kAdcUsed,
FunctionUsage::kAdcUsed};
PeripheralCfg periph_cfg_02 = {FunctionUsage::kAdcNotUsed, FunctionUsage::kAdcNotUsed,
FunctionUsage::kAdcUsed};
};
</code></pre>
<p>There is a "container" containing instances of all the drivers</p>
<p>Hal.h</p>
<pre><code>#include "Peripheral.h"
#include "DriversCfg.h"
class Hal {
public:
Peripheral *periph_01;
Peripheral *periph_02;
Hal();
private:
DriversCfg configuration;
};
</code></pre>
<p>Hal.cpp</p>
<pre><code>#include "Hal.h"
#include "DriversCfg.h"
#include "Registers.h"
Hal::Hal() {
periph_01 = new Peripheral(configuration.periph_cfg_01, PERIPH_01_BASE_ADDRESS);
periph_02 = new Peripheral(configuration.periph_cfg_02, PERIPH_02_BASE_ADDRESS);
}
</code></pre>
<p>The intended usage is</p>
<p>main.cpp</p>
<pre><code>int main(int argc, char** argv)
{
Hal hal;
hal.periph_01->enable();
hal.periph_02->enable();
}
</code></pre>
<p>I have tested this approach and it works. Nevertheless I have some doubts regarding namely following aspects:</p>
<ul>
<li>container <code>DriversCfg</code> with configuration for the peripherals in which the individual configurations are public - is it a problem here?</li>
<li>order of instantiation of the private attribute <code>DriversCfg configuration</code> in the <code>class Hal</code> more precisely whether there is a chance that the <code>DriversCfg configuration</code> will not be created at the moment when a reference to it will be passed into the peripheral drivers?</li>
</ul>
<p>Thanks in advance for any remarks and suggestions.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T17:27:19.173",
"Id": "497634",
"Score": "1",
"body": "What is the target platform for this code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T17:29:03.813",
"Id": "497636",
"Score": "0",
"body": "And what compiler is this for?"
}
] |
[
{
"body": "<h1>Avoid the placement <code>new</code></h1>\n<p>The placement <code>new</code> you are doing looks redundant. <code>PeripheralRegs</code> is a POD type, so its member values will <a href=\"https://stackoverflow.com/questions/14659752/placement-new-and-uninitialized-pod-members\">probably</a> not be initialized, but to avoid any doubt I would just write:</p>\n<pre><code>Peripheral::Peripheral(const PeripheralCfg& peripheral_cfg, uint32_t base_address):\n regs{reinterpret_cast<PeripheralRegs*>(base_address)}\n{\n regs->control_reg.cfg_bit_01 = static_cast<uint32_t>(peripheral_cfg.cfg_bit_1);\n regs->control_reg.cfg_bit_02 = static_cast<uint32_t>(peripheral_cfg.cfg_bit_2);\n regs->control_reg.cfg_bit_03 = static_cast<uint32_t>(peripheral_cfg.cfg_bit_3);\n}\n</code></pre>\n<h1>Toggle using XOR</h1>\n<p>You can rewrite <code>toggleReset()</code> by using the XOR operation:</p>\n<pre><code>void Peripheral::toggleReset()\n{\n regs->control_reg.reset_bit ^= 1;\n}\n</code></pre>\n<h1>Why the <code>k</code> prefix for <code>enum class</code> values?</h1>\n<p>I see the values of <code>enum class FunctionUsage</code> are prefixed with a <a href=\"https://stackoverflow.com/questions/5016622/where-does-the-k-prefix-for-constants-come-from\"><code>k</code></a>. This looks like Hungarian notation, but I don't see Hungarian notation used anywhere else in this code. I suggest you drop it. Since it's an <code>enum class</code>, there is no chance that these values would conflict with anything else.</p>\n<h1>Use arrays where appropriate</h1>\n<p>I see several variables being repeated with just a different number at the end. Those are often a candidate to be replaced by arrays. Consider writing:</p>\n<pre><code>struct PeripheralCfg\n{\n FunctionUsage cfg_bits[3];\n};\n\n...\n\nstruct DriversCfg \n{\n PeripheralCfg periph_cfgs[2] = {\n {FunctionUsage::kAdcNotUsed, FunctionUsage::kAdcUsed, FunctionUsage::kAdcUsed},\n {FunctionUsage::kAdcNotUsed, FunctionUsage::kAdcNotUsed, FunctionUsage::kAdcUsed},\n };\n};\n\n...\n\nclass Hal {\n ...\n Peripheral *peripherals[2];\n ...\n};\n</code></pre>\n<p>And so on. You can always rename the variables you used before to refer to an array element, for example <code>periph_01</code> becomes <code>periph[0]</code>. Also, it opens up possibilities to use <code>for</code>-loops to avoid repetition:</p>\n<pre><code>for (auto &periph: hal.peripherals)\n periph->enable();\n</code></pre>\n<p>Although it looks silly now with an array of only two elements, it will quickly become more useful if you have to support hardware which supports more peripherals.</p>\n<h1>Make <code>Hal::configuration</code> <code>static const</code></h1>\n<p>It looks like <code>Hal::configuration</code> is only meant to be read once, and never changed. You should change it into a <code>static const</code> variable:</p>\n<pre><code>class Hal {\n ...\n static const DriversCfg configuration;\n ...\n};\n</code></pre>\n<p>Although it does look a bit weird this way. If it's only used by the constructor of <code>Hal</code>, then this should not be a (static) class member at all. You could move it completely into <code>Hal.cpp</code>:</p>\n<pre><code>static const struct\n{\n PerpheralCfg periph_configs[2] = {...};\n} configuration;\n\nHal::Hal() {\n perhiperal[0] = new Peripheral(configuration.periph_cfgs[0], PERIPH_01_BASE_ADDRESS);\n perhiperal[1] = new Peripheral(configuration.periph_cfgs[1], PERIPH_02_BASE_ADDRESS);\n}\n</code></pre>\n<p>You could also keep the configuration in <code>DriversCfg.h</code>, but then still exactly as I've shown here.</p>\n<p>As for the order of instantiation: global variables are instantiated before <code>main()</code> runs, so <code>configuration</code> will be valid before the variable <code>hal</code> is constructed. If it was still a regular member variable, then it would also have been instantiated before the body of the constructor was run, so your code is fine in that respect.</p>\n<h1>Avoid unnecessary memory allocations</h1>\n<p>Why does <code>Hal</code> need to allocate the <code>Peripheral</code>s on the heap? Especially on an MCU you want to avoid dynamic memory allocations. So instead of having pointers to <code>Peripheral</code>s inside <code>class Hal</code>, just have them by value:</p>\n<pre><code>class Hal {\npublic:\n Peripheral peripherals[2];\n Hal();\n};\n\n...\n\nHal::Hal():\n peripherals{\n {configuration.periph_cfgs[0], PERIPH_01_BASE_ADDRESS},\n {configuration.periph_cfgs[1], PERIPH_02_BASE_ADDRESS},\n }\n{}\n</code></pre>\n<p>And then use it like so:</p>\n<pre><code>int main(...)\n{\n Hal hal;\n for (auto &periph: hal.peripherals)\n periph.enable();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T15:22:31.263",
"Id": "497901",
"Score": "0",
"body": "thank you very much for your remarks. Please can you explain to me why it is necessary to use the initialization part of the constructor of the Hal for initializing the instances of the Peripheral class in the peripherals array instead of initializing the instances in the constructor body?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T16:30:30.980",
"Id": "497919",
"Score": "0",
"body": "@L3sek In this case it doesn't really matter. If the variables you initialize are more complex, with their own constructors/destructors, then it might be slightly more efficient, or the only way possible; if it's in the body the variables will first be default constructed, then copy-assigned (and not all classes can be default constructed and/or copy-assigned to). And if something in the constructor body can `throw`, then it becomes really important that the member variables are properly initialized before the body runs, to avoid things being left in an inconsistent state."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T20:23:08.370",
"Id": "252557",
"ParentId": "252534",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "252557",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T16:05:38.880",
"Id": "252534",
"Score": "3",
"Tags": [
"c++",
"embedded",
"device-driver"
],
"Title": "Software drivers for the mcu peripherals in C++"
}
|
252534
|
<p>After an extended absence from coding, I decided I would make something to try and get back on my feet again. I ended up making a project that I have made several times before, a higher-lower guessing game. Now while the coding process went well and I came out with something that works quite well, I feel like I fell into a lot of my old bad coding practices. I feel it would be good that before I move onto bigger projects that I post this here and see where I'm screwing up.</p>
<p>I would just like to know if there are any just general bad practices or things that could be made better.</p>
<pre class="lang-py prettyprint-override"><code>from random import randint
def find_min_max() -> list:
"""Find ths minimum and maximum values for the number to be between"""
while True:
try:
min_max = [int(input("Please enter the min value: ")), int(input("Please enter max value: "))]
if min_max[0] < min_max[1]:
return min_max
else:
print("Make sure the min number is smaller than the max number.")
except ValueError:
print("Please enter numbers only.")
def find_guess_limit():
"""Finds if the user wants a guess limit, and sets it if they do"""
while True: # Finds if the user wants a guess limit
guess_limit = input("Would you like to limit your guess's? (Y/N): ").lower()
if (guess_limit == "y") or guess_limit == "n":
if guess_limit == "n":
return None
while True: # Gets what the user wants the guess limit to be
try:
guess_limit = int(input("What would you like the guess limit to be: "))
if guess_limit > 0:
return guess_limit
else:
print("Make sure the number is greater than zero.")
except ValueError:
print("Please enter only a number.")
else:
print("Please only enter Y or N.")
def setup():
"""Sets up the game parameters"""
min_max = find_min_max()
guess_limit = find_guess_limit()
return min_max, guess_limit
def play_round(num: int) -> bool:
"""Goes through one guess by the player"""
while True:
try:
guess = int(input("What number is your guess: "))
if guess == num:
print("You got it!")
return True
elif guess > num:
print("The number is lower.")
return False
elif guess < num:
print("The number is higher.")
return False
except ValueError:
print("Please only enter a number.")
def reset() -> [bool]:
"""Checks if the player wants to quit, and if they don't, checks if they want to change the rules"""
while True: # Checks if the user wants to quit the game
close = input("Would you like to exit the game? (Y/N): ").lower()
if (close == "y") or (close == "n"):
if close == "y":
quit()
else:
break
print("Please only enter Y or N.")
while True: # Checks if the user wants the rules to be changed
rule_change = input("Would you like to change the rules? (Y/N): ").lower()
if (rule_change == "y") or (rule_change == "n"):
if rule_change == "y":
return True
else:
return False
print("Please only enter Y or N.")
min_max, guess_limit = setup()
while True:
num = randint(min_max[0], min_max[1])
if guess_limit is None:
while True:
if play_round(num):
break
else:
for _ in range(guess_limit):
won = play_round(num)
if won:
break
if not won:
print("Sorry, you ran out of guess's")
if reset():
min_max, guess_limit = setup()
</code></pre>
|
[] |
[
{
"body": "<h2>Return tuples</h2>\n<p><code>find_min_max</code> is not well-suited to returning a list. Instead:</p>\n<ul>\n<li>Separate <code>min_max</code> into two variables, <code>min_val</code> and <code>max_val</code></li>\n<li><code>return min_val, max_val</code></li>\n<li>Change your return hint to <code>Tuple[int, int]</code></li>\n</ul>\n<p>This is what <code>setup</code> already does, though <code>setup</code> would benefit from unpacking the result from <code>find_min_max</code>, and should get its own return type hint.</p>\n<h2>Grammar</h2>\n<p><code>your guess's</code> -> <code>your guesses</code></p>\n<h2>Input validation</h2>\n<pre><code>if (guess_limit == "y") or guess_limit == "n":\n # ...\nelse:\n print("Please only enter Y or N.")\n</code></pre>\n<p>is better-stated, I think, as</p>\n<pre><code>if guess_limit == 'n':\n return None\n\nif guess_limit != 'y':\n print("Please only enter Y or N.")\n continue\n\n# ...\n</code></pre>\n<p>This allows de-indentation of the rest of the loop, takes care of the simple cases first, and reduces the number of comparisons necessary.</p>\n<p>Similarly,</p>\n<pre><code> if (rule_change == "y") or (rule_change == "n"):\n if rule_change == "y":\n return True\n else:\n return False\n print("Please only enter Y or N.")\n</code></pre>\n<p>can be</p>\n<pre><code>if rule_change in {'y', 'n'}:\n return rule_change == 'y'\nprint("Please only enter Y or N.")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T17:23:04.633",
"Id": "252543",
"ParentId": "252537",
"Score": "3"
}
},
{
"body": "<h1>Unnecessary construction of lists</h1>\n<pre class=\"lang-py prettyprint-override\"><code>min_max = [int(input("Please enter the min value: ")), int(input("Please enter max value: "))]\n</code></pre>\n<p>Unnecessary list construction here. It requires you to do <code>min_max[]</code> to get the correct value. Just remove the list construction and separate it into two variables.</p>\n<pre class=\"lang-py prettyprint-override\"><code>min_val, max_val = int(input("Please enter the min value: ")), int(input("Please enter max value: "))\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>min_val = int(input("Please enter the min value: "))\nmax_val = int(input("Please enter the max value: "))\n</code></pre>\n<p>Your <code>except</code> block will catch any bad input. That's good! We can further improve it by doing the following</p>\n<p>(optional)</p>\n<p>Say I enter the first value correctly, but mess up when I input the second one. The problem here is I have to re-enter the first value again. We can solve this with just a few more lines of code, overall a better experience;</p>\n<p>I personally prefer having a function like such</p>\n<pre class=\"lang-py prettyprint-override\"><code>def num_input(prompt, err_msg = "Invalid input!"):\n while True:\n try:\n num = int(input(prompt))\n except Exception:\n print(err_msg)\n continue \n break\n return num\n</code></pre>\n<p>That way I can take input in the following manner</p>\n<pre class=\"lang-py prettyprint-override\"><code>min_val = num_input("Please enter the min value: ")\nmax_val = num_input("Please enter the max value: ")\n</code></pre>\n<p>Now each variable has its own <code>while True</code> loop which ensures you get good, valid input.</p>\n<hr />\n<h1>If-statement logic</h1>\n<pre class=\"lang-py prettyprint-override\"><code> if (guess_limit == "y") or guess_limit == "n":\n if guess_limit == "n":\n return None\n while True: # Gets what the user wants the guess limit to be\n try:\n ...\n ...\n\n else:\n print("Please only enter Y or N.")\n</code></pre>\n<ul>\n<li>The parenthesis are not required</li>\n</ul>\n<p>Notice you are checking for <code>guess_limit == "y"</code> twice here. How about you re-structure this and make it</p>\n<pre class=\"lang-py prettyprint-override\"><code> if guess_limit == "n":\n return None \n if guess_limit != "y":\n print("Please only enter Y or N.") \n continue\n while True: # Gets what the user wants the guess limit to be\n try:\n ....... \n</code></pre>\n<p>Not only here, but there are 2-3 instances in your code where having a <code>num_input</code> function like the one in my previous point will reduce a lot of repetition. They all follow the same rule, put them in a function.</p>\n<hr />\n<h1>Splitting work</h1>\n<pre class=\"lang-py prettyprint-override\"><code>def find_guess_limit():\n """Finds if the user wants a guess limit, and sets it if they do"""\n while True: # Finds if the user wants a guess limit\n guess_limit = input("Would you like to limit your guess's? (Y/N): ").lower()\n if (guess_limit == "y") or guess_limit == "n":\n if guess_limit == "n":\n return None\n while True: # Gets what the user wants the guess limit to be\n try:\n guess_limit = int(input("What would you like the guess limit to be: "))\n if guess_limit > 0:\n return guess_limit\n else:\n print("Make sure the number is greater than zero.")\n except ValueError:\n print("Please enter only a number.")\n else:\n print("Please only enter Y or N.")\n</code></pre>\n<p>Better split this into two functions, <code>wants_limit_guess()</code> and <code>find_limit_guess()</code>. Follow the <a href=\"https://deviq.com/single-responsibility-principle/\" rel=\"noreferrer\">single-responsibillity-principle</a>. That way you can do</p>\n<pre class=\"lang-py prettyprint-override\"><code>if (wants_limit_guess()) \n limit_guess = find_limit_guess()\nelse:\n ...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T17:27:36.327",
"Id": "252544",
"ParentId": "252537",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "252543",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T16:14:17.550",
"Id": "252537",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"number-guessing-game"
],
"Title": "Higher or Lower guessing game"
}
|
252537
|
<p>I implemented a Vigenere cipher that preserves case and can also decrypt if you pass the <code>-d</code> argument. Usage is <code>./vigenere <plaintext|ciphertext> key [-d]</code> and it works fine but I think there are probably some things I could do better. So, just looking for critique.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define ENCRYPT 1
#define DECRYPT -1
int mod(int x, int n)
{
return (x % n + n) % n;
}
char *vigenere(char *input, char *keystream, int mode)
{
if (strlen(keystream) != strlen(input))
return NULL;
int output_len = strlen(input), offset = 'a', wasupper = 0;
char *output = malloc(output_len);
for (int i = 0; i < output_len; ++i)
{
if (isupper(input[i]))
{
input[i] = tolower(input[i]);
wasupper = 1;
}
else
wasupper = 0;
output[i] = mod((input[i] - offset) + (keystream[i] - offset) * mode, 26) + offset;
if (wasupper)
output[i] = toupper(output[i]);
}
return output;
}
char *gen_keystream(char *key, int keystream_len)
{
int key_len = strlen(key), j = 0;
char *keystream = malloc(keystream_len);
for (int i = 0; i < keystream_len; j = ++i % key_len)
keystream[i] = key[j];
return keystream;
}
int main(int argc, char **argv)
{
if (argc < 3)
return EXIT_FAILURE;
int mode = ENCRYPT;
if (argc > 3 && strcmp(argv[3], "-d") == 0)
mode = DECRYPT;
int keystream_len = strlen(argv[1]);
char *keystream = gen_keystream(argv[2], keystream_len);
char *result = vigenere(argv[1], keystream, mode);
printf("%s\n", result);
free(keystream);
free(result);
return EXIT_SUCCESS;
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>Bug: no null character</strong></p>\n<p><code>printf("%s\\n", result);</code> fails as <code>result</code> does not point to a <em>string</em>. That data lacks a <em>null character</em> and is short, by 1 of allocated memory needed.</p>\n<pre><code>// char *output = malloc(output_len);\nchar *output = malloc(output_len +1);\noutput[output_len] = '\\0';\n</code></pre>\n<p>Similar problem with decryptor.</p>\n<p><strong>No protection against non-A-Z characters</strong></p>\n<p>I'd expect only encrypting/decrypting when the <code>input[]</code> is an <code>A-Z</code>.</p>\n<p>I suspect code may generate <code>output[i] == 0</code> for select inputs, rendering the string short.</p>\n<hr />\n<p><strong>Pedantic bug: Negative <code>char</code></strong></p>\n<p>When <code>input[i] < 0</code>, <code>isupper(input[i])</code> is UB. Better to access the string via an <code>unsigned char *</code> for <code>is...()</code>.</p>\n<p>A negative <code>char</code> value also messes-up <code>mod()</code>. When <code>x < 0</code>, <code>x % n</code> code does <a href=\"https://stackoverflow.com/a/20638659/2410359\"><em>not</em></a> perform a Euclidean mod.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T09:22:50.663",
"Id": "497715",
"Score": "0",
"body": "In your code example you comment out the first line, then repeat it verbatim - shouldn't your replacement be `char *output = malloc(output_len)+1;` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T11:35:18.930",
"Id": "497730",
"Score": "0",
"body": "@GuntramBlohm You mean `char *output = malloc(output_len + 1);`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T13:35:45.303",
"Id": "497739",
"Score": "0",
"body": "@KonradRudolph Ouch. Got me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T14:44:26.167",
"Id": "497750",
"Score": "0",
"body": "@KonradRudolph I first used the transparent no width `+ 1`. Edited to show opaque code`. (IOWs, I erred)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T08:04:08.157",
"Id": "497864",
"Score": "0",
"body": "As part of the comment about negative `char`, the program doesn't play well with letters such as `à` or `ñ`, even if converted to unsigned first..."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T19:16:49.783",
"Id": "252551",
"ParentId": "252546",
"Score": "7"
}
},
{
"body": "<h1>Process a stream of data instead of a single string</h1>\n<p>Your program works by passing the input as a command-line argument, but what if you want to encode or decode a whole file? What if the input is huge? I would try to modify the program so that it can run from a file, or from standard input if no file is specified, so you can do for example:</p>\n<pre><code>./vigenere key < plaintext.txt > ciphertext.txt\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T19:18:13.677",
"Id": "252552",
"ParentId": "252546",
"Score": "7"
}
},
{
"body": "<p>Here are some things that may help you improve your code.</p>\n<h2>Always use braces</h2>\n<p>The code currently includes this:</p>\n<pre><code>if (isupper(input[i]))\n{\n input[i] = tolower(input[i]);\n wasupper = 1;\n}\nelse\n wasupper = 0;\n\n output[i] = mod((input[i] - offset) + (keystream[i] - offset) * mode, 26) + offset;\n \n if (wasupper)\n output[i] = toupper(output[i]);\n \n</code></pre>\n<p>The problem is that the indentation after the <code>else</code> <em>suggests</em> that all of those lines are executed only if <code>isupper(input[i])</code> evaluates to false, but that's not the case. Only the <code>wasupper = 0;</code> line is exclusively executed on that path. So then the reader of the code has to try to figure out if it's an indentation error or a missing braces error. For that reason, especially if you're new to the language, I recommend <em>always</em> using <code>{}</code> for such conditional constructs.</p>\n<h2>Fix the bugs</h2>\n<p>A string in C must be terminated with a <code>'\\0'</code> character to be able to use function calls such as <code>strlen()</code>, but there are bugs in <code>gen_keystream</code> and in <code>vigenere</code> that fail to account for the terminator. Remember that <code>strlen()</code> returns the length of a string <em>excluding</em> this terminating character.</p>\n<h2>Think carefully about mathematical operations</h2>\n<p>This function is not broken, but it's not as efficient as it could be:</p>\n<pre><code>int mod(int x, int n)\n{\n return (x % n + n) % n;\n}\n</code></pre>\n<p>We can express the same notion using simply <code>return (x + n) % n;</code> given the expected range of <code>x</code> is <span class=\"math-container\">\\$(-n,n)\\$</span>. You can also simplify a bit more than this, as I'll demonstrate later.</p>\n<h2>Use <code>const</code> where practical</h2>\n<p>Because <code>vigenere</code> should alter neither <code>input</code> nor <code>keystream</code>, both should be declared <code>const</code>.</p>\n<h2>Put each statement on a single line</h2>\n<p>It is detrimental to the readability of your code declare several variables on the same line or to abuse the comma operator:</p>\n<pre><code>int output_len = strlen(input), offset = 'a', wasupper = 0; \n</code></pre>\n<p>Instead, separating each statement on its own line makes the code easier to read and maintain. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es10-declare-one-name-only-per-declaration\" rel=\"nofollow noreferrer\">ES.10</a></p>\n<h2>Check return values for errors</h2>\n<p>Calls to <code>malloc</code> can fail. You must check the return values to make sure they haven't or your program may crash (or worse) when given malformed input or due to low system resources. Rigorous error handling is the difference between mostly working versus bug-free software. You should strive for the latter.</p>\n<h2>Consider whether a function is needed</h2>\n<p>There are other ways to structure the program so that neither <code>gen_keystream</code> nor <code>keystream</code> are needed. You could simply pass the key into a modified version of <code>vigenere</code>.</p>\n<h2>Consider using pointers instead of indexing</h2>\n<p>Using pointers effectively is an essential skill for every C programmer. Here's a rewritten version of your function using most of the simplifications and corrections mentioned above:</p>\n<pre><code>char *vigenere(const char *input, const char *key, int mode)\n{\n int output_len = strlen(input); \n if (output_len == 0) {\n return NULL;\n }\n // add +1 for the terminating NUL character\n char *output = malloc(output_len + 1);\n if (output == NULL) {\n return output;\n }\n const char *keyptr = key;\n output[output_len] = '\\0';\n \n for (char *curr = output ; *input; ++input) {\n if (*keyptr == '\\0') {\n keyptr = key;\n }\n *curr = (mode * (*keyptr - tolower(*input)) + 26) % 26 + 'a';\n if (isupper(*input)) {\n *curr = toupper(*curr);\n }\n ++curr;\n ++keyptr;\n }\n return output;\n}\n</code></pre>\n<p>Note that in this code, I assume that all characters have already been checked and <code>isalpha()</code> is true for all input and that <code>islower()</code> and <code>isalpha()</code> are both true for every character of the key.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T16:44:46.670",
"Id": "497763",
"Score": "0",
"body": "Nitpick: Commas between variable declarations are not the \"comma operator\". And it's quite common and ideomatic to initialize multiple variables on a single line."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T16:56:18.373",
"Id": "497764",
"Score": "0",
"body": "True, it's not the comma operator in this context, but while it was once common to do so, modern usage favors one declaration per line. I've updated my answer to clarify this point."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T19:55:11.020",
"Id": "252554",
"ParentId": "252546",
"Score": "5"
}
},
{
"body": "<h1>This isn't a Vignère cipher</h1>\n<p>This line:</p>\n<blockquote>\n<pre><code>if (strlen(keystream) != strlen(input))\n return NULL;\n</code></pre>\n</blockquote>\n<p>means that the key needs to be exactly the same length as the input. So what you really have is a one-time-pad.</p>\n<p>A real Vignère cipher, in contrast, can encode arbitrarily large messages, by re-using the key every <code>strlen(key)</code> input characters. This explains how a Vignère cipher is less secure than OTP, particularly for short keys - but it's much more usable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T17:36:31.493",
"Id": "497776",
"Score": "0",
"body": "You might want to double check that. The code does, in fact, work with long input."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T08:01:07.070",
"Id": "497863",
"Score": "0",
"body": "Oh, I see - the calling code repeats the key. The function is still poorly named, IMO. And it shouldn't be necessary to allocate memory and copy out the key - I'll leave eliminating that as an exercise for the question author."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T17:10:51.377",
"Id": "252604",
"ParentId": "252546",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T18:13:12.557",
"Id": "252546",
"Score": "5",
"Tags": [
"c",
"vigenere-cipher",
"encryption"
],
"Title": "Vigenere cipher C program"
}
|
252546
|
<p>I am using one line arrow functions a lot, if they are well written I believe they can make code easier to read. I believe that the following code can be easily transformed into one liner but I can't figure out how. Any ideas please? I am asking more just from curiosity.</p>
<pre class="lang-javascript prettyprint-override"><code>const getUID = async () => {
let uid;
await firebase.auth().onAuthStateChanged(async (user) => {
if (!user) await firebase.auth().signInAnonymously();
uid = user.uid;
});
return uid;
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T19:39:52.007",
"Id": "497658",
"Score": "3",
"body": "No, it can't, and probably shouldn't. The real problem is that `onAuthStateChanged` expects a callback and is supposed to be used as an observable that **can fire multiple times**, but you're trying to use it as a promise, waiting for the first change only. You would need to immediately unsubscribe, similar to [this code](https://stackoverflow.com/q/47043188/1048572). Also you should not pass an `async` function as a callback."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T19:50:33.027",
"Id": "497660",
"Score": "0",
"body": "Ah, yeah, I forget that `onAuthStateChanged` is not one time job. Thanks for explaining!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T05:57:39.733",
"Id": "497700",
"Score": "0",
"body": "There is no syntactic rule that would force you to use new line characters. You can write entire applications as one liners. Whether you should is a different story. Don't let number of lines become your holy grail."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T08:26:40.577",
"Id": "497709",
"Score": "0",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<p>First of all, <code>onAuthStateChanged</code> expects a callback and <strong>can be fired multiple times</strong>. To resolve that you can use <code>unsubscribe()</code> after the first success.</p>\n<p>Secondly, for your code to work, you need to wait for <code>signInAnonymously</code>. At the moment you assign it to a temporary variable, but I can't see it working. Because <code>onAuthStateChanged</code> accepts a callback that can be fired multiple times, it won't wait in the main scope. To solve this, I suggest using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise\" rel=\"nofollow noreferrer\">Promise</a> constructor.</p>\n<p>Finally, you call <code>signInAnonymously</code>, but you don't do anything with its response. You need to use <code>user.uid</code> if the user is logged in, otherwise you need to use <code>signInAnonymously().user.uid</code></p>\n<p>So the final solution:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const getUID = async () => new Promise(resolve => {\n const unsubscribe = firebase.auth().onAuthStateChanged(user => {\n unsubscribe();\n resolve(user ? user.uid : firebase.auth().signInAnonymously().then(v => v.user.uid))\n });\n})\n\nconst uid = await getUID()\n</code></pre>\n<p>Explanation:</p>\n<ol>\n<li>Wrap everything to <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise\" rel=\"nofollow noreferrer\">Promise</a> and resolve it when we get <code>uid</code></li>\n<li>Auth & listen on <code>onAuthStateChanged</code></li>\n<li>Unsubscribe on the first <code>onAuthStateChanged</code> callback trigger (because one trigger it's enough in your case)</li>\n<li>Check if a user is defined (that means the user is signed in), resolve promise with user <code>uid</code></li>\n<li>If the user is not defined, use <code>signInAnonymously</code> to sign anonymous user, resolve that user `uid.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T08:06:23.347",
"Id": "252580",
"ParentId": "252553",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T19:30:46.310",
"Id": "252553",
"Score": "0",
"Tags": [
"javascript",
"ecmascript-6"
],
"Title": "Transform this to one line arrow function ES6+"
}
|
252553
|
<p>I implemented a queue that holds elements on an array as underlying data type:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <cstddef>
#include <cassert>
#include <concepts>
#include <stdexcept>
#include <type_traits>
#include <iostream>
namespace mine {
template <std::semiregular T, std::size_t N> class queue {
public:
using value_type = std::remove_cv_t<T>;
using const_value_type = std::add_const_t<value_type>;
using reference_type = std::add_lvalue_reference_t<value_type>;
using const_reference_type = std::add_const_t<reference_type>;
using size_type = std::size_t;
using const_size_type = std::add_const_t<size_type>;
void enqueue(const value_type val) {
if (current_size == N) {
throw std::overflow_error("queue overflowed.");
}
if (current_size == 0) {
m_head = m_tail = 0;
}
m_tail = current_size;
m_data[current_size++] = val;
}
value_type dequeue() {
if (current_size == 0) {
m_head = m_tail = 0;
throw std::underflow_error("queue underflowed.");
}
--current_size;
auto ret = m_data[m_head];
m_data[m_head] = T{};
++m_head;
return ret;
}
[[nodiscard]] reference_type head() { return m_data[m_head]; }
[[nodiscard]] const_reference_type head() const { return m_data[m_head]; }
[[nodiscard]] reference_type tail() { return m_data[m_tail]; }
[[nodiscard]] const_reference_type tail() const { return m_data[m_tail]; }
[[nodiscard]] bool empty() noexcept { return current_size == 0; }
[[nodiscard]] const bool empty() const noexcept { return current_size == 0; }
[[nodiscard]] size_type size() noexcept { return current_size; }
[[nodiscard]] const size_type size() const noexcept { return current_size; }
private:
size_type m_head = 0;
size_type m_tail = 0;
int current_size = 0;
value_type m_data[N]{};
};
}
</code></pre>
<p>And I wonder about the possible blunders, what is missing and how to make it better in general. Thanks a lot.</p>
|
[] |
[
{
"body": "<h1>Avoid unnecessary copies</h1>\n<p><code>enqueue()</code> takes its parameter by value, which means the caller has to make a copy. Then it has to store that value in the array, making another copy. You can avoid copies by replacing the function that takes a value with two overloads, one for <code>const</code> references and one for rvalue references:</p>\n<pre><code>void enqueue(const_reference_type val) {\n // same as before\n ...\n}\n\nvoid enqueue(value_type &&val) {\n // mostly the same\n ...\n // but now we move:\n data[current_size++] = std::move(val);\n}\n</code></pre>\n<p>The first version will make just one copy, the second one will use move assignment, which might avoid an expensive copy.</p>\n<p>Similarly, <code>dequeue()</code> makes a copy. You can avoid this by splitting this function in two; one that returns a reference to the head element so the caller can read it without having to copy it, and another function that just removes the head element. You already have a <code>head()</code>, so then just modify <code>dequeue()</code> to be:</p>\n<pre><code>void dequeue() {\n // mostly the same as before, except without returning anything\n ...\n}\n</code></pre>\n<p>This is also why <code>std::queue</code> provides a separate <code>front()</code> and <code>pop()</code> function. Also, doing it this way makes the requirements for <code>T</code> less strict; it now only requires it to be <code>std::default_constructible</code> and <code>std::movable</code>.</p>\n<h1>Make it look like <code>std::queue</code></h1>\n<p>Programming is much easier if everything has a similar interface. Consider renaming your member functions to match that of <code>std::queue</code>:</p>\n<ul>\n<li><code>enqueue()</code> -> <code>push()</code></li>\n<li><code>dequeue()</code> -> <code>pop()</code></li>\n<li><code>head()</code> -> <code>front()</code></li>\n<li><code>tail()</code> -> <code>back()</code></li>\n</ul>\n<p>You could also add <code>emplace()</code> and <code>swap()</code> to make it almost a drop-in replacement.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T23:15:05.450",
"Id": "497682",
"Score": "0",
"body": "Any tip on how to implement `swap()`? Because I need to swap the private variables as well. Maybe I could write a getter for the `m_data`, (like the `data()` on `std::vector`) to access but it would probably be nonsensical to have accessors for `m_head` and `m_tail` which are just a index values."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T07:26:39.063",
"Id": "497707",
"Score": "2",
"body": "If you make it a member function it has access to `private` variables, if you make it an out-of-class function you should make it a `friend` of your `class queue`. See [this question](https://stackoverflow.com/questions/5695548/public-friend-swap-member-function) for more details."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T21:24:51.897",
"Id": "252560",
"ParentId": "252555",
"Score": "7"
}
},
{
"body": "<h2>Make your typedefs more similar to Standard Library types</h2>\n<p>There is no need for <code>const_size_type</code> or <code>const_value_type</code>; if the user wanted them they could simply use <code>const mine::queue::value_type</code> or the like—as, in fact, you do.</p>\n<p>The standard library containers use <code>reference</code> and <code>const_reference</code>, not <code>reference_type</code> and <code>const_reference_type</code>. I would use the former set for consistency.</p>\n<p>I wouldn't do <code>using value_type = std::remove_cv_t<T>;</code>. <code>T</code> cannot have top-level <code>const</code>, since then it wouldn't fulfil the requirements for <code>semiregular</code>. The only purpose then is to strip top-level <code>volatile</code>, which is of dubious benefit for the additional semantic burden.</p>\n<h2>Don't define a non-<code>const</code> <code>size()</code> or <code>empty()</code> overload</h2>\n<p>The idea that calling <code>queue.size()</code> on a mutable queue potentially modifies it is... worrying. I would remove this overload entirely: remember that <code>const</code> member functions can be called on non-<code>const</code> objects, though not the other way around.</p>\n<p>For the <code>const</code> overload you should return <code>size_type</code>, not <code>const size_type</code>. Although there is no functional difference in this case, returning by <code>const</code> value is typically discouraged, as for class types it can inhibit moving. (The fact that there is no functional difference for primitive types is probably a case for avoiding the <code>const</code> in <code>const size_type</code> in and of itself, too.)</p>\n<p>All of the above applies to <code>empty()</code> as well.</p>\n<h2>Make the type of <code>current_size</code> consistent</h2>\n<p>Currently your <code>current_size</code> variable is of type <code>int</code>, but everywhere you use it where you would otherwise expect to be using <code>size_type</code>. This is problematic, because <code>signed</code> types (like <code>int</code>) and <code>unsigned</code> types (like <code>std::size_t</code>) have different behaviour and can cause some odd issues when mixed.</p>\n<p>In addition, on many systems <code>sizeof(std::size_t) > sizeof(int)</code>. This means that if the size of the array grows too large your <code>current_size</code> value will overflow, causing undefined behaviour.</p>\n<p>As you are using <code>std::size_t</code>/<code>size_type</code> everywhere else here, you should make <code>current_size</code> <code>size_type</code> as well.</p>\n<h2>Include (only) what you use</h2>\n<p>Your class does not appear to use anything from <code><cassert></code> or <code><iostream></code>. As such, you should remove those headers, to potentially improve compile times.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T05:02:17.513",
"Id": "252577",
"ParentId": "252555",
"Score": "6"
}
},
{
"body": "<p>You asked how to make the queue better in general, so I’m going to go in a completely different direction from the other reviews, and answer that question specifically.</p>\n<h1>Don’t abuse the standard library</h1>\n<p>The <code>enqueue()</code>/<code>push()</code> function throws <code>std::overflow_error</code> if the queue is full, and <code>dequeue()</code>/<code>pop()</code> throws <code>std::underflow_error</code> if the queue is empty. The problem with this is: that is <em>not</em> what those exceptions mean.</p>\n<p><code>std::overflow_error</code> and <code>std::underflow_error</code> are <em>supposed</em> to signal arithmetic errors—the overflow/underflow of values when doing numeric computations. If I tried to push a value into a queue and got a <code>std::overflow_error</code> thrown in my face, my response would be a flabbergasted: “What the <em>hell</em>? Did this queue just blow past <code>numeric_limits<size_t>::max()</code> while trying to calculate its new size? Does it have some weird internal bug?”</p>\n<p>Abusing existing standard exceptions because they just happen to have a name that sorta-kinda works in this case is a terrible idea. Either use the <em>correct</em> standard exceptions for the situation (for example, trying to push when the queue is full might warrant a <code>std::length_error</code>) or, much better, make specific exceptions for the specific errors. You could (and should) derive them from the standard exceptions where possible—in these cases, <code>std::logic_error</code> seems like a logical base:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>class queue_is_full : public std::logic_error\n{\npublic:\n queue_is_full() :\n std::logic_error{"failed attempt to push to full queue"}\n {}\n};\n\nclass queue_is_empty : public std::logic_error\n{\npublic:\n queue_is_empty() :\n std::logic_error{"failed attempt to pop from empty queue"}\n {}\n};\n</code></pre>\n<p>Or you could just throw a <code>std::logic_error</code>. This doesn’t really seem like a situation where specialized exceptions are necessary, because it’s not something that should ever happen. It’s trivial to not pop from an empty queue, or not push to a full queue, so it’s not like you should ever expect that to happen in well-written code.</p>\n<h1>Ease up on the restrictions</h1>\n<p>You constrain the types that can be put in the queue using the <code>std::semiregular</code> concept. Is that really necessary? Is there a reason I shouldn’t be allowed to store, say, <code>unique_ptr</code>’s in a queue?</p>\n<p>What do you <em>really</em> need for types in a queue? Well, as I see it, all you really need is for it to be copyable <em>OR</em> movable, so it can be copied/moved into and out of the queue. And you might not even need that with a slightly different interface. For example, if you had <code>emplace()</code>, then a value could theoretically be enqueued in-place—no copying or moving required at all. And if you had a way to pop that didn’t return the popped value—maybe spelled <code>drop()</code> or <code>ignore()</code>—then you could even dequeue without moving or copying (just destructing).</p>\n<p>Now, <code>std::semiregular</code> implies not only copyable, but also default-constructible… which you really <em>shouldn’t</em> need for a queue at all. But we’ll cross that bridge shortly.</p>\n<p>At the bare minimum, you should at least allow for noncopyable, move-only types. Because why not, right? You’d only need to change like two lines of code to do moves instead of copies in <code>enqueue()</code> and <code>dequeue()</code>, and use a requires clause instead of a concept directly:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>template <typename T, std::size_t N>\nrequires std::default_initializable<T> and (std::copyable<T> or std::movable<T>)\nclass queue\n{\n // ...\n</code></pre>\n<h1>A more honest interface</h1>\n<p>The biggest issue I’d have with this queue is that it’s dishonest about its state. By that I mean, for example, if I create queue with <code>auto q = mine::queue<T, 10>{};</code>, then when <code>q.empty()</code> returns <code>true</code>… the queue is not really empty. There are actually 10 <code>T</code>’s in it!</p>\n<p>Granted, I can’t actually get at those 10 <code>T</code>’s without some skullduggery… but they’re there. If <code>T</code> is some type that registers itself in some registry on construction, or has some static counter counting instances, I’m going to be baffled about where all these extra <code>T</code> objects are.</p>\n<p>More honest implementations of <code>empty()</code> and <code>size()</code> might look more like:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>constexpr auto empty() const noexcept { return false; }\nconstexpr auto size() const noexcept { return N; }\n</code></pre>\n<p>Except that’s also somewhat misleading, because <code>q.empty()</code> would be <code>true</code> and <code>q.size()</code> would be 10… but when I do <code>dequeue()</code>/<code>pop()</code>… I get an exception because there’s supposedly nothing there.</p>\n<p>I don’t have a solution to this quagmire (other than what I recommend about avoiding unnecessary constructions below). It would probably require additional or differently-named member functions, and probably giving up all hope of conforming to the standard container concepts.</p>\n<h1>Avoid unnecessary constructions</h1>\n<p>The <em>real</em> biggest issue with this queue—the cause of the problem above—is that it initializes an array full of default-constructed <code>T</code>’s as an “empty” queue. That’s pretty weird; I’d expect an empty queue to have zero <code>T</code>’s in it… not several that just happen to be hidden from me.</p>\n<p>Consider this implementation instead (neither tested, nor particularly well-thought-out; don’t trust it for anything but illustration):</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>template <typename T, std::size_t N>\nclass queue\n{\n static_assert(N != 0);\n\n std::array<std::optional<T>, N> m_data = {};\n std::size_t m_head = 0;\n std::size_t m_tail = 0;\n\npublic:\n template <typename... Args>\n requires std::constructible_from<T, Args...>\n auto emplace(Args&&... args) -> void\n {\n if (size() == N)\n throw std::logic_error{"queue is full"};\n\n // Don't update m_tail until the push succeeds, just in case of exception.\n //\n // The tail might be past-the-end (if the head is 0 and the queue is\n // full). To deal with this, we use the modulo operator (saves us a\n // conditional branch).\n auto index = m_tail % N;\n\n m_data[index].emplace(std::forward<Args>(args)...);\n\n m_tail = ++index;\n }\n\n auto push(T const& t) -> void\n {\n emplace(t);\n }\n\n auto push(T&& t) -> void\n {\n emplace(std::move(t));\n }\n\n auto pop() -> T\n {\n if (empty())\n throw std::logic_error{"queue is empty"};\n\n auto result = *std::move(m_data[m_head]);\n m_data[m_head].reset();\n\n // Advance the head. If it's past-the-end, wrap it around.\n m_head = (++m_head) % N;\n\n return result;\n }\n\n auto clear() noexcept -> void\n {\n for (auto&& t : m_data)\n t.reset();\n\n m_head = 0;\n m_tail = 0;\n }\n\n constexpr auto empty() const noexcept -> bool\n {\n // If the head and the tail are the same, then the queue is either empty\n // or full. The difference can be detected by seeing if the head optional\n // has a value or not.\n return m_head == (m_tail % N) and not m_data[m_head].has_value();\n }\n\n constexpr auto size() const noexcept -> std::size_t\n {\n // If the tail is greater than the head, then the size is simply the\n // distance between them.\n //\n // However, if the tail is less than the head, then the size is the\n // number of items between the head and the end of the array, plus the\n // number of items between the start of the array and the tail.\n //\n // (You could rewrite this to avoid the conditional, if you like, but I'd\n // leave that to the compiler.)\n if (m_tail >= m_head)\n return m_tail - m_head;\n else\n return (N - m_head) + m_tail;\n }\n\n constexpr auto max_size() const noexcept -> std::size_t { return N; }\n};\n</code></pre>\n<p>When this queue is constructed, even though its size is statically-determined and there is no dynamic allocation, it’s still “empty” in that there are no <code>T</code> objects in it… just <code>N</code> value-less <code>std::optional</code>’s. As you push stuff, those <code>optional</code>s will contain those values… as you pop stuff, they become value-less again.</p>\n<p>You could also do it better, with less wasted memory, and entirely <code>constexpr</code>†, by using an array of uninitialized memory, and <code>std::aligned_storage</code> or the equivalent, and <code>std::construct_at()</code>/<code>std::destruct_at()</code>. This would be <em>much</em> more complicated to do, but would probably be worth it. You’d need the <code>current_size</code> member again, but that’s one extra <code>std::size_t</code> in the queue class versus an extra <code>bool</code> for every element of the queue, so you’ll almost certainly save a <em>lot</em> of space for large queues. <a href=\"https://en.cppreference.com/w/cpp/types/aligned_storage\" rel=\"noreferrer\">The cppreference page on <code>std::aligned_storage</code> has a sample implementation of a static vector you could use as a base for this</a> (though you should use <code>std::construct_at()</code>/<code>std::destruct_at()</code> rather than placement new and so on).</p>\n<p>† (Presumably C++23? will have a fully-<code>constexpr</code> <code>std::optional</code>. But for now, you’d have to roll your own.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T22:38:44.577",
"Id": "252774",
"ParentId": "252555",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "252774",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T20:05:10.120",
"Id": "252555",
"Score": "6",
"Tags": [
"c++",
"c++20"
],
"Title": "Array based queue implementation with C++20"
}
|
252555
|
<p>Is there any way in which I can improve my code? I don't know if it is 100% right, and if it can be tweaked in order to be more efficient. That's why I'm posting here.</p>
<p>I'm open to any suggestions :)</p>
<pre><code>#include <iostream>
using namespace std;
int binarySearch(int arr[], int low, int high, int n)
{
if (low <= high)
{
int i = (high + low) / 2;
if (arr[i] == n)
{
return i;
}
else
{
if (arr[i] > n)
{
return binarySearch(arr, low, i - 1, n);
}
if (arr[i] < n)
{
return binarySearch(arr, i + 1, high, n);
}
}
}
return -1;
}
int main()
{
int arr[10]{ 1, 2, 3, 4, 5, 6, 8 }, n = 7;
cout<<binarySearch(arr, 0, 6, 9);
return 0;
}
</code></pre>
<p>Thanks.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T21:05:55.757",
"Id": "497664",
"Score": "0",
"body": "Improve the way you think about *divide&conquer*: multiple (typical: all) subproblems are solved, the overall solution is build from their solutions. Tends to be an improvement when effort grows faster than problem size and building a solutions from part-solutions is fast."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T09:23:25.593",
"Id": "497716",
"Score": "1",
"body": "I'd also declare the array `const` for two reasons: 1 readability, 2 compiler can make more assumptions if caller and this function are in separate code units."
}
] |
[
{
"body": "<h1>Avoid deeply nested <code>if</code>-statements</h1>\n<p>Deeply nested <code>if</code>-statements are hard to read. You can reduce the amount of nesting here by inverting the first <code>if</code>-statement and returning early, and avoiding the <code>else</code>-statement by using the fact that the <code>if</code> part already returns:</p>\n<pre><code>int binarySearch(int arr[], int low, int high, int n)\n{\n if (low > high)\n {\n return -1;\n }\n \n int i = (high + low) / 2;\n if (arr[i] == n)\n {\n return i;\n }\n\n if (arr[i] > n)\n {\n return binarySearch(arr, low, i - 1, n);\n }\n else\n {\n return binarySearch(arr, i + 1, high, n);\n }\n}\n</code></pre>\n<h1>Use <code>size_t</code> for array indices</h1>\n<p>When dealing with sizes, counts and indices, prefer using <code>size_t</code> to hold their values, as that type is guaranteed to be big enough to cover any array that can be addressed by your computer.</p>\n<p><code>size_t</code> is unsigned, so it might look like you can't return <code>-1</code>, but it turns out that integer promotion rules make it work regardless: you can <code>return -1</code>, and the caller can check <code>if (binarySearch(...) == -1)</code>, although perhaps better would be to create a constant for this, similar to <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/npos\" rel=\"noreferrer\"><code>std::string::npos</code></a>.</p>\n<h1>Try to make it more generic</h1>\n<p>Your binary search algorithm works for plain arrays of integers, but it doesn't work for anything else. What if you want to search in an array of <code>float</code>s? What if you want to search in a <code>std::vector</code>? The standard library provides <a href=\"https://en.cppreference.com/w/cpp/algorithm/binary_search\" rel=\"noreferrer\"><code>std::binary_search()</code></a> which can work on a variety of containers holding any type that can be compared. It might be good practice to try to make the interface to your binary search implementation similar to that of <code>std::binary_search()</code>. It is not as hard as it looks! You can start by making it a template for arrays of different types:</p>\n<pre><code>template<typename T>\nsize_t binarySearch(T arr[], size_t low, size_t high, const T &n)\n{\n ...\n}\n</code></pre>\n<p>Once you have done that excercise, try to have it take two iterators, and return an iterator to the element if it's found, or <code>last</code> if not (assuming <code>last</code> now points to right after the end of the range to search):</p>\n<pre><code>template<typename It, typename T>\nIt binarySearch(It first, It last, const T &n)\n{\n ...\n}\n</code></pre>\n<p>This is a bit more advanced; you have to work within the limitations of the iterators.\nLast you might want to add another template parameter, <code>typename Comp</code>, so you can provide a custom comparison operator.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T21:07:49.923",
"Id": "497665",
"Score": "0",
"body": "*avoiding the `else`-statement by using the fact that the `if` part already returns* does that apply to the last conditional statement in the first revision of your answer, too?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T21:28:40.103",
"Id": "497669",
"Score": "2",
"body": "@greybeard You are right, but the last `else return ...` did not increase indentation levels, and in this case I think it better preserves the symmetry between the two branches."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T07:17:20.693",
"Id": "497705",
"Score": "0",
"body": "Thanks for the great tips. I'll edit the code accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T14:39:07.877",
"Id": "497749",
"Score": "1",
"body": "@KonradRudolph I copied [cppreference's](https://en.cppreference.com/w/cpp/algorithm/binary_search) variable names here. I guess it's a matter of preference, and at this point consistency is the most important factor to name things, so that either all your iterator variables are named `begin`/`end` or all are named `first`/`last`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T14:51:05.030",
"Id": "497752",
"Score": "0",
"body": "@G.Sliepen My bad, I confused them with `front` and `back`. In fact, t’s not just cppreference: the standard *itself* uses these names for half-open iterator ranges, so this is entirely appropriate and even canonical."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T20:55:59.313",
"Id": "252558",
"ParentId": "252556",
"Score": "13"
}
},
{
"body": "<p>Should have some documentation saying what it does, i.e., what the parameters mean and what the result will be. Especially what <code>high</code> means, as some people make it inclusive and others make it exclusive. It's also against C++ usual name <code>last</code> and apparently against C++'s usual semantic of <code>last</code> being exclusive. One shouldn't have to analyze the implementation code in order to find all that out.</p>\n<p>You might not want to test <code>arr[i] == n</code> first, as that's the <em>least</em> likely case, so giving it the fastest route (just one test instead of two or three) is rather an anti-optimization. Btw, why check <code><</code> after you already ruled out <code>==</code> and <code>></code>? Int pairs can't fail all three. And if you use this for other types where all three <em>can</em> fail (for example sets with subset/superset relationships), then... you probably shouldn't be doing that anyway.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T04:46:45.053",
"Id": "497695",
"Score": "0",
"body": "To stress the indispensability of documentation (and in-code documentation gets separated/lost from the code least easily): suppose this is in a multi-developer project. One checks what happens when the range doesn't contain the key and relies on, say, result < 0. Another one finds it useful to get the least index of an item no smaller than the key (à la Python [`bisect_left()`](https://docs.python.org/3/library/bisect.html)) and modifies the code accordingly - after all, found or not can be established with a single equality check, right? (wrong: return value may be `high`)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T07:18:29.937",
"Id": "497706",
"Score": "0",
"body": "Can you give me an example of inclusive vs exclusive parameters in this DAC algorithm? The other part was clear. Thanks :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T10:49:29.183",
"Id": "497724",
"Score": "1",
"body": "@OctavianNiculescu Not sure what you mean. Are you just not familiar with those words? Inclusive means the range [low,high] and exclusive means [low,high). For inclusive, `arr[high]` is part of the input, for exclusive it's not (the last element is instead `arr[high - 1]`)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T21:31:25.270",
"Id": "252562",
"ParentId": "252556",
"Score": "5"
}
},
{
"body": "<p>Since nobody has mentioned it:</p>\n<p><strong>Your code contains a <a href=\"https://ai.googleblog.com/2006/06/extra-extra-read-all-about-it-nearly.html\" rel=\"noreferrer\">famous bug</a>.</strong> The following code may overflow the <code>int</code> range for large arrays:</p>\n<pre><code>int i = (high + low) / 2;\n</code></pre>\n<p>To avoid this, use the following:</p>\n<pre><code>int i = low + (high - low) / 2;\n</code></pre>\n<p>Note that simply using a different data type isn’t enough — it just postpones the bug to larger arrays.</p>\n<p>Another, unrelated issue relates to code readability: in the parameter list to <code>binarySearch</code>, <code>int arr[]</code> looks like an array declaration but (because of C++ rules), this is actually a <em>pointer</em>, i.e. it’s equivalent to writing <code>int* arr</code>. Using the <code>int arr[]</code> syntax is potentially misleading, and therefore best avoided.</p>\n<p>To further improve readability, use a different name for <code>i</code> (what does <code>i</code> stand for?). <code>mid</code> is frequently used here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T14:10:01.850",
"Id": "497744",
"Score": "0",
"body": "Ha, I wanted to mention that bug but got too riled up about the unclear parameters and then forgot :-). In what way is `int arr[]` misleading, i.e., how might someone misunderstand it and what would be the problem? (I don't know what you mean with C++ rules.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T14:17:15.963",
"Id": "497745",
"Score": "1",
"body": "@superbrain Arrays have subtly different semantics from pointers in C and C++. The most obviously problem is that `sizeof` behaves differently. They’re also simply distinct types, so they call different overloaded functions. But the most obvious problem is that thinking an array is passed here reinforces a wrong mental model of the C++ type system, and using this false array syntax instead of pointer syntax is therefore almost exclusively done *in error* by beginners who genuinely think they’re passing an array (or who think that arrays and pointers are the same thing)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T14:22:06.033",
"Id": "497747",
"Score": "1",
"body": "Put simpler, the function parameter type is a *pointer*, not an *array*. Using a “fake-array” syntax implies the wrong type. The fact that C++ even has this misleading syntax is a historic mistake."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T14:32:09.230",
"Id": "497748",
"Score": "5",
"body": "Good point, this issue is so common that C++20 introduced a function to deal with it: [`std::midpoint()`](https://en.cppreference.com/w/cpp/numeric/midpoint). And an excellent talk to go with it here: https://www.youtube.com/watch?v=sBtAGxBh-XI"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T15:13:23.433",
"Id": "497756",
"Score": "2",
"body": "@G.Sliepen Interesting. I wasn’t aware of this function. Unfortunately, as far as I can tell, this function is actually *less efficient* than `a + (b - a) / 2` (at least the implementation shown in the talk is!) — and in this particular scenario the latter works fine. I’m actually also confused that they settled for the less efficient implementation for the `T*` overload. This looks like a QOI bug."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T12:22:03.523",
"Id": "252589",
"ParentId": "252556",
"Score": "8"
}
},
{
"body": "<p>My immediate reaction on reading this is "why is it recursive"? It has a bit of a feel for a recursive algorithm because it is divide and conquer, but there is really no need to do so here. What recursion provides is an easy way to manage the context of the intermediate parts. (For example, when sorting the array a recursive solution is good because you can solve the sub parts and then combine them, and the sub parts have distinct data that has to be managed.) But the data to be managed in binary search is trivial -- namely the lowest index of the part still being searched and the upper index of the part still being searched.</p>\n<p>Consequently, in your binary search you are paying a large cost with all those recursive calls. Remember each call requires setting up a stack frame, copying all the parameters and initializing all the variables, plus for large arrays you could potentially use a lot of stack memory. (Not likely to be a problem on regular computers, but definitely in memory limited situations.)</p>\n<p>Here is the solution given in <a href=\"https://en.wikipedia.org/wiki/Binary_search_algorithm#Procedure\" rel=\"nofollow noreferrer\">wikipedia</a>. It is, you will see, pretty straightforward. The state is managed on only two variables - L and R, the leftmost and rightmost indexes of the space still being searched. Obviously you'd have to translate it into C++, but the translation is pretty straightforward.</p>\n<pre><code>function binary_search(A, n, T) is\n L := 0\n R := n − 1\n while L ≤ R do\n m := floor((L + R) / 2)\n if A[m] < T then\n L := m + 1\n else if A[m] > T then\n R := m − 1\n else:\n return m\n return unsuccessful\n</code></pre>\n<p>You might consider a simple example as to why recursion is the wrong approach here. Consider another potentially recursive problem -- calculating factorial. Factorial(n) is defined as all the integers between 1..n multiplied together. (So obviously it only works for integers and only works for numbers >=1.) You can define factorial like this:</p>\n<pre><code>function factorial(n) is\n if n == 1 return 1;\n else return n * factorial(n-1);\n</code></pre>\n<p>Is this correct? Yes, for sure but it is a terrible solution. All those extra function calls make it very expensive. You can instead simply define it as:</p>\n<pre><code>function factorial(n) is\n int total = 1;\n for(int i=2; i<=n; i++) total *= i;\n return total;\n</code></pre>\n<p>Now in a for loop you don't have the huge cost of n function calls. This is because the function call's purpose is to store the intermediate state, and it isn't necessary. You can store it all in one variable.</p>\n<p>FWIW, both the recursive factorial and your binary search algorithms are tail recursive, so I suppose some really aggressive optimizer might make the conversion automatically for you. But I doubt a C++ compiler could ever be that aggressive since it requires a lot of deep information about function side effects that is pretty hard to gather, and risky to assume. (If you were using a pure functional language, for example, you would give it as you have written, and the tail recursion would generally be optimized away.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T07:21:54.557",
"Id": "497856",
"Score": "0",
"body": "Your factorial example actually cannot do tail recursion; it needs to modify the return value from the recursive call before it can return itself. Note that tail recursion is quite a simple optimization, most C++ compilers will happily do that. It doesn't require deep knowledge about side effects, in fact side effects are perfectly fine to have with tail recursion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T07:48:27.060",
"Id": "497860",
"Score": "0",
"body": "Thanks a lot for your answer. I'll look into it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T12:19:03.337",
"Id": "497884",
"Score": "0",
"body": "“why is it recursive?” — Because the algorithm is naturally expressed using recursion. There’s really absolutely nothing wrong with that. I don’t understand why you’re mentioning the factorial here at all. It’s completely unrelated to the question. Providing a terrible implementation is just generally not a good argument. For one, the recursive binary search is *not* terrible. For another, naturally recursive factorial implementations don’t *have* to be terrible. Yours happens to be, but a straightforward recursive implementation can have the same performance as an optimal, iterative version."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T00:18:32.727",
"Id": "252629",
"ParentId": "252556",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "252558",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T20:08:31.763",
"Id": "252556",
"Score": "6",
"Tags": [
"c++",
"algorithm",
"divide-and-conquer"
],
"Title": "Writing my first binary search by myself"
}
|
252556
|
<p>I have this following code snippet, I was wondering If I am using unnecessary If statements?</p>
<pre><code>func ReadBook(b *book) (string, error) {
bookProps, err := GetFunc1(b.name)
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
if awsErr.Code() == ResourceNotFoundException {
_, err = Create(b.name)
if err != nil {
return nil, err
}
bookProps, err = GetFunc1(b.name)
if err != nil {
return nil, err
}
} else {
return nil, err
}
} else {
return nil, err
}
}
return bookProps.name, nil
}
</code></pre>
|
[] |
[
{
"body": "<p>Yes. It's not an absolute rule but generally if you're using more than one <code>if err != nil</code> per function or more then one level of error checking in Go you should refactor.</p>\n<p>I can't test this because you didn't provide enough code to use it but here is first pass flattened version that reads more clearly:</p>\n<pre><code>func ReadBook(b *book) (string, error) {\n \n bookProps, err := GetFunc1(b.name)\n if err == nil {\n return bookProps.name, nil\n }\n\n awsErrCode, err := unpackAWSErr(err)\n if err != nil {\n return nil, err\n }\n\n // Could easily be replaced with switch{ case: } to handle different error codes\n if awsErrCode == ResourceNotFoundException {\n _, err = Create(b.name)\n if err != nil {\n return err\n }\n }\n\n bookProps, err := GetFunc1(b.name)\n if err == nil {\n return bookProps.name, nil\n }\n\n return nil, err\n}\n\n// assuming awsErr.Code() returns an int\nfunc unpackAWSErr (err error) (int, error) {\n if awsErr, ok := err.(awserr.Error); ok {\n return awsErr.Code(), nil\n }\n\n return (-1, ok)\n}\n</code></pre>\n<p>Also, I'm guessing that at some point you're going to want either rewrite your function or create a wrapper to accept a <code>func(string) (string, error)</code> in place of <code>GetFunc1()</code>. Right now that's an unmoored function floating through your code without any direct relation to the <code>book</code> type or being passed explicitly into <code>ReadBook()</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T23:04:52.407",
"Id": "252571",
"ParentId": "252559",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T21:10:23.170",
"Id": "252559",
"Score": "-2",
"Tags": [
"go"
],
"Title": "Am I using unnecessary If statements?"
}
|
252559
|
<p>So I have been tasked to make an array without duplicated values from another existing array.
So I did it, but I want to know is there some other better way to do that.</p>
<p>Example input/output:</p>
<p><code>Input</code>: <code>10, 15, 10, 5, 1, 3</code></p>
<p><code>Output</code>: <code>10, 15, 5, 1, 3</code></p>
<p>So here is my code.</p>
<pre><code>#include <stdio.h>
int main(void) {
const int MAX_ARRAY_SIZE = 5;
int m[MAX_ARRAY_SIZE], p[MAX_ARRAY_SIZE];
for(int i = 0; i < MAX_ARRAY_SIZE; i++) {
printf("Enter number: ");
scanf("%d",&m[i]);
}
int k = 0;
int dup = 0;
for(int i =0; i < MAX_ARRAY_SIZE; i++) {
for(int j = i +1; j <MAX_ARRAY_SIZE; j++) {
if(m[i] == m[j]) {
dup = 1;
}
}
if(dup != 1) {
p[k++] = m[i];
}
dup = 0;
}
printf("The new array without repeated values\n");
for(int i = 0; i < k; i++) {
printf("%d\n",p[i]);
}
return 0;
}
</code></pre>
<p>I'm not sure if this is the right and simple way I do that. I want some suggestions.</p>
<p>Thanks in advance. :)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T22:24:16.227",
"Id": "497675",
"Score": "2",
"body": "Tasked - via homework? If so, please tag this as such."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T22:24:57.027",
"Id": "497676",
"Score": "0",
"body": "@Reinderien Yes something like this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T10:59:54.767",
"Id": "497726",
"Score": "3",
"body": "Please do not vandalize your post."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T12:51:22.033",
"Id": "497736",
"Score": "1",
"body": "Does the problem require a particular order for the output? The example output shows the order preserved, keeping the first of each duplicated member, but does it allow different orderings? It probably doesn't make any difference to the reviews, but it's always good to check such requirements, and to document assumptions in the code itself."
}
] |
[
{
"body": "<h2>Early termination</h2>\n<p>After</p>\n<pre><code> dup = 1;\n</code></pre>\n<p>you should <code>break</code>. There's no need to execute the rest of the loop.</p>\n<h2>Booleans</h2>\n<p>Consider using <code><stdbool.h></code>, making <code>bool dup = false</code>, later assigning it <code>true</code>, and writing <code>if (!dup)</code>.</p>\n<h2>Complexity</h2>\n<p>In practical terms, an array of five values poses no computational cost. However, if your prof cares about complexity analysis, the "proper" solution to this would need to complete in linear time (rather than your current quadratic time), using something like a hash-set, with pseudocode:</p>\n<pre><code>Set *seen = make_set();\nfor (int i = 0; i < MAX_ARRAY_SIZE; i++)\n{\n int m;\n scanf(&m);\n if (!contains(seen, m))\n add(seen, m);\n}\n\nfor (m in seen)\n printf(m);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T22:31:59.293",
"Id": "252569",
"ParentId": "252565",
"Score": "4"
}
},
{
"body": "<p>This Q needs some dedup itself. <a href=\"https://codereview.stackexchange.com/questions/252583/remove-duplicates-from-array-and-save-it-to-another-one/252586#252586\">Remove duplicates...</a> But since this is my third version of the inner loop I take advantage of a fresh start.</p>\n<p>This inoffensive assignment\n<code>int j = i + 1;</code>, originally packed into the for-expression-list, does more than just initialize <code>j</code> for the last i: it makes <code>m[j]</code> illegal/undefined.</p>\n<p>The goal (?) is to avoid the <code>dup</code> flag and to "normalize" the loops. I think this rearrangement is worth it:</p>\n<pre><code> int j;\n for (int i = 0; i < ARRAY_SIZE; i++) {\n j = i;\n do\n if (++j == ARRAY_SIZE) { // already past end? \n p[k++] = m[i]; // copy this one\n break; // and finish\n }\n while (m[i] != m[j]); // if match, then just finish \n }\n</code></pre>\n<p>Now everything is at the natural place.</p>\n<p>I wrote <code>do statement while (expr);</code> without braces to illustrate the structure. What is a bit hidden is the loop increment <code>if (++j...</code>.</p>\n<hr />\n<p>Instead of a real (sorted) structure one can use the new unique array to search for duplicates. Because of the <code>0</code> already in the new array I first copy the first element unconditionally, and then start the loop with the second element.</p>\n<pre><code> int k = 1;\n /* First is always unique */\n printf("m[0] -> p[0]\\n");\n p[0] = m[0];\n for (int i = 1; i < ARRAY_SIZE; i++)\n for (int j = 0;; j++) {\n if (j == k) { \n printf("m[i=%d] -> p[k=%d]\\n", i, k);\n p[k++] = m[i];\n break;\n }\n if (p[j] == m[i])\n break;\n }\n</code></pre>\n<p>Still this <code>if (p[j] == m[i])</code> has to be logically after <code>if (j == k)</code>, so the for-loop has to be freestyled a bit.</p>\n<p>The <code>printf</code>s illustrate:</p>\n<pre><code>Enter number: 6\nEnter number: 6\nEnter number: 0\nEnter number: 0\nEnter number: 8\nm[0] -> p[0]\nm[i=2] -> p[k=1]\nm[i=4] -> p[k=2]\nThe array without repeated values\n6\n0\n8\n\n</code></pre>\n<p>Side effect: the order is now preserved.</p>\n<p>I guess this is a bit tricky because the searching and inserting are so closely connected. The <code>k</code> index must be handled precisely. (the other ones also)</p>\n<p><strong>Performance:</strong> I don't even know if using the new array up to k is faster than OP searching the rest of the original. It seems to amount to the same at least for some cases.</p>\n<p>Problem is the new array is not sorted. Keeping it sorted costs too much if done naively, after every insert.</p>\n<p>So one would have to "spread" out first in order to search efficiently. For (random) integers, modulo 10 can create ten different arrays - or buckets. With a 2D <code>b[][]</code> (instead of OP <code>p[]</code> )</p>\n<pre><code>b[0] {100}\nb[1] {1, 31, 20001}\nb[2] {12, 32, 502}\nb[3] {}\nb[4] {94}\n...\n</code></pre>\n<p>Every (sub)array needs the original <code>ARRAY_SIZE</code> for the worst case. But now the array to search for dups is 10 times shorter on average.</p>\n<hr />\n<p>So you could change the interactive input into a one-million-integers array generator and do some tests.</p>\n<hr />\n<p>All because of that <code>dup</code> loop flag ;)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T07:09:15.133",
"Id": "497854",
"Score": "0",
"body": "`do … while` without braces is just plain confusing. Don't suggest that to beginners."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T07:11:31.843",
"Id": "497855",
"Score": "1",
"body": "Pointing to the end of an array does not invoke undefined behavior. Only dereferencing that pointer would invoke undefined behavior"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T16:07:08.620",
"Id": "252602",
"ParentId": "252565",
"Score": "0"
}
},
{
"body": "<p>A few comments:</p>\n<ul>\n<li><p>Using printf/scanf is something like thirty years out of date. Use cin and cout instead. They are superior in almost every way -- easier to read, type safe, not prone to stack overflow, etc. etc.</p>\n</li>\n<li><p>I am sure this is controversial, since, especially among C/C++ programmers brevity seems more important than clarity, but all those single letter variable names that bear no resemblance to their purpose makes the code way harder to follow. Why not call m "withDups" and p "noDups"? It'd make it a lot clearer what you are doing. Why not call k "noDupsEnd"? I'd go so far as to change the names of i,j too since that is just confusing, but I will grant that this is standard practice in C/C++</p>\n</li>\n<li><p>So instead of i,j use a better form of forloop:</p>\n<pre><code> for(int passOne: withDups)\n {\n for(int passTwo: withDups)\n ifpassOne == passTwo)\n {\n dup = true;\n break;\n }\n if(! dup) noDups[noDupsEnd++] = withDups[passOne];\n }\n // Or something like that. My C++ is a bit out of date, but I believe that is correct.\n</code></pre>\n</li>\n</ul>\n<p>The advantage of this being that you are less likely to make dumb mistakes and the code is easier to understand.</p>\n<ul>\n<li>You could further simplify this by making the inner loop search noDups upto notDupsEnd, meaning that it'll make less passes in general.</li>\n<li>Finally, algorithmically, I think truthfully it depends on the actual underlying requirements. If you are dealing with arrays of five elements (or let's say up to 100 elements) then your solution is algorithmically fine. However, the complexity of this is potentially quadratic. This is a brute force approach. If you are going to have larger lists you need better data structures, such as a hash set, or a tree to maintain the values already in nodups. That is obviously rather more complex, but will reduce the performance complexity substantially, potentially to close linear with a good hash table, if you have lots of memory, or at least n.log(n) with a tree structure of some kind.</li>\n</ul>\n<p>For example, if you use a simple hash table (forgive, my C++ is a bit rusty) you might do something like this. Here I am using vectors which are more flexible than fixed size arrays.</p>\n<pre><code>// Return a vector containing the input vector maintaining order but removing duplicates.\n// Neither input or output vector can contain -1\nstd::vector<int> removeDups(std:vector<int> arr)\n{\n // We need a bit more space in our hash table than the original table, so this\n // multiplier gives us extra space\n const int hashTblMultiplier = 2;\n const int hashTblSize = arr.size() * hasTblMultiplier;\n // Give it a capacity to make sure it doesn't go through qaudratic copies in expansions.\n // If a vector has to auto expand then it must copy all its contents, so if the vector\n /// has too small a capacity it can drop into some nasty performance behaviors.\n const result = new std::vector<int>(size /2);\n // For this simple implementation I assume arr only has positive values. Otherwise the hash\n // table will have to be a bit more complicated.\n auto hashTable = new std:vector<int>(hashTblSize, -1);\n for(int item: arr)\n {\n // Use simple linear probing for hash collision resolution and a simple hash function\n // which assumes the input data is equally distributed.\n int hash = item % hashTblSize;\n while(hashTbl[hash] != item && hashTbl[hash] != -1)\n hash = (hash+1)%hashTblSize;\n if(hashTbl[hash] == -1)\n {\n hasTbl[hash] = item;\n result.push_back(item);\n }\n }\n return result;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T07:08:04.917",
"Id": "497852",
"Score": "1",
"body": "This question had never been tagged as c++, so the statement about printf is wrong. And, by the way, C++ streams are not superior in all cases. For i18n, printf is far better."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T03:15:24.787",
"Id": "252632",
"ParentId": "252565",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T22:09:47.437",
"Id": "252565",
"Score": "3",
"Tags": [
"algorithm",
"c",
"sorting",
"homework"
],
"Title": "Remove duplicates from array and save it to another one"
}
|
252565
|
<p>I'm working on my first real Elixir application, after dabbling for a few years. In my elixir/phoenix application I have to work with data over an external REST API. For my purposes, I can tolerate some staleness in the data so I would like to cache the data from the external system and consult the cache during request handling instead of calling out to their API for every request. So I have this plan to write one module which connects to the API, and then access it through a caching proxy module, which uses <a href="https://hex.pm/packages/cachex" rel="nofollow noreferrer">Cachex</a> to cache return results for some small amount of time. This is the proxy module:</p>
<pre><code>defmodule MyApp.SlowApiCache do
alias MyApp.SlowApi
Code.ensure_compiled(SlowApi)
for {func, arity} <- SlowApi.__info__(:functions) do
args = Macro.generate_arguments(arity, __MODULE__)
def unquote(func)(unquote_splicing(args)) do
cache_key = {unquote(func), unquote_splicing(args)}
Cachex.fetch!(:slow_api_cache, cache_key, fn ->
SlowApi.unquote(func)(unquote_splicing(args))
end)
end
end
end
</code></pre>
<p>So it simply generates a matching function for each function in the wrapped module and when the cache misses then it passes it on to the real API module. In my code I write the data pulling functions in the <code>MyApp.SlowApi</code> module but in the rest of the program I access those functions through the <code>MyApp.SlowApiCache</code> functions instead.</p>
<p>Does this make sense or am I shooting myself in the foot somehow? Is this going to have issues in production? Is this kind of thing idiomatic in Elixir?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T22:28:14.333",
"Id": "252568",
"Score": "1",
"Tags": [
"cache",
"meta-programming",
"elixir"
],
"Title": "Metaprogamming elixir for module proxy"
}
|
252568
|
<p>I'm writing a piece table library in Rust with the structures:</p>
<pre class="lang-rust prettyprint-override"><code>#[derive(Default)]
struct Piece {
additional: bool,
offset: usize,
length: usize,
}
</code></pre>
<p>and</p>
<pre class="lang-rust prettyprint-override"><code>/// PieceTable contains the additional, original buffers and a vector of pieces.
/// It also maintains a length variable.
pub struct PieceTable {
table: VecDeque<Piece>,
orig_buffer: String,
add_buffer: String,
length: usize,
}
</code></pre>
<p>I'm fairly confident that I didn't mess anything up here, though I'm not sure if VecDeque is the best structure to hold the pieces. My insert method is:</p>
<pre class="lang-rust prettyprint-override"><code>impl PieceTable {
...
pub fn insert(&mut self, index: usize, text: &string) {
match self.piece_at(index + 1) {
Ok((index, offset)) => {
// isolate piece being inserted into
let into = &self.table[index];
// create necessary Pieces to enter
let previous = Piece {
additional: into.additional,
offset: into.offset,
length: offset - into.offset,
};
let insert = Piece {
additional: true,
offset: self.add_buffer.len(),
length: text.len(),
};
let next = Piece {
additional: into.additional,
offset: offset,
length: into.length - (offset - into.offset),
};
// remove index, add in previous, insert, next
self.table.remove(index);
self.table.insert(index, previous);
self.table.insert(index + 1, insert);
self.table.insert(index + 2, next);
// update buffer, length vars
self.add_buffer.push_str(text);
self.length += text.len();
}
Err(_) => self.push_str(text),
}
}
}
</code></pre>
<p>Which refers to the <code>piece_at</code> method:</p>
<pre class="lang-rust prettyprint-override"><code>fn piece_at(&self, index: usize) -> Result<(usize, usize>, i32> {
if index > self.length {
return Err(-1);
}
let mut remaining = index.clone();
for (i, piece) in self.table.iter().enumerate() {
if remaining <= piece.length {
return Ok((i, remaining));
}
remaining -= piece.length;
}
return Err(-1);
}
</code></pre>
<p>It also relies on the push_str method, which is just appends a piece with the proper parameters to the end of <code>self.table</code>.</p>
<p>This algorithm is stolen basically verbatim from the python implementation at <a href="https://github.com/saiguy3/piece_table" rel="nofollow noreferrer">https://github.com/saiguy3/piece_table</a>, so hopefully there's nothing terribly wrong with it that I missed. Rust is hard and I started learning it yesterday, so I'm fully expecting I horribly misused some language feature.</p>
<p>Thanks!</p>
|
[] |
[
{
"body": "<p>Keep in mind that there already exist rope structure implementations in Rust, which support utf8, for example <code>an_rope</code>, where your <code>PieceTable::insert</code> is <code>Rope::insert_str</code>: <a href=\"https://docs.rs/an-rope/0.3.1/an_rope/struct.Rope.html#method.insert_str\" rel=\"nofollow noreferrer\">https://docs.rs/an-rope/0.3.1/an_rope/struct.Rope.html#method.insert_str</a></p>\n<p>Your code is really good for someone who just started learning, and nothing stands out as a misuse of language.</p>\n<p>Why is <code>index + 1</code> passed to <code>piece_at</code>, not simply <code>index</code>?</p>\n<p>Using <code>VecDeque</code> does give a little potential for speedup in random insertion and removal. Although if I was doing a program like this, my choice of the data structure would be different - I'd use <code>BTreeSet<Piece></code> instead, and order the <code>Piece</code>s by <code>piece.offset</code>.</p>\n<p>You may write a removal and an insert at the same index as a single <code>[]</code> <code>=</code> instead.</p>\n<p>About <code>Copy</code>/<code>Clone</code>:</p>\n<ul>\n<li>if your <code>Piece</code> derived <code>Copy</code>, the <code>&</code> in <code>&self.table[index]</code> could be omitted. Did you try compiling this code? Can it compile without errors? I doubt it since the immutable borrow with <code>&</code> will prevent you from removal and insertion later on.</li>\n<li>the <code>.clone()</code> in <code>piece_at</code> can be omitted, because <code>piece: usize</code> is Plain Old Data that is copied around with zero overhead (in syntax and in performance as well).</li>\n</ul>\n<p>There are two tiny misspellings</p>\n<ul>\n<li><code>text: &string</code> instead of <code>text: &str</code></li>\n<li><code>(usize,usize>,</code> instead of <code>(usize,usize)>,</code></li>\n</ul>\n<p>I'd change the <code>Err(-1)</code> return to carry the unit value instead as we don't need the <code>i32</code> to signal anything. We return <code>Err(())</code> there.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T11:47:54.523",
"Id": "252749",
"ParentId": "252572",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "252749",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T23:30:02.637",
"Id": "252572",
"Score": "1",
"Tags": [
"strings",
"rust"
],
"Title": "Rust - insert into piecetable"
}
|
252572
|
<h3>Background:</h3>
<p>I have close to 50 excel files - I cannot change the data source - and I steadily get more.<br />
My task is to make sense of all that data and, lo an behold, save that as another excel file (I asked if I should put it in a local database, but no, I should not).</p>
<p><em>Asking on SO lead me here, as I thought it might be a better fit here, but my problem, if it even is one, is quite specific.</em></p>
<hr />
<h3>Code:</h3>
<p>In my current code I used a couple of classes to model the data; I read somewhere that data should be data and not a class but are dictionaries helpful in this case?</p>
<p>Assembly Class:</p>
<pre class="lang-vb prettyprint-override"><code>Private pPartnumber As String
Private pDescription As String
Private pLevel As Long
Private pSupplier As Supplier
Private pCustomers As CustomerCollection
Private pSubAssemblies As AssemblyCollection
Private pWarehouse As String
Private pEligibility As String
Private pApprovedData As String
Private pApprovedDataBasedOn As String
Private BuyOrMake As AssemblyBuyMake
Public Enum AssemblyBuyMake
Buy = 0
Make = 1
Both = 2
Other = 4
End Enum
' Lots of getters and setters
' removed for conciseness
Private Sub SetEligibilityOfSubAssemblies(ByVal Value As String)
Dim subAssembly As Assembly
If Not pSubAssemblies Is Nothing Then
For Each subAssembly In pSubAssemblies
subAssembly.Eligibility = Value
Next
End If
End Sub
Private Sub SetApprovedDataOfSubAssemblies(ByVal Value As String)
Dim subAssembly As Assembly
If Not pSubAssemblies Is Nothing Then
For Each subAssembly In pSubAssemblies
subAssembly.ApprovedData = Value
Next
End If
End Sub
'@Description "Checks if Partnumbers are equal, ignores Description- and other deviations"
Public Function Equals(ByVal Assembly As Assembly) As Boolean
Equals = (pPartnumber = Assembly.Partnumber)
End Function
</code></pre>
<p>As you can see my class has lots of fields; the two setter subs are private as any Subassembly automatically inherits the Topassembly's ApprovedData and Eligibility as per requirement.</p>
<p>AssemblyCollection:</p>
<pre class="lang-vb prettyprint-override"><code>Private pAssemblyCollection As Collection
Private Sub Class_Initialize()
Set pAssemblyCollection = New Collection
End Sub
Public Sub Add(ByVal Value As Assembly, Optional ByVal Key As String)
'
End Sub
Public Sub Remove(Optional ByVal Value As Assembly, Optional ByVal Key As String)
'
End Sub
'@DefaultMember
Public Function Item(Optional ByVal index As Long = -1, Optional ByVal Key As String) As Assembly
'
End Function
'@MemberAttribute VB_MemberFlags, "40"
'@Enumerator
Public Property Get NewEnum() As IUnknown
Set NewEnum = pAssemblyCollection.[_NewEnum]
End Property
</code></pre>
<p>The <code>CustomerCollection</code> looks the same.</p>
<p>Customer:</p>
<pre class="lang-vb prettyprint-override"><code>Private pName As String
Private pID As String
Private pCountry As String
Private pHTSCode As String
' And its getters and setters
'@Description "Returns True if Name, ID and HTSCode are the same"
Public Function Equals(ByVal Customer As Customer) As Boolean
Equals = (pName = Customer.Name And pID = Customer.ID And pHTSCode = Customer.HTSCode)
End Function
</code></pre>
<p>The <code>HTSCode</code> is currently part of the <code>Customer</code> as the file I found it in contains Customer and sales data and barely enough assembly data to identify an assembly - think "customer has a partnumber for an assembly and my files have a partnumber which don't match" and you are just supposed to know which ones refer to the same assembly.</p>
<hr />
<h3>Question:</h3>
<p>Instead of using these classes should I use dictionaries of dictionaries?
And for comparing data of different sheets should I store either these classes or dictionaries with the data in new dictionaries or arrays?
I'm not sure if there's a maximum on how many custom objects I can create (other than memory limits), but I fear I'll end up with a lot of <code>Assembly</code> instances in this case.</p>
<p><em>Currently I</em></p>
<pre class="lang-vb prettyprint-override"><code>Dim arr() As Assembly
</code></pre>
<p><em>to collect all the data before parsing it to a sheet.</em></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T09:16:44.470",
"Id": "497714",
"Score": "2",
"body": "In VBA, collection objects (collections, array lists, scripting.dictionaries) don't restrict the type of data used as a key or value as they are based on the Variant datatype under the hood. A good practice in VBA is to wrap a collection object so that the getters and setters specify the Type that is being used and allows the compiler to detect when you are using a collection object in the wrong way. So for VBA encapsulating data in a collection object is a good way to store data and probably the way you should wish to go."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T19:14:02.093",
"Id": "510381",
"Score": "0",
"body": "Can't help wondering if Power Query might be a better approach to this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T18:07:19.163",
"Id": "510911",
"Score": "0",
"body": "@androo235 not sure how PowerQuery would be a solution. I ended up with almost 90 files with different layouts. But I worked very little with PowerQuery, tbh"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T23:40:03.617",
"Id": "252573",
"Score": "3",
"Tags": [
"object-oriented",
"vba",
"excel",
"hash-map"
],
"Title": "Modeling data from Excel sheets to parse to Excel sheet"
}
|
252573
|
<p>I just finished writing an ncurses-based Tetris clone in C. It's only my second project of this size, the first being a Snake clone. I would really appreciate any and all suggestions/improvements as I'm relatively new to C and I would like to improve.</p>
<p>As this is a 300-plus-line codebase, anything I can add to this question to more easily facilitate its review, I will.</p>
<p><code>main.c</code>:</p>
<pre class="lang-c prettyprint-override"><code>#include "game.h"
#include "ncurses_util.h"
#include <ncurses.h>
#include <unistd.h>
int main(void) {
ncurses_init();
curs_set(0); // Invisible cursor
draw_game_board();
int ch;
enum Direction dir;
while ((ch = getch())) {
switch (ch) {
case KEY_DOWN: dir = Down; break;
case KEY_UP: dir = Up; break;
case KEY_LEFT: dir = Left; break;
case KEY_RIGHT: dir = Right; break;
default: dir = None; break;
}
update_game(dir);
usleep(20000); // 50FPS
}
}
</code></pre>
<p><code>game.h</code>:</p>
<pre class="lang-c prettyprint-override"><code>#ifndef TETRIS_GAME_H
#define TETRIS_GAME_H
#define BOARD_WIDTH 10
#define BOARD_HEIGHT 12
enum Direction { Up, Down, Left, Right, None };
struct Coords {
int y;
int x;
};
void draw_game_board();
void update_game(enum Direction press);
#endif /* TETRIS_GAME_H */
</code></pre>
<p><code>game.c</code>:</p>
<pre class="lang-c prettyprint-override"><code>#include "game.h"
#include "ncurses_util.h"
#include <ncurses.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
enum Piece { T, S, Z, L, J, O, I };
const struct Coords pieces[7][4] = {
{ { 1, 4 }, { 2, 5 }, { 1, 6 }, { 1, 5 } }, // T
{ { 2, 5 }, { 1, 6 }, { 2, 4 }, { 1, 5 } }, // S
{ { 1, 4 }, { 2, 6 }, { 2, 5 }, { 1, 5 } }, // Z
{ { 1, 6 }, { 2, 4 }, { 2, 6 }, { 2, 5 } }, // L
{ { 1, 4 }, { 2, 4 }, { 2, 6 }, { 2, 5 } }, // J
{ { 1, 5 }, { 1, 6 }, { 2, 5 }, { 2, 6 } }, // O
{ { 1, 4 }, { 1, 5 }, { 1, 6 }, { 1, 7 } }, // I
};
int tetris_check() {
static char *fullLine;
static char *emptyLine;
if (!fullLine) {
fullLine = malloc(sizeof(char) * (BOARD_WIDTH + 1));
emptyLine = malloc(sizeof(char) * (BOARD_WIDTH + 1));
for (int i = 0; i < BOARD_WIDTH; i++) {
fullLine[i] = '#';
emptyLine[i] = ' ';
}
fullLine[BOARD_WIDTH] = '\0';
emptyLine[BOARD_WIDTH] = '\0';
}
int tetrises = 0;
char *line = malloc(sizeof(char) * (BOARD_WIDTH + 1));
for (int i = 1; i <= BOARD_HEIGHT; i++) {
mvinnstr(i, 1, line, BOARD_WIDTH);
if (strcmp(line, fullLine) == 0) {
mvaddstr(i, 1, emptyLine);
tetrises++;
}
}
int dropAmount = 0;
for (int i = BOARD_HEIGHT + 1; i >= 1; i--) {
mvinnstr(i, 1, line, BOARD_WIDTH);
if (strcmp(line, emptyLine) == 0) {
dropAmount++;
} else {
mvaddstr(i + dropAmount, 1, line);
if (dropAmount) {
mvaddstr(i, 1, emptyLine);
}
}
}
return tetrises;
}
void rotate_piece(struct Coords *originalPiece, enum Piece pieceType) {
if (pieceType == O) return; // No point in rotating an O
struct Coords piece[4];
memcpy(piece, originalPiece, sizeof(struct Coords) * 4);
if (pieceType == I) {
if (piece[0].x == piece[1].x) { // Horizontal
for (int i = 0; i < 4; i++) {
if (i == 1) continue;
piece[i].x = piece[1].x + (piece[i].y - piece[1].y);
piece[i].y = piece[1].y;
}
} else { // Vertical
for (int i = 0; i < 4; i++) {
if (i == 1) continue;
piece[i].y = piece[1].y + (piece[i].x - piece[1].x);
piece[i].x = piece[1].x;
}
}
} else {
// The last coordinate pair always corresponds to the "center" of a non-I/O piece
for (int i = 0; i < 3; i++) {
if (piece[i].x == piece[3].x && piece[i].y == piece[3].y - 1) {
piece[i].x += 1;
piece[i].y += 1;
} else if (piece[i].x == piece[3].x && piece[i].y == piece[3].y + 1) {
piece[i].x -= 1;
piece[i].y -= 1;
} else if (piece[i].x == piece[3].x - 1 && piece[i].y == piece[3].y) {
piece[i].x += 1;
piece[i].y -= 1;
} else if (piece[i].x == piece[3].x + 1 && piece[i].y == piece[3].y) {
piece[i].x -= 1;
piece[i].y += 1;
} else if (piece[i].x == piece[3].x - 1 && piece[i].y == piece[3].y - 1) {
piece[i].x += 2;
} else if (piece[i].x == piece[3].x + 1 && piece[i].y == piece[3].y - 1) {
piece[i].y += 2;
} else if (piece[i].x == piece[3].x + 1 && piece[i].y == piece[3].y + 1) {
piece[i].x -= 2;
} else if (piece[i].x == piece[3].x - 1 && piece[i].y == piece[3].y + 1) {
piece[i].y -= 2;
}
}
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (piece[i].x == originalPiece[j].x && piece[i].y == originalPiece[j].y) {
goto ROTATE_PIECE_OUTER_CONTINUE;
}
}
chtype ch = mvinch(piece[i].y, piece[i].x);
if (ch == '#' || ch == L'│' || ch == L'▁' || ch == L'▔') return;
ROTATE_PIECE_OUTER_CONTINUE:
continue;
}
for (int i = 0; i < 4; i++) {
mvaddch(originalPiece[i].y, originalPiece[i].x, ' ');
}
for (int i = 0; i < 4; i++) {
mvaddch(piece[i].y, piece[i].x, '#');
}
refresh();
memcpy(originalPiece, piece, sizeof(struct Coords) * 4);
}
bool update_piece_on_screen(struct Coords *piece, enum Direction dir) {
switch (dir) {
case Down:
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (i == j) continue;
if (piece[i].x == piece[j].x && piece[i].y == piece[j].y - 1) goto UPDATE_PIECE_DOWN_CONTINUE;
}
chtype adjCh = mvinch(piece[i].y + 1, piece[i].x);
if (adjCh == '#' || adjCh == L'▔') return false;
UPDATE_PIECE_DOWN_CONTINUE:
continue;
}
for (int i = 0; i < 4; i++) {
mvaddch(piece[i].y, piece[i].x, ' ');
piece[i].y++;
}
for (int i = 0; i < 4; i++) {
mvaddch(piece[i].y, piece[i].x, '#');
}
break;
case Left:
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (i == j) continue;
if (piece[i].y == piece[j].y && piece[i].x == piece[j].x + 1) goto UPDATE_PIECE_LEFT_CONTINUE;
}
chtype adjCh = mvinch(piece[i].y, piece[i].x - 1);
if (adjCh == '#' || adjCh == L'│') return false;
UPDATE_PIECE_LEFT_CONTINUE:
continue;
}
for (int i = 0; i < 4; i++) {
mvaddch(piece[i].y, piece[i].x, ' ');
piece[i].x--;
}
for (int i = 0; i < 4; i++) {
mvaddch(piece[i].y, piece[i].x, '#');
}
break;
case Right:
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (i == j) continue;
if (piece[i].y == piece[j].y && piece[i].x == piece[j].x - 1) goto UPDATE_PIECE_RIGHT_CONTINUE;
}
chtype adjCh = mvinch(piece[i].y, piece[i].x + 1);
if (adjCh == '#' || adjCh == L'│') return false;
UPDATE_PIECE_RIGHT_CONTINUE:
continue;
}
for (int i = 0; i < 4; i++) {
mvaddch(piece[i].y, piece[i].x, ' ');
piece[i].x++;
}
for (int i = 0; i < 4; i++) {
mvaddch(piece[i].y, piece[i].x, '#');
}
break;
default: break;
}
return true;
}
int add_new_piece() {
int piece = 6; // rand() % 7;
for (int i = 0; i < 4; i++) {
if (mvinch(pieces[piece][i].y, pieces[piece][i].x) == '#') return -1;
mvaddch(pieces[piece][i].y, pieces[piece][i].x, '#');
}
return piece;
}
void draw_game_board() {
// mvaddstr is used in place of mvaddch for wide characters because macOS's ncurses is broken
mvaddch(0, 0, ' ');
for (int x = 1; x <= BOARD_WIDTH; x++) {
mvaddstr(0, x, "▁");
}
mvaddch(0, BOARD_WIDTH + 1, ' ');
for (int y = 1; y <= BOARD_HEIGHT; y++) {
mvaddstr(y, 0, "│");
for (int x = 1; x <= BOARD_WIDTH; x++) {
mvaddch(y, x, ' ');
}
mvaddstr(y, BOARD_WIDTH + 1, "│");
}
mvaddch(BOARD_HEIGHT + 1, 0, ' ');
for (int x = 1; x <= BOARD_WIDTH; x++) {
mvaddstr(BOARD_HEIGHT + 1, x, "▔");
}
mvaddch(BOARD_HEIGHT + 1, BOARD_WIDTH + 1, ' ');
refresh();
}
void update_game(enum Direction press) {
static int downTimer = 0;
static struct Coords *piece;
static enum Piece pieceType;
if (!piece) {
piece = malloc(sizeof(struct Coords *) * 4);
srand(time(NULL));
rand();
pieceType = add_new_piece();
memcpy(piece, pieces[pieceType], sizeof(struct Coords) * 4);
}
switch (press) {
case Up: rotate_piece(piece, pieceType); break;
case Left:
case Right: update_piece_on_screen(piece, press); break;
case Down: goto MOVE_DOWN;
case None: break;
}
downTimer++;
if (downTimer >= 50) {
MOVE_DOWN:
downTimer = 0;
if (!update_piece_on_screen(piece, Down)) {
tetris_check();
pieceType = add_new_piece();
if (pieceType == -1) { // Game over
ncurses_deinit();
printf("%s\n", "Game over");
exit(0);
}
memcpy(piece, pieces[pieceType], sizeof(struct Coords) * 4);
for (int i = 0; i < 4; i++) {
mvaddch(piece[i].y, piece[i].x, '#');
}
}
}
refresh();
}
</code></pre>
<p><code>ncurses_util.h</code>:</p>
<pre class="lang-c prettyprint-override"><code>#ifndef TETRIS_NCURSES_UTIL_H
#define TETRIS_NCURSES_UTIL_H
void ncurses_init();
void ncurses_deinit();
void ncurses_should_exit(int signalValue);
#endif /* TETRIS_NCURSES_UTIL_H */
</code></pre>
<p><code>ncurses_util.c</code>:</p>
<pre class="lang-c prettyprint-override"><code>#include "ncurses_util.h"
#include <locale.h>
#include <ncurses.h>
#include <signal.h>
#include <stdlib.h>
void ncurses_init() {
// Default cleanup for ^C, etc.
signal(SIGINT, ncurses_should_exit);
signal(SIGTERM, ncurses_should_exit);
signal(SIGQUIT, ncurses_should_exit);
setlocale(LC_ALL, "");
initscr();
start_color();
use_default_colors();
cbreak();
nodelay(stdscr, TRUE);
keypad(stdscr, TRUE);
noecho();
}
void ncurses_deinit() {
endwin();
}
void ncurses_should_exit(int signalValue) {
ncurses_deinit();
exit(128 + signalValue);
}
</code></pre>
<p>Some of the aspects I'm most interested in:</p>
<ul>
<li>I use <code>goto</code> in several places to escape nested loops. Is this use acceptable, or is there a cleaner way to do this?</li>
<li>Are there any (common) mistakes that I've made?</li>
<li>My comments are relatively sparse; is this OK or should I comment more thoroughly?</li>
<li>Is my code generally readable/understandable?</li>
</ul>
<p><em>For this code to properly function on macOS, you must compile it with</em> <code>-D_XOPEN_SOURCE_EXTENDED -lncurses</code><em>. On Linux, you must compile it with</em> <code>-lncursesw</code><em>. This is due to its usage of wide characters.</em></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T03:57:26.863",
"Id": "497693",
"Score": "1",
"body": "Code copied into the body of the question is required, please."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T04:02:27.080",
"Id": "497694",
"Score": "0",
"body": "@Reinderien Thanks for letting me know; I added the code to the question body."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T07:36:32.947",
"Id": "497857",
"Score": "1",
"body": "The only thing I can say is that your coding style and indention is too messy and inconsistent for me to even bother reading the code. `update_piece_on_screen` is for example some serious spaghetti code, add the lack of new line after each if statement and it turns completely unreadable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T07:40:24.523",
"Id": "497858",
"Score": "0",
"body": "@Lundin The lack of newlines after non-braced `if`s is a formatting choice that I prefer; I have it set this way in my `clang-format` rules and what I've read online indicates that (the lack of) a newline there is up to preference. Would you mind explaining what about my coding style and indentation are messy/inconsistent?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T07:55:38.577",
"Id": "497861",
"Score": "0",
"body": "It is simply not commonly used style at all, so to someone who is used at reading a whole lot of code written with common code styles, it becomes very difficult to read. Particularly without a new line after statement - if I see `if(something)` then I expect that the code on the next line after `if` belongs to the `if`. Not some completely unrelated code. Also, your switch formatting is weird, but that's a minor remark."
}
] |
[
{
"body": "<h2>Assignment-in-expression</h2>\n<p>Whereas this -</p>\n<pre><code>while ((ch = getch()))\n</code></pre>\n<p>is a "common" paradigm in C, that doesn't mean it's a great idea. You're better-served by splitting it into separate assignment and condition-check statements.</p>\n<h2>Helpful constants</h2>\n<p>It's good that you wrote a comment here:</p>\n<pre><code>usleep(20000); // 50FPS\n</code></pre>\n<p>it would be even nicer if you had constants that derive this programatically, i.e.</p>\n<pre><code>#define FRAME_RATE 50\n#define FRAME_TIME_US (1000000 / FRAME_RATE)\n</code></pre>\n<p>or equivalent <code>const</code> declarations.</p>\n<h2><code>typedef</code>s</h2>\n<p>It's generally more usable to add utility <code>typedef</code>s to your <code>enum</code> and <code>struct</code> declarations so that you can (for example) drop the <code>enum</code> in</p>\n<pre><code>enum Direction dir;\n</code></pre>\n<h2>State management</h2>\n<p>The way you manage state is interesting. The state of the game is (from what I can tell) entirely represented in your display term buffer. That's not crazy, but it's a measure toward a level of efficiency that in this context is really not necessary, and harms your application in other categories.</p>\n<p>What if you wanted to play a "headless" game? What if you wanted to run unit tests in the absence of a real terminal? What if you have a real terminal, but you want to quickly page between different game instances? Your current implementation makes all of these very difficult.</p>\n<p>Consider prying apart your application layer from your presentation layer. Rather than representing the game state as display character data, represent it as the best "logical" two-dimensional array of booleans, or maybe bitfields if you want to be fancy. Also, eliminate statics such as</p>\n<pre><code>static char *fullLine;\nstatic char *emptyLine;\n</code></pre>\n<p>with prejudice. They will introduce surprising side-effects for anyone attempting to use your code in a re-entrant manner.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T18:13:35.480",
"Id": "497784",
"Score": "0",
"body": "Thank you so much! I had a few clarifying questions (I'm not doubting anything you said; I just would like to understand better): 1. You mention that assignment in the `while` condition isn't the best idea. What's the reason for this? 2. For `fullLine`, I wasn't sure how to handle representing that once I refactored to allow a variable-sized game board. What would be a better way of doing that? If I could use a `#define` I would. 3. For the other statics, I figured that it'd be OK to use them to store the game state since they'd be polled/modified on each call anyway. Would globals be better?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T18:43:39.513",
"Id": "497785",
"Score": "1",
"body": "1. Clarity and vulnerability to human error. Writing it as you have doesn't make a performance difference to any optimizing compiler; the issue is that you're doing two things at once, and one of the things has a side-effect."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T18:50:10.367",
"Id": "497786",
"Score": "1",
"body": "2. I don't think you need `fullLine` in memory at all. For the comparison, use a simple `==` within a loop; and for output of a full line you can use one of the `ncurses` window-based functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T18:51:04.513",
"Id": "497787",
"Score": "1",
"body": "_Would globals be better?_ Nope. Consider making a `struct` to represent your game state and passing it around to functions that need it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T19:12:37.960",
"Id": "497788",
"Score": "1",
"body": "Thanks for elaborating. I really do appreciate it. "
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T17:47:01.900",
"Id": "252607",
"ParentId": "252574",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "252607",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T02:45:13.343",
"Id": "252574",
"Score": "1",
"Tags": [
"c",
"game",
"tetris",
"curses"
],
"Title": "Tetris clone in C"
}
|
252574
|
<p>Link to problem: <a href="https://www.codewars.com/kata/5539fecef69c483c5a000015/train/powershell" rel="nofollow noreferrer">https://www.codewars.com/kata/5539fecef69c483c5a000015/train/powershell</a></p>
<p>I have a working solution in Codewars but my solution is slow for some reason and<br/> I need to improve the efficiency.</p>
<p>Please look over my solution and offer any suggestions on things I could do to <br/>improve what I have.</p>
<h2>Instructions for problem:</h2>
<p>Backwards Read Primes are primes that when read backwards in base 10 (from right<br/>to left) are a different prime. (This rules out primes which are palindromes.)</p>
<p>Examples:
13 17 31 37 71 73 are Backwards Read Primes
13 is such because it's prime and read from right to left writes 31 which is prime too. Same for the others.</p>
<p>Task
Find all Backwards Read Primes between two positive given numbers (both inclusive), the second one always being greater than or equal to the first one. The resulting array or the resulting string will be ordered following the natural order of the prime numbers.</p>
<p>Example
backwardsPrime(2, 100) => [13, 17, 31, 37, 71, 73, 79, 97] backwardsPrime(9900, 10000) => [9923, 9931, 9941, 9967] backwardsPrime(501, 599) => []</p>
<p>Note for Forth
Return only the first backwards-read prime between start and end or 0 if you don't find any</p>
<p>Don't use Ruby Prime class, it's disabled.
backwardsPrime(2, 100) => [13, 17, 31, 37, 71, 73, 79, 97]
backwardsPrime(9900, 10000) => [9923, 9931, 9941, 9967]</p>
<p>Thanks.</p>
<pre class="lang-js prettyprint-override"><code>
$primes = @{ 2 = 2; 3 = 3; 5 = 5; 7 = 7; 11 = 11; 13 = 13; 17 = 17; 31 = 31; 37 = 37; 71 = 71; 73 = 73; 79 = 79; 97 = 97; 107 = 107; 113 = 113; 149 = 149; 157 = 157; 167 = 167; 179 = 179; 199 = 199 };
function backwards-prime($start, $stop)
{
function revNum ([int] $n) {
$numStr = $n.ToString();
return ($numStr[-1..-($numStr.Length)] -join "") -as [int];
}
function isPrime ($num) {
if ($primes.containsKey($num)) {
return $true;
}
if ($num -lt 3) {
return $num -gt 1;
}
if ($num % 2 -eq 0 -or $num % 3 -eq 0) {
return $false;
}
$i = 5;
while ($i * $i -le $num) {
if ($num % $i -eq 0 -or $num % ($i + 2) -eq 0) {
return $false;
}
$i += 6;
}
$primes[$num.ToString()] = $num;
return $true;
}
$res = @();
if($start % 2 -eq 0) { $start = $start + 1; }
if($stop % 2 -eq 0) { $stop = $stop - 1; }
for ($i = $start; $i -le $stop; $i += 2) {
$nPrime = isPrime $i;
$nReversed = revNum $i;
$nPrimeReverse = isPrime $nReversed;
if ($nPrime -and $nPrimeReverse -and $i -ne $nReversed -and $i -ge 13) {
$res += $i;
}
}
return ($res -join ", ").Trim();
}
</code></pre>
|
[] |
[
{
"body": "<p>Update: Later this night after I asked my question I continued to think of ways I could have improved the performance of my solution. I made some refactors that I'm going to share which gave me enough boost to beat the time requirement for this problem.</p>\n<p>But please continue to post your answers, I'm here to learn as well. And any new nugget of efficiency I can add or look at is still super valuable to me.</p>\n<p>Thanks in advance...</p>\n<p>So the fist changes I made even though a bit small was</p>\n<p>I removed the .ToString() to my $num in my isPrime function, I realized that it was not even needed, and yes that's a small change but every bit helps in this case...</p>\n<p>The update isPrime function below...</p>\n<pre class=\"lang-php prettyprint-override\"><code>\n function isPrime ($num) {\n\n if ($primes.containsKey($num)) {\n return $true;\n }\n\n if ($num -lt 3) {\n return $num -gt 1;\n }\n\n if ($num % 2 -eq 0 -or $num % 3 -eq 0) {\n return $false;\n }\n\n $i = 5;\n\n while ($i * $i -le $num) {\n if ($num % $i -eq 0 -or $num % ($i + 2) -eq 0) {\n return $false; \n }\n\n $i += 6;\n }\n\n $primes[$num] = $num; # removed the .ToString() here... very small optimization but it all matters I guess.\n\n return $true;\n }\n\n</code></pre>\n<p>Next I went to the for-loop and realized that I was doing 2 isPrime calls and a reverse number call as well... It dawned on me that I could easily just declare and assign $nPrime variable and then check if it's false then no need to continue and just go to the next iteration, same with $nPrimeReverse. But before that I would call revNum and test if $nReversed is equal to $i if it is, then also I would call continue and start the next iteration. Then finally I just add a check at the start determining if $i is greater than 13.</p>\n<p>Here is the updated for-loop:</p>\n<pre class=\"lang-php prettyprint-override\"><code>\n for ($i = $start; $i -le $stop; $i += 2) {\n \n if ($i -lt 13) { continue; }\n \n $nPrime = isPrime $i;\n \n if ($nPrime -eq $false) { continue; }\n \n $nReversed = revNum $i;\n \n if ($nReversed -eq $i) { continue; }\n \n $nPrimeReverse = isPrime $nReversed;\n \n if ($nPrimeReverse -eq $false) { continue; }\n\n $res += $i;\n }\n\n</code></pre>\n<p>After all these small changes my solution passed within the time constraint.</p>\n<p>Please feel free to comment any additional items that I could refactor and improve.</p>\n<p>Warm Regards</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T07:56:06.973",
"Id": "252579",
"ParentId": "252575",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "252579",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T03:52:08.457",
"Id": "252575",
"Score": "1",
"Tags": [
"performance",
"algorithm",
"mathematics",
"powershell"
],
"Title": "\"Backwards Read Primes\" of Codewars powershell version"
}
|
252575
|
<p>Im trying to get more grip of Classes and also calling different classes to each other which will be more understandable when showing code before:</p>
<p><strong>Utils.py</strong></p>
<pre class="lang-py prettyprint-override"><code>from proxymanager import ProxyManager # https://pypi.org/project/proxy-manager/
class ProxyServer:
def __init__(self):
self.proxy_manager_test = ProxyManager('./test.txt')
self.proxy_manager_test2 = ProxyManager('./test2.txt')
self.proxy_manager_test3 = ProxyManager('./test3.txt')
self.proxy_manager_test4 = ProxyManager('./test4.txt')
def hello(self):
return self.proxy_manager_test.random_proxy().get_dict()
def world(self):
return self.proxy_manager_test2.random_proxy().get_dict()
def hey(self):
return self.proxy_manager_test3.random_proxy().get_dict()
def yes(self):
return self.proxy_manager_test4.random_proxy().get_dict()
class Testing:
def GetData(self, value=None):
if value:
dataSaved = getattr(ProxyServer(), value)() # <--- Technically works but is it correct way to do it?
print(dataSaved)
</code></pre>
<p><strong>Main.py</strong></p>
<pre class="lang-py prettyprint-override"><code>
import random
import time
from .utils import Testing
scraper = Testing()
randomList = ["hello", "world", "hey", "yes"]
while True:
response = scraper.GetData(
value=random.choice(randomList)
)
time.sleep(10)
</code></pre>
<p>My concern is the <code>dataSaved = getattr(ProxyServer(), value)()</code> which seem to work as expected but i'm not sure if its correct way to do it, I did get some review about it but the answer I got was that it will technically work but its wrong to do it this way and I want a second opinion from you guys, Is it actually wrong doing it this way?</p>
<p>And please, let me know if I am missing anything else here to provide missing information :)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T19:26:44.997",
"Id": "497797",
"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)*. Consider waiting till a full day has past and posting a follow-up question instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T19:29:33.107",
"Id": "497799",
"Score": "1",
"body": "@Mast Woops im sorry! It is my fault, I was not able to find documenation about if it is ok to add additional code in my question (At the very bottom) based from Grajdeanu Alex. answer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T19:33:35.793",
"Id": "497802",
"Score": "1",
"body": "No, consider asking a follow-up question as stated in my previous comment. Feel free to add a link to both this and the new question to the other one for bonus context. Don't touch the code."
}
] |
[
{
"body": "<p>I think you've over-engineered the code a bit. If I were to write this code I wouldn't have used a class at all. Looking at what your code does I understand that:</p>\n<ul>\n<li>you have multiple proxies files</li>\n<li>you randomly choose one of them and perform whatever actions based on that</li>\n</ul>\n<p>Why not just doing something along the following lines:</p>\n<pre><code>import random\nimport time\n\nfrom proxymanager import ProxyManager\n\n\nPROXY_FILES = (\n './test.txt',\n './test2.txt',\n './test3.txt',\n './test4.txt',\n)\nDELAY = 10\n\n\ndef get_random_proxy():\n """\n Return a random proxy dict from a random file.\n """\n random_file = random.choice(PROXY_FILES)\n return ProxyManager(random_file).random_proxy().get_dict()\n\n\ndef main():\n while True:\n proxy = get_random_proxy()\n print(f'Do something with {proxy["http"]}\\n')\n time.sleep(DELAY)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p>This approach will save you a lot of development time since you:</p>\n<ul>\n<li>won't have to add a new method to your <code>ProxyServer</code> each time you have a new proxy file.</li>\n<li>won't have to keep track of <code>random_list</code> (which is not quite random since it has to match the attributes of the class)</li>\n<li>you won't need a <code>Testing()</code> class anymore</li>\n</ul>\n<p>Notice that with this version is really easy to figure out what you're doing.</p>\n<h2>Recommendations (<a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>):</h2>\n<ul>\n<li>use appropriate naming for your variables (<em>snake_case</em> naming convention for methods/functions, <em>UPPER_CASE</em> naming convention for constants);</li>\n<li>use docstrings to help your readers understand the code;</li>\n</ul>\n<hr />\n<p>If you're really tied to use classes, I'd mix your solution with mine and do something along these lines:</p>\n<pre><code>import random\nimport time\n\nimport requests\n\nfrom proxymanager import ProxyManager\n\n\nPROXY_FILES = (\n './test.txt',\n './test2.txt',\n './test3.txt',\n './test4.txt',\n)\nDELAY = 10\n\n\nclass ProxyServer:\n def __init__(self, random_proxy_file):\n self.proxy_manager = ProxyManager(random_proxy_file)\n\n def get_proxy(self):\n """\n Return a random proxy dict.\n """\n return self.proxy_manager.random_proxy().get_dict()\n\n\nclass Scrapper:\n def __init__(self, base_url):\n self.base_url = base_url\n\n @staticmethod\n def _get_random_proxy():\n random_proxy_file = random.choice(PROXY_FILES)\n return ProxyServer(random_proxy_file).get_proxy()\n\n def get_url_data(self):\n proxy = self._get_random_proxy()\n data = requests.get(self.base_url, proxies={'http': proxy['http']})\n return data\n\n def do_something_with_data(self, data):\n return data\n\n\ndef main():\n scrapper = Scrapper('http://scrapeme.not/')\n \n while True:\n data = scrapper.get_url_data()\n scrapper.do_something_with_data(data)\n time.sleep(DELAY)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p>But notice how this has become a lot more complex than it should've been. Some advantages that this has over your solution:</p>\n<ul>\n<li>it uses better naming;</li>\n<li>it avoids creating multiple <code>ProxyManager()</code> instances;</li>\n<li>it avoids mapping the <code>getattr()</code> to a value from a list you'd have to maintain all the time as complexity of the scrapper increases;</li>\n</ul>\n<hr />\n<p>And to answer your question: no, it's not wrong to use <code>getattr()</code> like that but in this specific case I don't think it's necessary due to the above listed reasons.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T17:39:08.293",
"Id": "497777",
"Score": "0",
"body": "Hello! This is very good review and I do really like it! There is so much I can easily improve with this code review and I do apprecaite it! There is one missing part that I might have needed to more explain, the reason why I had different functions for proxies is that my plan later on is that when I want to call a specific proxy, in my case etc: proxy \"world\" then I want to specific use the `./test2.txt` and in our case you are using a random function. For now I had a random `randomList = [\"hello\", \"world\", \"hey\", \"yes\"]` for this part but later on I will instead call a specific one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T17:39:59.523",
"Id": "497779",
"Score": "0",
"body": "And here I might need in your case maybe a small change if it doesn't take up too much time for you! But the choice of calling a specific proxy is much needed and I would like to call the specific proxy when I do it later on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T19:58:34.470",
"Id": "497806",
"Score": "0",
"body": "Would you be able to put PROXY_FILES into a dict and then you can just do something like: `PROXY_FILES [proxyType].random_proxy().get_dict()` where proxyType can be etc: `hello` ?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T15:36:04.910",
"Id": "252600",
"ParentId": "252581",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "252600",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T09:23:55.667",
"Id": "252581",
"Score": "1",
"Tags": [
"python",
"python-3.x"
],
"Title": "Calling different class objects using python"
}
|
252581
|
<p>I have a program that should read and process about 500,000 files in the format <code>hdf5</code>, each of them containing about 400 <a href="https://nrc-digital-repository.canada.ca/eng/view/object/?id=9f09901d-0736-4204-a35d-0c88ffb8da3b" rel="nofollow noreferrer">data points representing the coordinates of carbon atoms in a sheet of graphene</a>. Since I have an HDD, the process of reading is slow and as such I don't want to delay the reading process as it waits for the computation to finish. My idea was moving the reading process onto a new thread so that new files are read all the time and processed whenever they are available in the main thread.</p>
<p>My implementation of this was spawning an <code>std::thread</code> for reading and <code>std::move</code>ing a <code>std::vector<std::promise<DataEntry*>></code> of structs I have defined that are then used in the main thread through their respective futures.</p>
<p><strong>Is there a more efficient way of implementing this multithreading?</strong> It feels horribly inefficient to have to make 500,000 promises and futures. I suppose it would be easy to <code>delete</code> the futures once used on the main thread but I don't know how I would go about freeing the promises that are still on the reading thread.</p>
<p>Apart from that, are there any other ways in general of improving my code, especially in terms of performance?</p>
<hr />
<p><strong>utility.h</strong></p>
<pre><code>#pragma once
#include <vector>
#include <future>
#include <chrono>
#include <string>
#include <iostream>
namespace porous {
struct Timer {
high_resolution_clock::time_point start;
high_resolution_clock::time_point end;
std::string message;
Timer(std::string msg) {
message=msg;
start = high_resolution_clock::now();
}
void now() {
end = high_resolution_clock::now();
int64_t duration = std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count();
std::cout << message << " took " << duration << "ms\n";
}
~Timer() {
end = high_resolution_clock::now();
int64_t duration = std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count();
std::cout << message << " took " << duration << "ms\n";
}
};
struct double2 {
double x,y;
};
struct DataEntry {
double energy;
int n_points;
double2* position;
DataEntry(int n):n_points(n) {
position = new double2[n_points];
}
~DataEntry() {
delete[] position;
}
};
}
typedef std::vector<std::promise<porous::DataEntry*>> promised_entries_t;
typedef std::vector<std::future<porous::DataEntry*>> future_entries_t;
</code></pre>
<p><strong>reader.h</strong></p>
<pre><code>#pragma once
#include <string>
#include <filesystem>
#include <chrono>
#include <mutex>
#include <future>
#include <vector>
#include <H5Cpp.h>
#include "utility.h"
using namespace porous;
using namespace H5;
using std::filesystem::directory_iterator;
using std::filesystem::directory_entry;
namespace porous {
class Reader {
private:
std::vector<std::string> files;
std::thread reader_thread;
void threaded_read(promised_entries_t entries);
promised_entries_t entry_promises;
const char* next();
public:
Reader(std::string basedir);
future_entries_t read_all();
DataEntry* read(std::string path); //called from worker thread
void detach();
};
}
</code></pre>
<p><strong>reader.cpp</strong></p>
<pre><code>#include "reader.h"
#include "utility.h"
#include <iostream>
namespace fs = std::filesystem;
using namespace std;
using namespace porous;
Reader::Reader(string path) {
try {
Timer t("[Reader] init");
for (auto& entry : fs::directory_iterator(path)) {
files.push_back(entry.path().string());
}
cout << "There are " << files.size() << " to read\n";
} catch (std::exception& e) {
cout << e.what() << endl;
}
}
DataEntry* Reader::read(string path) {
H5File f;
try{
f = H5File(path, H5F_ACC_RDONLY);
} catch(...) {
cout << "this file did not read:\n" << path << endl;
return NULL;
}
DataSet coords_ds = f.openDataSet("coordinates");
DataSpace coords_space = coords_ds.getSpace();
hsize_t dims1[2];
coords_space.getSimpleExtentDims(dims1,NULL);
const int coord_dimension = (int)dims1[0];
DataEntry* entry = new DataEntry(coord_dimension);
const DataSet energy_ds = f.openDataSet("energy");
energy_ds.read(&entry->energy, PredType::NATIVE_DOUBLE);
hsize_t offset[2] = {0,1};
hsize_t count[2] = {coord_dimension,2};
coords_space.selectHyperslab(H5S_SELECT_SET,count,offset);
hsize_t offset_output[2] = {0,0};
hsize_t dim_output[2] = {coord_dimension,2};
DataSpace output_space(2, dim_output);
output_space.selectHyperslab(H5S_SELECT_SET,dim_output,offset_output);
coords_ds.read(entry->position, PredType::NATIVE_DOUBLE, output_space,coords_space);
f.close();
return entry;
}
void Reader::threaded_read(promised_entries_t entries) {
for (int i = 0; i < files.size(); i++) {
entries[i].set_value(this->read(files[i]));
}
}
future_entries_t Reader::read_all() {
future_entries_t zukunft;
for(int i = 0; i < files.size(); i++) {
std::promise<DataEntry*> pr;
zukunft.push_back(pr.get_future());
entry_promises.push_back(std::move(pr));
}
reader_thread = std::thread(&Reader::threaded_read, this, std::move(entry_promises));
return zukunft;
}
void Reader::detach() {
reader_thread.detach();
}
</code></pre>
<p><strong>main.cpp</strong></p>
<pre><code>#include <iostream>
#include <string>
#include <chrono>
#include "utility.h"
#include "reader.h"
using namespace porous;
using namespace std;
using namespace std::chrono_literals;
int main() {
using namespace porous;
Reader r("../../big-graphene/test");
future_entries_t dat = r.read_all();
for (auto& fut_dat : dat) {
DataEntry* e = fut_dat.get();
std::this_thread::sleep_for(1s);//simulate some long computation
//cout << e->energy << endl;
delete e;
}
r.detach();
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T11:30:22.937",
"Id": "497728",
"Score": "2",
"body": "I’d love to help review the code and offer suggestions on how to improve it, but there just isn’t enough there to even begin to know what could be improved. Like what is `reader_thread`? How does it work? Does it run each task sequentially? Or does it spawn threads? Use a thread pool? No idea. Try to put together the minimal amount of code *that compiles*, and maybe someone could help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T12:04:34.720",
"Id": "497734",
"Score": "0",
"body": "@indi `reader_thread` is just a member variable of the class, but I will add some stubs to make this compile"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T12:48:46.903",
"Id": "497735",
"Score": "2",
"body": "Welcome to Code Review! The code you posted is missing some important parts, which means we can't compile it. This makes it much harder to test different ways of achieving the same result. If you [edit] your question to make the code complete, that will improve its chances of attracting good answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T16:05:03.647",
"Id": "497758",
"Score": "1",
"body": "Please post the entire reader class, as well as some unit test code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T09:26:44.877",
"Id": "497868",
"Score": "0",
"body": "@TobySpeight is it preferrable to include all the code in the question or is it also valid to post the main code and link the rest through e.g. a Gist?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T09:30:33.930",
"Id": "497870",
"Score": "0",
"body": "It's best if you can make the code complete in the question (for example, add the relevant `#include` lines and class definitions). Sometimes that's not possible (if it's tightly coupled to other code that's out of scope of the review), in which case it's still worth including those trivial things. Remember: the more you help reviewers, the better reviews you're likely to get."
}
] |
[
{
"body": "<pre><code>struct DataEntry {\n double energy;\n int n_points;\n double2* position;\n DataEntry(int n):n_points(n) {\n position = new double2[n_points];\n }\n ~DataEntry() {\n delete[] position;\n }\n};\n</code></pre>\n<p>Use a <code>std::vector</code> for the positions:</p>\n<pre><code>struct DataEntry {\n double energy;\n std::vector<double2> position;\n DataEntry(int n):\n position(n) { }\n};\n</code></pre>\n<p>If we need a pointer to the data, we can use <code>position.data()</code>.</p>\n<hr />\n<pre><code>using namespace std;\nusing namespace porous;\n</code></pre>\n<p>It's best to avoid <code>using</code> whole namespaces like this to avoid name collisions. Since the things being defined are inside the <code>porous</code> namespace, we don't actually need that <code>using</code> statement at all.</p>\n<hr />\n<pre><code>try {\n Timer t("[Reader] init");\n for (auto& entry : fs::directory_iterator(path)) {\n files.push_back(entry.path().string());\n }\n cout << "There are " << files.size() << " to read\\n";\n} catch (std::exception& e) {\n cout << e.what() << endl;\n} \n</code></pre>\n<p>Is there anything that we particularly want to <code>catch</code> here? I think we could just let any exception escape for the user to handle, rather than carrying on with only a message to <code>cout</code>.</p>\n<p>It might be a good idea to move this code out of the constructor and into <code>read_all</code> (and take the path as an argument there). I don't think there's any reason to separate iterating through the directory from the rest of the work that the <code>Reader</code> does.</p>\n<hr />\n<pre><code>DataEntry* Reader::read(string path) {\n ...\n DataEntry* entry = new DataEntry(coord_dimension);\n</code></pre>\n<p>If we need the dynamic memory allocation, we should be using a smart pointer to make ownership simpler and easier.</p>\n<p>Or we could just pass the DataEntry around using move semantics (which is easy if we use a <code>std::vector</code> internally for the positions).</p>\n<hr />\n<pre><code>void Reader::detach() {\n reader_thread.detach();\n}\n</code></pre>\n<p>Since all the work is already complete when this is called, we can <code>join</code> instead of <code>detach</code>ing. The <code>join</code> can be done in the <code>Reader</code> destructor so it happens automatically.</p>\n<hr />\n<p>We should be able to reduce the amount of state and number of functions in the <code>Reader</code> class significantly:</p>\n<pre><code>class Reader\n{\npublic:\n \n Reader() = default;\n ~Reader() { if (m_thread.joinable()) m_thread.join(); }\n \n future_entries_t read_all(std::string const& dir_path);\n \nprivate:\n \n std::thread m_thread;\n};\n\nnamespace\n{\n \n std::vector<std::string> list_files_in_dir(std::string const& dir_path);\n \n DataEntry read_file(std::string const& path);\n \n void read_files(promised_entries_t entries, std::vector<std::string> files); // threaded_read...\n \n} // unnamed\n\nfuture_entries_t Reader::read_all(std::string const& dir_path)\n{\n auto files = list_files_in_dir(dir_path);\n \n future_entries_t futures;\n promised_entries_t promises;\n for (auto i = std::size_t{ 0 }; i != files.size(); ++i)\n {\n // ... as before\n }\n \n m_thread = std::thread(&read_files, std::move(promises), std::move(files));\n return futures;\n}\n\nint main()\n{\n Reader r;\n for (auto& future : r.read_all("../../big-graphene/test"))\n {\n auto e = future.get();\n // ...\n }\n}\n</code></pre>\n<p>This fetches the list of files in <code>read_all</code>, and passes it to <code>read_files</code>, along with the promises.</p>\n<p>An anonymous namespace is used for functions that don't need access to any data inside the <code>Reader</code> class.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T09:32:58.410",
"Id": "498032",
"Score": "0",
"body": "if I understand correctly, the method `DataEntry read_file(..)` is the same as my implementation, except that its return would look like `return std::move(*entry);`.. Is this correct?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T10:08:42.850",
"Id": "498036",
"Score": "1",
"body": "Yep, but using a `std::vector` inside `DataEntry`, and creating `entry` on the stack (rather than using `new`). So we can just do `return entry;` and the compiler will either optimize out the copy entirely, or use move semantics. We shouldn't do `return std::move(entry);` as this can prevent the compiler from optimizing as effectively."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T11:39:03.453",
"Id": "498044",
"Score": "1",
"body": "Ah, got 2⁄3 of the way through writing a *long* review, only to be beaten to the punch! Nice review; you covered pretty much everything I was going to. Oh well, my effort’s not entirely wasted because there’s still one other key thing I want to review about the code, so I’ll still be adding my own (much shortened!) review later."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T07:58:32.550",
"Id": "252699",
"ParentId": "252582",
"Score": "1"
}
},
{
"body": "<p>user673679’s answer covers pretty much all of the suggestions I thought to make about the actual code as presented. But it doesn’t answer the primary question: “Is there a more efficient way of implementing this multithreading?”</p>\n<p>To answer that, I’m going to do a higher-level review, a review not of the actual code, but rather of the <em>design</em>. That’s going to require that I make some guesses and assumptions, because there’s so much code missing, and no real information about what the ultimate goals of the code are supposed be. So this design review is going to be necessarily vague.</p>\n<h1>A note about the C++ standard library (and particularly the threading stuff)</h1>\n<p>Before I begin, I want to give some guidance about the C++ standard library, and particularly the threading sub-library. The C++ standard library is very different from the standard libraries of most popular languages. Most languages try to give you a fully-complete, high-level, universally-usable set of libraries as part of their standard library—basically, most languages want you to use their standard libraries for everything that they cover, and only use third-party libraries for stuff that isn’t important enough to be worthy of being part of their standard library. The upshot of that is that you can do most things “out of the box” in those languages—it’s rare to need a third-party library. The downside is that their standard libraries tend to be <em>HUGE</em>… often there’s only a single implementation because it would be too big a task for anyone to try to re-implement the whole thing.</p>\n<p>The C++ standard library goes another way. It does not try to be all things to all people. Instead, it’s quite spartan, focusing on providing only a small set of vocabulary types, and key facilities that you <em>need</em> to do many/most things, but are either too hard or simply impossible to roll your own portably. You can use the standard library directly if it happens to solve your problem, but the <em>main</em> goal of the C++ standard library is to give you the tools you need to write good, high-level libraries… not to <em>be</em> those libraries itself.</p>\n<p>In other words, you shouldn’t look at the C++ standard library’s threading stuff and say, “okay, everything I need to solve my problem should be in here”. You should think about what high-level tools you need, and then see what the C++ standard library provides to help you build those tools. Or, even better, find a third-party library that’s already done that.</p>\n<p>The reason why I explained all this will become clear in a moment.</p>\n<p>So let’s get started.</p>\n<h1>The review</h1>\n<p>I’d say your intuition—that it’s horribly inefficient to make a half-million promises and futures—is spot on. Of course, if you <em>need</em> to do that, then, well, that’s that; if you need it, you need it, and you just have to accept that it’s gonna take time. But the million-object question here is: do you <em>need</em> those promises and futures?</p>\n<p>Promises and futures are an excellent way to model values that will be coming from somewhere at any time, but that you don’t immediately need because you can do other stuff if the values aren’t available. That is, you have a task, and you need a value within that task… but not necessarily <em>immediately</em>—you can do other stuff while waiting for that value.</p>\n<p>That… doesn’t really sound like what you’re doing, does it? You’re not really doing a task where you can do other stuff while waiting on a value. What you’re doing is generating values, and you want to be able to work with them as soon as they come available, even if all the values aren’t ready yet.</p>\n<p>To me, that sounds like the tool you want is a concurrent queue.</p>\n<p>And this is where we circle back to what I said about the C++ standard library. Unfortunately, there is no concurrent queue in the standard library. (Yet! There’s actually one proposed for the future.) You could write one yourself, using the threading stuff in the standard library, or, better, you can use a third-party library. There are a lot out there; <a href=\"https://www.boost.org/doc/libs/release/doc/html/thread/sds.html#thread.sds.synchronized_queues\" rel=\"nofollow noreferrer\">Boost has one, for example</a>. There are even <em>lock-free</em> concurrent queues out there, if you like (though they sometimes come with limitations on use, like only a single producer, or they’re less efficient because they do a lot of dynamic allocation).</p>\n<p>So what would the code look like if you used a queue? Well, assuming a queue with an interface like the Boost one (which is similar to what’s proposed for future C++ standard library), it might look like this:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>// The reader thread function.\n//\n// Pretty simple. Takes the path and a reference to the queue, and just\n// iterates through the items in the path, reading the files, and pushing the\n// data to the queue.\n//\n// Once it's done, closes the queue.\nauto reader_thread_func(std::filesystem::path path, queue_t<DataEntry>& entries)\n{\n for (auto&& p : std::filesystem::directory_iterator{path})\n entries.push(read(p.path()));\n\n entries.close();\n}\n\n// The main thread.\n//\n// First, we create the queue.\nauto entries = queue_t<DataEntry>{};\n\n// Then we create the reader thread.\nauto reader_thread = std::thread{reader_thread_func, "/path/to/files", std::ref(entries)};\n\n// At this point, the reader thread is busy reading the data files in the\n// background. The data being read will be coming in entry-by-entry.\n//\n// So let's start using the entries as they come in:\nwhile (true)\n{\n auto entry = DataEntry{};\n\n if (auto result = entries.wait_pop(entry); result == queue_op_status::success)\n {\n // We just got another entry!\n //\n // Do whatever computation you want with it. I'll just use what you\n // wrote:\n std::this_thread::sleep_for(1s);//simulate some long computation\n //cout << e->energy << endl;\n }\n else if (result == queue_op_status::empty)\n {\n // The queue is empty, but not closed.\n //\n // This means we're processing entries faster than we're reading them.\n // So we have to wait until an entry becomes available. We'll just\n // have this thread give up its time, and then try again.\n std::this_thread::yield();\n }\n else if (result == queue_op_status::closed)\n {\n // The queue is empty, and closed.\n //\n // We're done.\n break;\n }\n}\n\n// Clean up.\nreader_thread.join();\n</code></pre>\n<p>There’s no error handling above (it wouldn’t be too much to add), but basically, that’s everything you need.</p>\n<p>The neat thing about using the right tool for the job is that you usually get additional benefits. In this case, a concurrent queue is really the right tool for the job, and it comes with benefits aplenty. For starters, you no longer have to allocate all the data entries—you can just use them more or less as they come in, and then discard them. That means no need for a half-million element vector. In fact, you can even <em>restrict</em> the maximum number of data entries to read to keep memory use bounded; the reader thread can simply wait until you’ve finished with a data entry and are ready for more. Also, you could even have <em>multiple</em> reader threads—perhaps even a thread pool of reader threads, so you can read like 4 or 8 or more files at a time.</p>\n<p>Okay, but I’ve made an assumption here (remember, there’s a lot of guesswork here for me, because you haven’t given enough information). I’m assuming that you don’t actually need all half-million data entry objects <em>at the same time</em>. I’m assuming you can read each entry, then discard it. But if that assumption is wrong—if you have to read the data entries, do some computation on them one-by-one as they come in, <em>and then later</em> do <em>another</em> computation on them <em>altogether</em>, then you can’t simply use a queue (because with a queue, you’d be discarding each entry after you processed it).</p>\n<p>But the basic idea still applies. You could use a <code>vector</code> instead of a queue, and do all the concurrency stuff manually. Or, perhaps better, you could make a “concurrent queue view” wrapped around a vector, and use the queue view while the data is coming in, and still have the vector of all entries at the end. What’s “best” depends entirely on the details, and I don’t know the details.</p>\n<h1>Summary</h1>\n<p>Promises and futures are the wrong tool for this job. They’re for situations where you’re waiting on a value, but you can do other stuff while you wait. Your situation is that you have a bunch of values coming in, and you want to start using them as soon as possible, without waiting for <em>all</em> the values to finish reading it. You’re not really doing anything else while waiting on each value… you’re just waiting on the next value. That situation usually means you want to use a queue.</p>\n<p>Unfortunately, the standard library doesn’t have a concurrent queue (yet). So you either have to roll your own, or use a third-party library. That’s pretty normal when it comes to C++ and its standard library. It doesn’t come with everything built-in, and all the bells and whistles you could ever need. It’s pretty spartan, only providing the bare minimum necessary to that actually useful libraries can be built <em>on top</em> of it.</p>\n<p>So get/make a concurrent queue, and then just use one thread (or multiple threads!) to read in the data, while another thread (or, again, multiple threads!) keeps pumping the queue for whatever data is available. You’ll spare yourself from having to allocate a half-million promises and a half-million futures, and get a more flexible and powerful abstraction to boot.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T07:53:04.090",
"Id": "498138",
"Score": "0",
"body": "I've already tried an implementation using `atomic_int` that keeps track of the maximum index available, but your solution with concurrent queues seems much more elegant and extendible. thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T14:43:43.617",
"Id": "498165",
"Score": "0",
"body": "Using an atomic index isn’t a bad idea at all! That’s actually pretty much exactly what I had in mind when I suggested to use a vector. You’d need two indexes, I think—one to keep track of reading, and one for writing—you’d have to wait when the reader catches up with the writer—and your reader loop would be like `while (not done and read_index < write_index)`. Yeah, that would totally work. (Though I’d suggest wrapping all that machinery up in a class, also with error handling… which would then basically be your “queue view” class.)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T23:43:06.853",
"Id": "252734",
"ParentId": "252582",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "252734",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T09:30:12.723",
"Id": "252582",
"Score": "3",
"Tags": [
"c++",
"performance",
"multithreading",
"processing"
],
"Title": "Multithread reading and processing when working with HDF5 files"
}
|
252582
|
<p>I have been tasked to make an array without duplicated values from another existing array.
So I did it, but I want to know is there some other better way to do that.</p>
<h3>Example input/output</h3>
<p><code>Input</code>: <code>1, 15, 1, 5, 1, 3</code></p>
<p><code>Output</code>: <code>1, 15, 5, 3</code></p>
<h3>My code</h3>
<pre><code>#include <stdio.h>
int main(void) {
const int ARRAY_SIZE = 5;
int m[ARRAY_SIZE], p[ARRAY_SIZE];
for(int i = 0; i < ARRAY_SIZE; i++) {
printf("Enter number: ");
scanf("%d",&m[i]);
}
// k variable is used to be the new indexing of the array p;
int k = 0;
// if it has a duplication dup is changed to 1;
int dup = 0;
// Loops through the array.
for(int i =0; i < ARRAY_SIZE; i++) {
for(int j = i +1; j <ARRAY_SIZE ; j++) {
if(m[i] == m[j]) {
dup = 1;
break;
}
}
if(dup != 1) {
p[k++] = m[i];
}
dup = 0;
}
printf("The array without repeated values\n");
for(int i = 0; i < k; i++) {
printf("%d\n",p[i]);
}
return 0;
}
</code></pre>
<p>I want some suggestions.</p>
<p>Thanks in advance. :)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T10:11:12.737",
"Id": "497721",
"Score": "0",
"body": "your algorithm is `O(n^2)` because of the nested loop. You could try using the `qsort()` function from the C header `stdlib.h` to first sort the array, then iterate through the sorted array once to only add the unique elements. This would be `O(nlogn)` time. Hash sets are even better but I don't know if there's a standard library object for that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T10:12:42.080",
"Id": "497722",
"Score": "0",
"body": "@JohnK Thanks for the advice. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T13:56:42.870",
"Id": "497741",
"Score": "2",
"body": "You're supposed to ask about *your own* code, not someone else's."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T16:33:22.607",
"Id": "497761",
"Score": "0",
"body": "One of several things is possible: either you copy-and-pasted the original question (including suggestions from its answer), which makes this off-topic due to authorship; or @parallela is a sock puppet for Lubomir Stankov and you're asking the same question with nearly no modification, which makes it a simple duplicate. Either way, in its current state this needs to be closed."
}
] |
[
{
"body": "<p>A flag "dup" can be avoided by rearranging the inner loop. Here is a compact version, somehow a bit inside-out so that we can do our thing <code>p[k++]=</code> right on the spot:</p>\n<pre><code> for (int i = 0; i < ARRAY_SIZE; i++) {\n\n for (int j = i + 1; m[i] != m[j]; j++) { /*NO! m[i+1] will be illegal */\n\n if (j == ARRAY_SIZE) {\n p[k++] = m[i]; // copy this one, next "i" please\n break;\n }\n }\n }\n</code></pre>\n<p>For clarity I almost prefer this as the inner loop:</p>\n<pre><code>\n for (int j = i + 1;; j++) {\n\n if (j == ARRAY_SIZE) {\n p[k++] = m[i]; // copy this one, next please\n break;\n }\n if (m[i] == m[j])\n break; // skip, next \n }\n\n</code></pre>\n<p>This is more symmetric; you can easily compare the two exit conditions for this eternal loop (no middle expression).</p>\n<p>It is important to first check if <code>j</code> has reached ARRAY_SIZE, and only then use it in <code>m[j]</code>.</p>\n<hr />\n<p>For an array like <code>120000000...000012</code> I think it would be faster to search in the new, unique array...but yes, that is why sorting is a useful first (and main) step.</p>\n<hr />\n<p>The first (compact) version is even <strong>wrong</strong>. <code>m[j]</code> will already be illegal for the last element.</p>\n<p><code>for (int j = i + 1; m[i] != m[j];...</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T11:25:09.947",
"Id": "252586",
"ParentId": "252583",
"Score": "1"
}
},
{
"body": "<p>If the input really does have commas between the numbers, then we'll want to allow for that here:</p>\n<blockquote>\n<pre><code>scanf("%d",&m[i]);\n</code></pre>\n</blockquote>\n<p>In any case, it's important to check the return value from <code>scanf()</code>, otherwise we could be using values that haven't been properly initialised.</p>\n<p>It's probably worth writing separate functions for the input, output and processing, and then have a simple <code>main()</code> that links the three together.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T12:55:02.033",
"Id": "252591",
"ParentId": "252583",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T09:52:56.803",
"Id": "252583",
"Score": "-1",
"Tags": [
"beginner",
"c",
"array",
"sorting",
"homework"
],
"Title": "Remove duplicates from array and save it to another one"
}
|
252583
|
<p>I write protocol messages encoder/decoder for my project.
All messages have 2-bytes header (1 byte - message type, 1 byte message sub-type) and body.
There are two types of messages:</p>
<ol>
<li>Plain message - no encoding</li>
<li>Encoded message - AES encoding</li>
</ol>
<p>I would like to get your feedback on:</p>
<ol>
<li>Overall design and coding style</li>
<li>Proposals for performance (it is very important) and memory usage
improvement.</li>
</ol>
<p>Comment #1: the following code is working code.
Comment #2: the "Unsafe" stream classes are classes that extend ByteArray streams. The aim is to get direct access to internal stream buffer (it is protected).</p>
<pre><code>public class PacketBuilder {
/**
* Creates DatagramPacket. The packet data is encoded.
* The cipher should be initialized with Cipher.ENCRYPT_MODE.
*
* @param data the data to be sent
* @param cipher the cipher
* @param sendTo the destination address
*
* @return DatagramPacket
*
* @throws NullPointerException if any of arguments is null
* @throws EncodingException if error occurred during encoding
*/
public static DatagramPacket buildEncoded(byte[] data, Cipher cipher, SocketAddress sendTo)
throws NullPointerException, EncodingException {
Objects.requireNonNull(data);
Objects.requireNonNull(cipher);
Objects.requireNonNull(sendTo);
try {
UnsafeByteArrayOutputStream bytes = new UnsafeByteArrayOutputStream();
CipherOutputStream cipherOutput = new CipherOutputStream(bytes, cipher);
cipherOutput.write(data);
cipherOutput.flush();
cipherOutput.close();
DatagramPacket packet = new DatagramPacket(bytes.getBuffer(), bytes.getByteCount());
packet.setSocketAddress(sendTo);
return packet;
} catch (IllegalStateException | IOException e) {
throw new EncodingException(e);
}
}
/**
* Creates DatagramPacket. The packet data is encoded.
* The cipher should be initialized with Cipher.ENCRYPT_MODE.
*
* @param type the message type
* @param subType the message sub-type
* @param string the string to be sent
* @param cipher the cipher
* @param sendTo the destination address
*
* @return DatagramPacket
*
* @throws NullPointerException if any of arguments is null
* @throws EncodingException if error occurred during encoding
*/
public static DatagramPacket buildEncoded(byte type, byte subType, String string, Cipher cipher, SocketAddress sendTo)
throws NullPointerException, EncodingException {
Objects.requireNonNull(string);
Objects.requireNonNull(cipher);
Objects.requireNonNull(sendTo);
byte[] data = null;
try {
data = string.getBytes(StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e1) {};
try {
UnsafeByteArrayOutputStream bytes = new UnsafeByteArrayOutputStream();
CipherOutputStream cipherOutput = new CipherOutputStream(bytes, cipher);
cipherOutput.write(type);
cipherOutput.write(subType);
cipherOutput.write(data);
cipherOutput.flush();
cipherOutput.close();
DatagramPacket packet = new DatagramPacket(bytes.getBuffer(), bytes.getByteCount());
packet.setSocketAddress(sendTo);
return packet;
} catch (IllegalStateException | IOException e) {
throw new EncodingException(e);
}
}
/**
* Creates DatagramPacket. The packet data is not encoded
*
* @param type the message type
* @param subType the message sub-type
* @param data the data to be sent
* @param sendTo the destination address
*
* @return DatagramPacket
*
* @throws NullPointerException if any of arguments is null
*/
public static DatagramPacket buildPlain(byte type, byte subType, String string, SocketAddress sendTo)
throws NullPointerException {
Objects.requireNonNull(string);
Objects.requireNonNull(sendTo);
byte[] data = null;
try {
data = string.getBytes(StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e1) {};
UnsafeByteArrayOutputStream out = new UnsafeByteArrayOutputStream();
try {
out.write(type);
out.write(subType);
out.write(data);
out.flush();
out.close();
} catch (IOException e) {}; //we cannot be here
DatagramPacket packet = new DatagramPacket(out.getBuffer(), out.getByteCount());
packet.setSocketAddress(sendTo);
return packet;
}
public class PacketParser {
/**
* Decode packet data and creates message.
* The cipher have to be initialized with Cipher.DECRYPT_MODE
*
* @param packet the packet to convert to message
* @param cipher the cipher
*
* @return message
*
* @throws NullPointerException if any of arguments is null
* @throws IllegalMessageException if packet data cannot be converted to message
* @throws DecodingException if error occurred during decoding
*/
public static Message parseEncoded(DatagramPacket packet, Cipher cipher)
throws NullPointerException, IllegalMessageException, DecodingException {
validate(packet);
Objects.requireNonNull(cipher);
UnsafeByteArrayInputStream bytesInput;
CipherInputStream cipherInput = null;
UnsafeByteArrayOutputStream bytesOutput = null;
try {
bytesInput = new UnsafeByteArrayInputStream(packet.getData(), 0, packet.getLength());
cipherInput = new CipherInputStream(bytesInput, cipher);
bytesOutput = new UnsafeByteArrayOutputStream();
for (int b = cipherInput.read(); b > -1; b = cipherInput.read())
bytesOutput.write(b);
return new Message(bytesOutput.getBuffer(), bytesOutput.getByteCount(), packet.getSocketAddress());
} catch (IllegalStateException | IOException e) {
throw new DecodingException(e);
} finally {
try {
if (cipherInput != null) cipherInput.close();
if (bytesOutput != null) bytesOutput.close();
} catch (Exception e) {};
}
}
/**
* Creates message from the given packet
*
* @param packet the packet to convert to message
*
* @return message
*
* @throws NullPointerException if any of arguments is null
* @throws IllegalMessageException if packet data cannot be converted to message
*/
public static Message parsePlain(DatagramPacket packet)
throws NullPointerException, IllegalMessageException {
validate(packet);
return new Message(packet.getData(), packet.getLength(), packet.getSocketAddress());
}
/*
* Validates the packet. Throws exception if
* message has no header or header is illegal
*/
private static void validate(DatagramPacket packet)
throws NullPointerException, IllegalMessageException {
Objects.requireNonNull(packet);
if (packet.getLength() < HEADER_LENGTH)
throw new IllegalMessageException("Message too short");
int type = packet.getData()[0];
int subType = packet.getData()[1];
switch (type) {
case Constants.REGISTRATION:
switch (subType) {
case Constants.HELLO:
case Constants.KEY_EXCHANGE:
case Constants.CLIENT_IF:
case Constants.ACCESS:
case Constants.ERROR:
break;
default:
throw new IllegalMessageException("Unknown message");
}
break;
case Constants.HEART_BEAT:
case Constants.CONN_REQUEST:
break;
default:
throw new IllegalMessageException("Unknown message");
}
}
public static class Message {
final private byte type;
final private byte subType;
final private byte[] data;
final private int length;
final private SocketAddress address;
private Message (byte[] buffer, int length, SocketAddress address) {
this.type = buffer[0];
this.subType = buffer[1];
this.address = address;
byte[] data = new byte[length - HEADER_LENGTH];
System.arraycopy(buffer, HEADER_LENGTH, data, 0, data.length);
this.data = data;
this.length = data.length;
}
public byte getType() {
return type;
}
public byte getSubType() {
return subType;
}
public byte[] getData() {
return data;
}
public int getLength() {
return length;
}
public SocketAddress getAddress() {
return address;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T05:57:54.667",
"Id": "497841",
"Score": "0",
"body": "If you use `String.getBytes(StandardCharsets.UTF_8)` you don't have to deal with the UnsupportedEncodingException."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T10:57:35.307",
"Id": "497874",
"Score": "0",
"body": "@mtj Sorry, but UnsupportedEncodingException thrown by String.getBytes(), so usage of constant doesn't help to avoid exception."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T11:37:16.807",
"Id": "497879",
"Score": "0",
"body": "Yes it does. There's two method signatures: one with a string parameter (the one you use), which thows the exception, the other with a charset parameter, which does *not* throw the exception."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T12:13:00.297",
"Id": "497883",
"Score": "0",
"body": "@ mtj My fault. Thanks for explanation."
}
] |
[
{
"body": "<p>Nice to see clean, well formatted and commented code.</p>\n<p><del>The <code>buildEncoded</code> builds the <code>DatagramPacket</code>, sends it and returns the packet. If the responsibilities cannot be split to separate methods, the reason should be documented in the code. Now the accurate name for the method would be <code>buildSendAndReturnEncoded</code> :).</del></p>\n<p>Have you identified the string-based <code>buildEncoded</code> and <code>buildPlain</code> methods as performance bottlenecks? If not, they should create the message data byte array from the string and send that data to <code>buildEncoded(byte[], Cipher, SocketAddress)</code> instead of duplicating the <code>DatagramPacket</code> initialization code. The reason why maintainability is sacrificed on the altar of performance should always be clearly documented in code.</p>\n<p>Same with the plaintext methods. If they are not performance hotspots, they should be scrapped and the crypto-methods should be reused with <a href=\"https://docs.oracle.com/javase/7/docs/api/javax/crypto/NullCipher.html\" rel=\"nofollow noreferrer\">NullCipher</a> instead.</p>\n<p>All the "common io util" libraries I know provide some form of <code>closeQuietly(Closeable)</code> method so you don't need to repeat the try-if-not-null-close-catch-ignore mantra.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T10:54:10.590",
"Id": "497873",
"Score": "0",
"body": "Thanks for review. 1. buildEncoded method doesn't send packet. It writes bytes into underlined stream -> ByteArrayStream. 2. Could you please elaborate \n\"they should reuse the byte array based equivalent\" statement. 3. closeQuitely and NullChipher are the great ideas. I will rewrite code using your proposal. Once again, THANKS!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T11:29:02.047",
"Id": "497878",
"Score": "0",
"body": "@bw_dev 1. That was my mistake. 2. I have improved the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T12:10:29.050",
"Id": "497882",
"Score": "0",
"body": "@Now I see your point. You are right. I will rewrite. thanks."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T06:52:49.953",
"Id": "252636",
"ParentId": "252588",
"Score": "0"
}
},
{
"body": "<pre><code>public class PacketBuilder {\n</code></pre>\n<p>...</p>\n<pre><code>public class PacketParser {\n</code></pre>\n<p>This I actually like very much, a clear distinction between objects that encode and decode. Or build and parse if you like.</p>\n<hr />\n<p>First lets start with naming / terminology. AES is a block cipher, a method for <strong>encryption</strong> and <strong>decryption</strong>. When we are talking about encoding we should be talking about e.g. hexadecimal encoding, base 64 encoding, binary encodings (like the one for your message) or character encoding (UTF-8).</p>\n<p>Most AES modes of operation such as CBC are - by themselves - not secure when used for transport mode. CBC with PKCS#7 padding (i.e. <code>"PKCS5Padding"</code> for Java) does not even preserve confidentiality when plaintext or padding oracles apply.</p>\n<hr />\n<pre><code>public static DatagramPacket buildEncoded(byte[] data, Cipher cipher, SocketAddress sendTo) \nthrows NullPointerException, EncodingException {\n</code></pre>\n<p>Never pass a <code>Cipher</code> instance. Instances of <code>Cipher</code> are stateful, so you get into trouble if they are used e.g. in parallel. If you have to keep anything, keep the key, not the cipher. Cipher instances should be created locally. This also means that you don't have to put in comments such as <code>Cipher.ENCRYPT_MODE</code> (which you should check if you write that down).</p>\n<p>Try and avoid static methods, prefer class instances to do the work for you (e.g. with a <code>key</code> and <code>address</code> as fields.</p>\n<hr />\n<p><code>UnsafeByteArrayOutputStream</code> seems to be part of an older Lucene package. Don't use experimental packages if this is the case. Also, please use and understand "try-with-resources". On the point of general stream handling: close should automatically flush, so there is no need for the call to <code>flush()</code>.</p>\n<p>A <code>ByteBuffer</code> may have been a better choice for this kind of operation; a datagram usually has a maximum size after all.</p>\n<hr />\n<pre><code>data = string.getBytes(StandardCharsets.UTF_8.name());\n</code></pre>\n<p>The good thing about <code>string.getBytes(StandardCharsets.UTF_8)</code> is that you don't have to handle the stupid exception for when the charset is not available. By calling <code>name()</code> you've removed that advantage.</p>\n<hr />\n<pre><code>public static DatagramPacket buildEncoded(byte[] data, Cipher cipher, SocketAddress sendTo) \nthrows NullPointerException, EncodingException {\n</code></pre>\n<p>Let's repeat some code? Having two methods doing the same thing is fine if it is advantages to the user of the library, but then you should call a private method that does the actual building of the datagram.</p>\n<p>You've got three things here:</p>\n<ol>\n<li>creating the binary message;</li>\n<li>possibly encrypting the binary message;</li>\n<li>creating the datagram for it.</li>\n</ol>\n<p>I'd like to see those in a design as three methods without code duplication.</p>\n<hr />\n<pre><code>public static Message parseEncoded(DatagramPacket packet, Cipher cipher) \nthrows NullPointerException, IllegalMessageException, DecodingException {\n</code></pre>\n<p>No, if you have a message here then your builder should accept messages as well.</p>\n<p>Furthermore, things like <code>NullPointerException</code> should normally not be part of the signature of a method.</p>\n<p>Because of the difference between encryption / decryption, it may not be clear to a user when either of the other two exceptions are thrown.</p>\n<hr />\n<pre><code>validate(packet);\n</code></pre>\n<p>Ah, only here we find out that some messages are acceptable and others are not. This is completely hidden from the user. There should be specialized message types instead, and you should not be able to send invalid packets using the builder, except maybe for error handling.</p>\n<hr />\n<pre><code>CipherInputStream cipherInput = null;\n</code></pre>\n<p>RED FLAG! You should never have to assign <code>null</code> to anything, especially when using try-with-resources.</p>\n<hr />\n<pre><code>packet.getLength()\n</code></pre>\n<p>I'm pretty sure that arrays in Java already store the length and start their index at 0. So there is really no need for all that it seems.</p>\n<hr />\n<pre><code>for (int b = cipherInput.read(); b > -1; b = cipherInput.read())`\n bytesOutput.write(b);\n</code></pre>\n<p>You'd be right if you thought that reading entire buffers at once would be faster than a one-by-one for loop.</p>\n<hr />\n<pre><code>int type = packet.getData()[0];\n</code></pre>\n<p>Zero should be a constant as well, e.g. <code>HEADER_TYPE_INDEX = 0</code>.</p>\n<hr />\n<pre><code>this.length = data.length;\n</code></pre>\n<p>Never needed.</p>\n<hr />\n<pre><code>public byte[] getData() {\n return data;\n}\n</code></pre>\n<p>You forgot to clone the bytes here, unless you want to name this <code>UnsafeMessage</code> of course.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T15:44:17.200",
"Id": "259948",
"ParentId": "252588",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T11:57:01.327",
"Id": "252588",
"Score": "2",
"Tags": [
"java",
"parsing",
"encoding"
],
"Title": "Message encode/decode library"
}
|
252588
|
<p>I wrote a code for sticky/fixed table header. I am bit confused with my coding, though it does my job. I know there are many jQuery codes available online. But I wanted to do it in plain <strong>JS</strong> with <strong>IE</strong> support. Now I want to see is there anything wrong/abuse of language in my code.</p>
<h3>Here my code:</h3>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/* Sticky table header starts here */
var table = document.getElementsByTagName("table");
table = [].slice.call(table);
var clonedTable = [];
document.addEventListener("DOMContentLoaded", function () {
for (i = 0; i < table.length; i++) {
function init() {
var wrapper = document.createElement("div"),
clone = table[i].cloneNode(true),
parent = table[i].parentNode;
clone.classList.add("fixed");
wrapper.classList.add("container");
for (let j = 0; j < clone.tBodies.length; j++) {
clone.removeChild(clone.tBodies[j]);
}
wrapper.appendChild(clone);
parent.insertBefore(wrapper, table[i]);
wrapper.appendChild(table[i]);
clonedTable.push(clone);
resizeFixed();
}
function resizeFixed() {
var ths = this.clonedTable[i].querySelectorAll('th'),
ths2 = table[i].querySelectorAll('th');
for (var u = 0; u < ths.length; u++) {
ths[u].style.width = ths2[u].offsetWidth + 'px';
}
}
init();
}
});
window.addEventListener('resize', function () {
for (let t = 0; t < clonedTable.length; t++) {
var ths = this.clonedTable[t].querySelectorAll('th'),
ths2 = table[t].querySelectorAll('th');
for (var u = 0; u < ths.length; u++) {
ths[u].style.width = ths2[u].offsetWidth + 'px';
}
}
});
window.addEventListener('scroll', function () {
var offset = this.pageYOffset;
for (var n = 0; n < table.length; n++) {
var tableOffsetTop = table[n].offsetTop,
tableOffsetBottom = tableOffsetTop + table[n].offsetHeight - table[n].tHead.offsetHeight;
if (offset < tableOffsetTop || offset > tableOffsetBottom)
clonedTable[n].style.display = 'none';
else if (offset >= tableOffsetTop && offset <= tableOffsetBottom)
clonedTable[n].style.display = 'table';
}
}); // working fine till now
/* sticky table header script ends here */</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
font: 1.2em normal Arial, sans-serif;
color: #34495E;
text-align: center;
}
.container {
width: 90%;
margin: auto;
}
table {
border-collapse: collapse;
width: 100%;
}
table th,
table td {
border: 1px solid #eee;
}
th,
td {
text-align: center;
padding: 5px 0;
}
.blue {
border: 2px solid #1ABC9C;
}
.blue thead {
background-color: #1ABC9C;
}
.purple {
border: 2px solid #9B59B6;
}
.purple thead {
background: #9B59B6;
}
thead {
color: white;
}
th,
td {
text-align: center;
padding: 5px 0;
}
tbody tr:hover {
background: #f1f5f7;
/* color:#FFFFFF; */
}
.fixed {
top: 0;
position: fixed;
width: auto;
display: none;
border: none;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="purple">
<thead>
<th>Colored Text</th>
<th>Color Preview</th>
<th>Color Name</th>
<th>Hex Value</th>
<th>RGB Value</th>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td>Fuscia</td>
<td>#f1a4b1</td>
<td>102, 74, 51</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Print</td>
<td>#ea12fb</td>
<td>41, 45, 21</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Pink</td>
<td>#aa12fa</td>
<td>55, 84, 100</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Gold</td>
<td>#abcdef</td>
<td>120, 210, 43</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Fuscia</td>
<td>#f1a4b1</td>
<td>102, 74, 51</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Print</td>
<td>#ea12fb</td>
<td>41, 45, 21</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Pink</td>
<td>#aa12fa</td>
<td>55, 84, 100</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Gold</td>
<td>#abcdef</td>
<td>120, 210, 43</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Pink</td>
<td>#aa12fa</td>
<td>55, 84, 100</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Gold</td>
<td>#abcdef</td>
<td>120, 210, 43</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Fuscia</td>
<td>#f1a4b1</td>
<td>102, 74, 51</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Print</td>
<td>#ea12fb</td>
<td>41, 45, 21</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Pink</td>
<td>#aa12fa</td>
<td>55, 84, 100</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Gold</td>
<td>#abcdef</td>
<td>120, 210, 43</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Pink</td>
<td>#aa12fa</td>
<td>55, 84, 100</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Gold</td>
<td>#abcdef</td>
<td>120, 210, 43</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Fuscia</td>
<td>#f1a4b1</td>
<td>102, 74, 51</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Print</td>
<td>#ea12fb</td>
<td>41, 45, 21</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Pink</td>
<td>#aa12fa</td>
<td>55, 84, 100</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Gold</td>
<td>#abcdef</td>
<td>120, 210, 43</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Pink</td>
<td>#aa12fa</td>
<td>55, 84, 100</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Gold</td>
<td>#abcdef</td>
<td>120, 210, 43</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Fuscia</td>
<td>#f1a4b1</td>
<td>102, 74, 51</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Print</td>
<td>#ea12fb</td>
<td>41, 45, 21</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Pink</td>
<td>#aa12fa</td>
<td>55, 84, 100</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Gold</td>
<td>#abcdef</td>
<td>120, 210, 43</td>
</tr>
</tbody>
</table>
<br>
<hr>
<br>
<table class="blue">
<thead>
<th>Colored Text</th>
<th>Color Preview</th>
<th>Color Name</th>
<th>Hex Value</th>
<th>RGB Value</th>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td>Fuscia</td>
<td>#f1a4b1</td>
<td>102, 74, 51</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Print</td>
<td>#ea12fb</td>
<td>41, 45, 21</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Pink</td>
<td>#aa12fa</td>
<td>55, 84, 100</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Gold</td>
<td>#abcdef</td>
<td>120, 210, 43</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Pink</td>
<td>#aa12fa</td>
<td>55, 84, 100</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Gold</td>
<td>#abcdef</td>
<td>120, 210, 43</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Fuscia</td>
<td>#f1a4b1</td>
<td>102, 74, 51</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Print</td>
<td>#ea12fb</td>
<td>41, 45, 21</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Pink</td>
<td>#aa12fa</td>
<td>55, 84, 100</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Gold</td>
<td>#abcdef</td>
<td>120, 210, 43</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Pink</td>
<td>#aa12fa</td>
<td>55, 84, 100</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Gold</td>
<td>#abcdef</td>
<td>120, 210, 43</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Fuscia</td>
<td>#f1a4b1</td>
<td>102, 74, 51</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Print</td>
<td>#ea12fb</td>
<td>41, 45, 21</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Pink</td>
<td>#aa12fa</td>
<td>55, 84, 100</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Gold</td>
<td>#abcdef</td>
<td>120, 210, 43</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Pink</td>
<td>#aa12fa</td>
<td>55, 84, 100</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Gold</td>
<td>#abcdef</td>
<td>120, 210, 43</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Fuscia</td>
<td>#f1a4b1</td>
<td>102, 74, 51</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Print</td>
<td>#ea12fb</td>
<td>41, 45, 21</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Pink</td>
<td>#aa12fa</td>
<td>55, 84, 100</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Gold</td>
<td>#abcdef</td>
<td>120, 210, 43</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Pink</td>
<td>#aa12fa</td>
<td>55, 84, 100</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Gold</td>
<td>#abcdef</td>
<td>120, 210, 43</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Fuscia</td>
<td>#f1a4b1</td>
<td>102, 74, 51</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Print</td>
<td>#ea12fb</td>
<td>41, 45, 21</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Pink</td>
<td>#aa12fa</td>
<td>55, 84, 100</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Gold</td>
<td>#abcdef</td>
<td>120, 210, 43</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Pink</td>
<td>#aa12fa</td>
<td>55, 84, 100</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Gold</td>
<td>#abcdef</td>
<td>120, 210, 43</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Fuscia</td>
<td>#f1a4b1</td>
<td>102, 74, 51</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Print</td>
<td>#ea12fb</td>
<td>41, 45, 21</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Pink</td>
<td>#aa12fa</td>
<td>55, 84, 100</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Gold</td>
<td>#abcdef</td>
<td>120, 210, 43</td>
</tr>
</tbody>
</table></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>Some of the things I've noticed:</p>\n<ul>\n<li>Avoid global variables</li>\n<li>It's a good decision to avoid <code>var</code> keyword as the variable declaration in 2020. Read about <code>let</code> and <code>const</code></li>\n<li>Some of the variables could be more descriptive</li>\n<li>Use classes instead of html tags for styling</li>\n<li>Instead of styling in JS. Add a CSS class in JS instead</li>\n<li>Look how packed with logic Your <code>for</code> loop is. It's a bit hard to understand + avoid complicated logic inside of loops. Performance is important</li>\n<li>It's not a good practice to separate the dom elements using <code><br></code></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-03T07:36:29.303",
"Id": "498685",
"Score": "0",
"body": "Thanks adam for your suggestion. My code works fine. I was stucked with my logic, that's why its bit difficult to see. I am working more on my coding to make it better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-03T08:15:05.713",
"Id": "498688",
"Score": "0",
"body": "@abjim keep it up ! :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T08:53:14.553",
"Id": "499272",
"Score": "0",
"body": "@abjim consider marking my response if it was helpful and You have no further questions : )"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-10T08:37:45.990",
"Id": "499492",
"Score": "0",
"body": "I'm bit confused with my JS part. in the domcontentloaded portion. Still waiting for further improvement."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-02T17:04:03.180",
"Id": "252941",
"ParentId": "252590",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T12:27:34.153",
"Id": "252590",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Sticky Table Header in Plain JS"
}
|
252590
|
<p>The code was written to generate the factorisation of numbers into primes in ascending order. E.g 3! ='2 * 3', 4!='2^3 * 3'. When I have huge numbers such as 100!, the run time becomes a problem. I want to have a code which will run in less time.</p>
<pre><code>from math import floor,sqrt,factorial
from decimal import Decimal
def prime(x):
if x==2 or x==3 or x==5:
return True
if (x%2==0) or (x%3==0) or (x%5==0) or (x==1):
return False
for i in range(6,floor(sqrt(x)),6):
if x%(i+1)==0:
return False
elif i%(i+5)==0:
return False
return True
def decomp(n):
y=factorial(n)
if y<7:
pri =list(filter(prime,range(1,y+1)))
else:
pri=list(filter(prime,range(1,floor(Decimal(y).sqrt()+1))))
a={};b=0
for i in pri:
while y%i==0:
y=y//i
b+=1
a[i]=b
b=0
if len(list(a.keys()))==1:
if list(a.values())!=[1]:
c=str(a.keys())+'^'+str(a.values())
else:
c=str(list(a.keys()))
elif len(list(a.keys()))>1:
if a[list(a.keys())[0]]>1:
c=str(list(a.keys())[0])+'^'+str(a[list(a.keys())[0]])
elif a[list(a.keys())[0]]==1:
c=str(list(a.keys())[0])
for key in list(a.keys())[1:]:
if a[key]!=1:
c+=' * '+str(key)+'^'+str(a[key])
elif a[key]==1:
c+=' * '+str(key)
return c
</code></pre>
|
[] |
[
{
"body": "<p>Your prime decomposition could be much (much) more efficient.</p>\n<p>Let's look at what you're doing right now : You create a big number (let's say <span class=\"math-container\">\\$100!\\$</span>), then get all the primes between between 1 and <span class=\"math-container\">\\$\\sqrt (100!)\\$</span> to then check if they are a factor of your number.</p>\n<p>One efficient but not "fun" approach would be to cache a predefined table of prime numbers up to a certain high value and use this cache to determine prime factorization.</p>\n<p>At the moment, you effectively check if a number is a prime twice, which is costly. Why not simply do this :</p>\n<pre><code>def prime_factorization(n):\n\n primes = []\n for i in range(2,int(sqrt(n))):\n if n == 1:\n return primes\n\n while n % i == 0:\n n = n // i\n primes.append(i)\n</code></pre>\n<p>Is it efficient? Not so much, but we only look at every number once. And since we start from</p>\n<p>How could it be more efficient? Our big problem is the <code>range(2,sqrt(n))</code>. We'd like to be a little bit more specific as to which number we look at. You could create a prime number generator (using the <code>yield</code> keyword) that would return only primes. There are a billion ways to create efficient prime number generators, so I'll skip on this. But then :</p>\n<pre><code>def prime_factorization(n):\n\n primes = []\n for i in prime_generator(from=2, to=sqrt(n)):\n if n == 1:\n return primes\n\n while n % i == 0:\n n = n / i\n primes.append(i)\n</code></pre>\n<p>Then you'd have something pretty fast and simple.</p>\n<p>Lastly, I would recommend wrapping all your code to print your result in another function, as it would make <code>decomp</code> clearer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T17:23:59.990",
"Id": "497771",
"Score": "0",
"body": "@superbrain replace `/`with `//`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T17:27:15.663",
"Id": "497773",
"Score": "0",
"body": "@superbrain You're right, `range` must be complaining for being passed a non-integer upper bound."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T17:29:44.013",
"Id": "497774",
"Score": "1",
"body": "@!EatBagels It seems OP only wants factorials to be factorized. In this case, the upper limit of `sqrt(n!)` is overkill. No prime factor will exceed `n`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T17:33:31.847",
"Id": "497775",
"Score": "0",
"body": "@ChristophFrings Yeah, even computing n! at all is overkill then (though easy and cheap in Python)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T19:22:47.340",
"Id": "497794",
"Score": "0",
"body": "@superbrain You're right, I wrote this answer fast-ish and didn't test out my code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T19:24:42.277",
"Id": "497796",
"Score": "0",
"body": "@ChristophFrings Excellent point, although in this case I'm \"lucky\" because since the range is never evaluated as a list, the function will terminate before the range goes higher than `n`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T20:08:30.480",
"Id": "497809",
"Score": "0",
"body": "Now `prime_factorization(6)` returns `None`. And there's still `/` in the second solution. With numbers like 100! it matters, as you'd get rounding errors, which leads to wrong results and introduces factors much larger than n (so it'll be slow after all)."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T14:46:54.850",
"Id": "252594",
"ParentId": "252593",
"Score": "3"
}
},
{
"body": "<p>Given that you do <code>y=factorial(n)</code> <em>inside</em> your <code>decomp(n)</code> function, I'm gonna assume that this is really about factoring factorials. And my review is gonna be:</p>\n<ul>\n<li><strong>Don't compute the factorial at all.</strong></li>\n<li>Use a better function name.</li>\n<li>Document what the function does.</li>\n<li>Separate the factorization from the presentation. Return something more useful than a string, like pairs of primes and their exponents. That can then be pretty-formatted if desired, or used for computations.</li>\n<li><strong>Test your code</strong>, because for example for <code>decomp(10)</code> returns <code>'2 * 3 * 5 * 7'</code>, missing the exponents.</li>\n</ul>\n<p>Instead of computing the factorial and then factoring that, factor all the numbers from 1 to n and combine their prime factorizations. Or even better... compute, for every prime from 1 to n, its exponent in n!. Let's say we want to find the exponent for 3 in 100!. Every third number from 1 to 100 (i.e., 3, 6, 9, 12, etc) contributes a factor 3, so there are <span class=\"math-container\">\\$\\lfloor\\frac{100}{3}\\rfloor=33\\$</span> numbers that contribute factor 3. Of those, every third number (i.e., 9, 18, 27, etc) contributes <em>another</em> factor 3. Of those, every third number (i.e., 27, 54 and 81) contributes <em>yet another</em>. And 81 even contributes a fourth. So the exponent for 3 in 100! is 33+11+3+1=48.</p>\n<p>Here's an O(n) solution doing that. Takes my laptop about 0.33 seconds to factor 1,000,000!. Compare that to just computing <code>math.factorial(10**6)</code>, which already takes about 10 seconds.</p>\n<pre class=\"lang-python prettyprint-override\"><code>def factorial_factorization(n):\n """Return the prime factorization of n! as list of (prime, exponent) pairs."""\n \n # Compute primes from 2 to n, see https://cp-algorithms.com/algebra/prime-sieve-linear.html\n lp = [None] * (n+1)\n primes = []\n for i in range(2, n+1):\n if not lp[i]:\n primes.append(i)\n lp[i] = i\n for p in primes:\n if p > lp[i] or i * p > n:\n break\n lp[i * p] = p\n\n # Find prime exponents for n!\n result = []\n for p in primes:\n e = 0\n m = n // p\n while m:\n e += m\n m //= p\n result.append((p, e))\n return result\n</code></pre>\n<p>Demo:</p>\n<pre><code>>>> factorial_factorization(3)\n[(2, 1), (3, 1)]\n\n>>> factorial_factorization(4)\n[(2, 3), (3, 1)]\n\n>>> factorial_factorization(100)\n[(2, 97), (3, 48), (5, 24), (7, 16), (11, 9), (13, 7), (17, 5), (19, 5), (23, 4), (29, 3), (31, 3), (37, 2), (41, 2), (43, 2), (47, 2), (53, 1), (59, 1), (61, 1), (67, 1), (71, 1), (73, 1), (79, 1), (83, 1), (89, 1), (97, 1)]\n\n>>> factorial_factorization(10**6)[:10]\n[(2, 999993), (3, 499993), (5, 249998), (7, 166664), (11, 99998), (13, 83332), (17, 62497), (19, 55553), (23, 45453), (29, 35713)]\n</code></pre>\n<p>If you want a less useful but prettier presentation, that's easy to do then:</p>\n<pre><code>>>> n = 42\n>>> print(f'{n}! =', ' * '.join(f'{p}^{e}' if e > 1 else f'{p}'\n for p, e in factorial_factorization(n)))\n42! = 2^39 * 3^19 * 5^9 * 7^6 * 11^3 * 13^3 * 17^2 * 19^2 * 23 * 29 * 31 * 37 * 41\n</code></pre>\n<p>Checking that:</p>\n<pre><code>>>> s = '2^39 * 3^19 * 5^9 * 7^6 * 11^3 * 13^3 * 17^2 * 19^2 * 23 * 29 * 31 * 37 * 41'\n>>> (result := eval(s.replace('^', '**')))\n1405006117752879898543142606244511569936384000000000\n\n>>> (expect := math.factorial(42))\n1405006117752879898543142606244511569936384000000000\n\n>>> result == expect\nTrue\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T18:10:55.913",
"Id": "252609",
"ParentId": "252593",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T14:22:24.640",
"Id": "252593",
"Score": "4",
"Tags": [
"python-3.x",
"mathematics",
"objective-c-runtime"
],
"Title": "Generate prime factorisations of factorial numbers"
}
|
252593
|
<p>I recently just stumbled upon a post regarding Google Foobar Level 2 and decided to try it out myself but starting from Level 1. The description and code are shown below.</p>
<blockquote>
<p>Write a function called <code>answer(data, n)</code> that takes in a list of less
than 100 integers and a number <em>n</em>, and returns that same list but with all of the numbers that occur more than <em>n</em> times removed entirely. The returned list should retain the same ordering as the original list - you don't want to mix up those carefully planned shift rotations! For instance, if <em>data</em> was <code>[5, 10, 15, 10, 7]</code>
and <em>n</em> was <code>1</code>, <code>answer(data, n)</code> would return the list <code>[5, 15, 7]</code> because 10 occurs
twice, and was thus removed from the list entirely.</p>
<p>Constrains:</p>
<p>Standard libraries are supported except for bz2, crypt, fcntl, mmap,
pwd, pyexpat, select, signal, termios, thread, time, unicodedata, zipimport, zlib.</p>
<p>Test Cases:</p>
<p>Inputs:<br />
(int list) <em>data</em> = <code>[1, 2, 3]</code><br />
(int) <em>n</em> = <code>0</code><br />
Output:<br />
(int list) <code>[]</code></p>
<p>Inputs:<br />
(int list) <em>data</em> = <code>[1, 2, 2, 3, 3, 3, 4, 5, 5]</code><br />
(int) <em>n</em> = <code>1</code><br />
Output:<br />
(int list) <code>[1, 4]</code></p>
<p>Inputs:<br />
(int list) <em>data</em> = <code>[1, 2, 3]</code><br />
(int) <em>n</em> = <code>6</code><br />
Output:<br />
(int list) <code>[1, 2, 3]</code></p>
</blockquote>
<p>Code:</p>
<pre><code>def answer(data, n):
if len(data) > 99:
exit('List contains more than 100 elements')
print('data:\n', data) #for error-checking
count = dict()
for i in data:
count.setdefault(i, 0)
count[i] += 1
print('count:\n', count) #for error-checking
for k, v in count.items():
if v > n:
for i in range(v):
data.remove(k)
return data
</code></pre>
<p>I decided to also test the code myself by using test cases and a new list containing random numbers</p>
<pre><code>data1 = [1, 2, 3]
n1 = 0
data2 = [1, 2, 2, 3, 3, 3, 4, 5, 5]
n2 = 1
data3 = [1, 2, 3]
n3 = 6
data4 = [random.randint(1, 15) for i in range(0, 99)]
n4 = 6
ans1 = answer(data1, n1)
print('ans1:\n', ans1, '\n')
ans2 = answer(data2, n2)
print('ans2:\n', ans2, '\n')
ans3 = answer(data3, n3)
print('ans3:\n', ans3, '\n')
ans4 = answer(data4, n4)
print('ans4:\n', ans4, '\n')
</code></pre>
<p>Output:</p>
<pre><code>data:
[1, 2, 3]
count:
{1: 1, 2: 1, 3: 1}
ans1:
[]
data:
[1, 2, 2, 3, 3, 3, 4, 5, 5]
count:
{1: 1, 2: 2, 3: 3, 4: 1, 5: 2}
ans2:
[1, 4]
data:
[1, 2, 3]
count:
{1: 1, 2: 1, 3: 1}
ans3:
[1, 2, 3]
data:
[15, 9, 14, 10, 13, 8, 7, 2, 10, 3, 10, 11, 9, 9, 10, 7, 5, 11, 12, 14, 1, 5, 14, 15, 11, 2, 13, 2, 6, 1, 6, 8, 3, 15, 8, 6, 6, 13, 14, 14, 2, 14, 12, 6, 15, 4, 7, 5, 13, 8, 8, 4, 7, 15, 6, 1, 2, 11, 14, 6, 8, 4, 10, 4, 2, 9, 6, 14, 11, 12, 8, 15, 7, 15, 6, 1, 14, 8, 5, 14, 6, 10, 8, 1, 4, 15, 11, 9, 11, 10, 13, 13, 9, 7, 7, 4, 4, 12, 12]
count:
{15: 8, 9: 6, 14: 10, 10: 7, 13: 6, 8: 9, 7: 7, 2: 6, 3: 2, 11: 7, 5: 4, 12: 5, 1: 5, 6: 10, 4: 7}
ans4:
[9, 13, 2, 3, 9, 9, 5, 12, 1, 5, 2, 13, 2, 1, 3, 13, 2, 12, 5, 13, 1, 2, 2, 9, 12, 1, 5, 1, 9, 13, 13, 9, 12, 12]
</code></pre>
<p>Any input is appreciated. Thank you :-)</p>
|
[] |
[
{
"body": "<pre><code>if len(data) > 99:\n exit('List contains more than 100 elements')\n</code></pre>\n<p>I'd change that error message to something like <code>'List contains a hundred or more elements'</code>. I might also raise a <code>ValueError</code> instead of calling <code>exit</code>. I think that's more appropriate for an error that the user may want to catch.</p>\n<hr />\n<p>You can get rid of your call to <code>setdefault</code> by using a <code>defaultdict</code> instead:</p>\n<pre><code>from collections import defaultdict\n\n. . .\n\ncount = defaultdict(int) # int is a function that returns 0 when no args are given to it\nfor i in data:\n count[i] += 1\n</code></pre>\n<p>The gain here isn't huge, but they're handy in many cases.</p>\n<p><code>collections.Counter</code> would probably be appropriate here as well, but I've only used it once, so I can't show a good example of it.</p>\n<hr />\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T15:31:11.437",
"Id": "252597",
"ParentId": "252595",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "252597",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T14:53:05.237",
"Id": "252595",
"Score": "2",
"Tags": [
"python",
"beginner",
"python-3.x",
"programming-challenge"
],
"Title": "Google Foobar Level 1 - Minion Task Schedule"
}
|
252595
|
<p>I am working on a <strong><a href="https://github.com/Ajax30/twigPress/" rel="nofollow noreferrer">online newspaper/blogging application</a></strong> with <strong>CodeIgniter 3.1.8</strong> and Bootstrap 4. I have decided to add themes to it. The application is <strong>not HMVC</strong>, only MVC.</p>
<p>I thought it was a good idea to use the <em>Twig</em> template engine to the theme(s). For this purpose, I use <strong><a href="https://github.com/kenjis/codeigniter-ss-twig" rel="nofollow noreferrer">CodeIgniter Simple and Secure Twig</a></strong>.</p>
<p>The theme's templates, placed in <code>application\views\themes\caminar</code> (caminar is the current theme's name) have the extension <code>.twig</code>, not <code>.php</code>.</p>
<p>The layout.twig file contains the "master layout code":</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>{{site_title}} | {{tagline}}</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="{{maincss}}">
</head>
<body>
<!-- Header -->
<header id="header">
<div class="logo"><a href="/">{{site_title}}</a></div>
</header>
<section id="main">
<div class="inner">
{% if singlePost is defined %}
{{include(singlePost)}}
{% elseif pageTemplate is defined %}
{{include(pageTemplate)}}
{% elseif notFound is defined %}
{{include(notFound)}}
{% else %}
{{ include('themes/caminar/templates/posts.twig') }}
{% endif %}
</div>
</section>
<!-- Footer -->
<footer id="footer">
<div class="container">
<ul class="icons">
<li><a href="{{twitter}}" target="_blank" class="icon fa-twitter"><span class="label">Twitter</span></a></li>
<li><a href="{{facebook}}" target="_blank" class="icon fa-facebook"><span class="label">Facebook</span></a></li>
<li><a href="{{instagram}}" target="_blank" class="icon fa-instagram"><span class="label">Instagram</span></a></li>
<li><a href="mailto:{{company_email}}" class="icon fa-envelope-o"><span class="label">Email</span></a></li>
</ul>
{% if pages %}
<ul class="icons">
{% for page in pages %}
<li><a href="{{base_url}}/pages/page/{{page.id}}">{{page.title}}</a></li>
{% endfor %}
</ul>
{% endif %}
</div>
<div class="copyright">
&copy; {{company_name}}. All rights reserved. Design by <a href="https://templated.co" target="_blank">TEMPLATED</a>
</div>
</footer>
</body>
</html>
</code></pre>
<p>The posts.twig file displays the posts:</p>
<pre><code><section class="wrapper style1">
{% for post in posts %}
{% if loop.first %}
<div class="image fit flush">
<a href="{{base_url}}{{post.slug}}">
<img src="{{base_url}}/assets/img/posts/{{post.post_image}}" alt="{{post.title}}" />
</a>
</div>
<header class="special">
<h2>{{post.title}}</h2>
<p>{{post.description}}</p>
</header>
<div class="content">{{post.content|raw}}</div>
{% else %}
<div class="spotlight {% if (loop.index is even) %}alt{% endif %}">
<div class="image flush">
<a href="{{base_url}}{{post.slug}}">
<img src="{{base_url}}/assets/img/posts/{{post.post_image}}" alt="{{post.title}}" />
</a>
</div>
<div class="inner">
<h3>{{post.title}}</h3>
<p>{{post.description}}</p>
<div class="{% if (loop.index is even) %}text-right{% else %}text-left{% endif %}">
<a href="{{base_url}}{{post.slug}}" class="button special small">Read More</a>
</div>
</div>
</div>
{% endif %}
{% endfor %}
</section>
<div class="pagination-container">{{ pagination|raw }}</div>
</code></pre>
<p>Finally, the posts controller is the main reason for my concerns regarding the quality of the code:</p>
<pre><code>class Posts extends CI_Controller {
public function __construct()
{
parent::__construct();
}
private function _initPagination($path, $totalRows, $query_string_segment = 'page') {
//load and configure pagination
$this->load->library('pagination');
$config['base_url'] = base_url($path);
$config['query_string_segment'] = $query_string_segment;
$config['enable_query_strings'] =TRUE;
$config['reuse_query_string'] =TRUE;
$config['total_rows'] = $totalRows;
$config['per_page'] = 12;
if (!isset($_GET[$config['query_string_segment']]) || $_GET[$config['query_string_segment']] < 1) {
$_GET[$config['query_string_segment']] = 1;
}
$this->pagination->initialize($config);
$limit = $config['per_page'];
$offset = ($this->input->get($config['query_string_segment']) - 1) * $limit;
return ['limit' => $limit, 'offset' => $offset];
}
public function index() {
//call initialization method
$config = $this->_initPagination("/", $this->Posts_model->get_num_rows());
$data = $this->Static_model->get_static_data();
$data['base_url'] = base_url("/");
$data['pages'] = $this->Pages_model->get_pages();
$data['categories'] = $this->Categories_model->get_categories();
//use limit and offset returned by _initPaginator method
$data['posts'] = $this->Posts_model->get_posts($config['limit'], $config['offset']);
$this->twig->addGlobal('maincss', base_url('themes/caminar/assets/css/main.css'));
$this->twig->addGlobal('pagination', $this->pagination->create_links());
$this->twig->display('themes/caminar/layout', $data);
}
public function byauthor($authorid){
//load and configure pagination
$this->load->library('pagination');
$config['base_url'] = base_url('/posts/byauthor/' . $authorid);
$config['query_string_segment'] = 'page';
$config['total_rows'] = $this->Posts_model->posts_by_author_count($authorid);
$config['per_page'] = 12;
if (!isset($_GET[$config['query_string_segment']]) || $_GET[$config['query_string_segment']] < 1) {
$_GET[$config['query_string_segment']] = 1;
}
$limit = $config['per_page'];
$offset = ($this->input->get($config['query_string_segment']) - 1) * $limit;
$this->pagination->initialize($config);
$data = $this->Static_model->get_static_data();
$data['base_url'] = base_url("/");
$data['pages'] = $this->Pages_model->get_pages();
$data['categories'] = $this->Categories_model->get_categories();
$data['posts'] = $this->Posts_model->get_posts_by_author($authorid, $limit, $offset);
$data['posts_count'] = $this->Posts_model->posts_by_author_count($authorid);
$data['posts_author'] = $this->Posts_model->posts_author($authorid);
$this->twig->addGlobal('maincss', base_url('themes/caminar/assets/css/main.css'));
$this->twig->addGlobal('pagination', $this->pagination->create_links());
$this->twig->display('themes/caminar/layout', $data);
}
public function post($slug) {
$data = $this->Static_model->get_static_data();
$data['pages'] = $this->Pages_model->get_pages();
$data['categories'] = $this->Categories_model->get_categories();
$data['authors'] = $this->Usermodel->getAuthors();
$data['posts'] = $this->Posts_model->sidebar_posts($limit=5, $offset=0);
$data['post'] = $this->Posts_model->get_post($slug);
$data['author_image'] = isset($data['post']->avatar) && $data['post']->avatar !== '' ? $data['post']->avatar : 'default-avatar.png';
//CSS, JS and other resources add to twig here, because PHP and Codeigniter functions are not available from Twig templates
$this->twig->addGlobal('maincss', base_url('themes/caminar/assets/css/main.css'));
if ($data['categories']) {
foreach ($data['categories'] as &$category) {
$category->posts_count = $this->Posts_model->count_posts_in_category($category->id);
}
}
if (!empty($data['post'])) {
// Overwrite the default tagline with the post title
$data['tagline'] = $data['post']->title;
// Get post comments
$post_id = $data['post']->id;
$data['comments'] = $this->Comments_model->get_comments($post_id);
$this->twig->addGlobal('singlePost','themes/caminar/templates/singlepost.twig');
$this->twig->display('themes/caminar/layout', $data);
} else {
$data['tagline'] = "Page not found";
$this->twig->addGlobal('notFound','themes/caminar/templates/404.twig');
$this->twig->display('themes/caminar/layout', $data);
}
}
}
</code></pre>
<h3>Concerns:</h3>
<ol>
<li>Is the code (too) repetitive?</li>
<li>Is the code over engineered?</li>
</ol>
|
[] |
[
{
"body": "<p>Well just some refactoring.</p>\n<p>i.e. <code>$this->twig->display('themes/caminar/layout', $data);</code> only needs to appear once.</p>\n<p>When you have code that repeats inside an <code>if</code>/<code>else</code>, it can come outside of that block.</p>\n<pre><code>if (!empty($data['post'])) {\n // Overwrite the default tagline with the post title\n $data['tagline'] = $data['post']->title;\n\n // Get post comments\n $post_id = $data['post']->id;\n $data['comments'] = $this->Comments_model->get_comments($post_id);\n $this->twig->addGlobal('singlePost','themes/caminar/templates/singlepost.twig');\n $this->twig->display('themes/caminar/layout', $data);\n} else {\n $data['tagline'] = "Page not found";\n $this->twig->addGlobal('notFound','themes/caminar/templates/404.twig');\n $this->twig->display('themes/caminar/layout', $data);\n}\n</code></pre>\n<p>Becomes</p>\n<pre><code>if (!empty($data['post'])) {\n // Overwrite the default tagline with the post title\n $data['tagline'] = $data['post']->title;\n\n // Get post comments\n $post_id = $data['post']->id;\n $data['comments'] = $this->Comments_model->get_comments($post_id);\n $this->twig->addGlobal('singlePost','themes/caminar/templates/singlepost.twig');\n} else {\n $data['tagline'] = "Page not found";\n $this->twig->addGlobal('notFound','themes/caminar/templates/404.twig');\n}\n$this->twig->display('themes/caminar/layout', $data);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T00:58:22.020",
"Id": "252630",
"ParentId": "252596",
"Score": "1"
}
},
{
"body": "<p>Since your concern is chiefly falling on the controller and I don't have particular expertise with twig scripting, I'll speak on the controller. <strong>Please do not take my snippet at the end to be ready for copy-pasta</strong> -- it is not tested and it is likely that I have made mistakes and/or misunderstood the data that is being passed into these controllers. Hopefully the itemized advice will help you to realize some techniques to clean up your methods.</p>\n<ol>\n<li><p><a href=\"https://www.php-fig.org/psr/psr-12/#:%7E:text=Method%20names,%20no%20meaning.\" rel=\"nofollow noreferrer\">PSR-12 says: Method names MUST NOT be prefixed with a single underscore to indicate protected or private visibility. That is, an underscore prefix explicitly has no meaning.</a></p>\n</li>\n<li><p>I prefer to declare data types on all incoming parameters and return values. Not only does this help with debugging, it also coerces values like numeric strings to ints and floats.</p>\n</li>\n<li><p>Rather than repeat the <code>$config</code> each time you want to declare a new element, just declare the full array in one go.</p>\n</li>\n<li><p>Better yet, don't declare the <code>$config</code> variable at all (or any single-use variables for that matter). Any time you declare a variable then only actually use it one time, then this is a good argument for writing the value directly into where you originally had the variable. There are some exceptions to this, for instance, you want to be declarative about the value or, perhaps, directly injecting the value makes the code less readable / too wide.</p>\n</li>\n<li><p>We shouldn't be seeing any instances of <code>$_GET</code> in your CI code. CI passes all this slash-delimited data in the url and all of the data is instantly available in your controller method's argument list. From memory, I don't think I ever use <code>$this->input->get()</code> in any of my CI work.</p>\n</li>\n<li><p>I prefer to use camelCase variable naming because PHPStorm does a good job of finding my misspellings and it is more concise than snake_case. Well, actually, <code>$queryStringSegment</code> is too verbose and only vaguely describes the value, <code>$segment</code> is just as vague, but more concise. Perhaps there is a better variable name to use.</p>\n</li>\n<li><p>You may have confused me with <code>/pages/page/{{page.id}}</code>, but I am assuming that <code>index()</code> method is what is receiving these page load requests and the only value that you actually need is the last one <code>{{page.id}}</code>. Add <code>$pageNumber</code> as the lone parameter of <code>index()</code> and pass the value along with other expected values to <code>_initPagination()</code>. Ensure that <code>$pageNumber</code> cannot be less than 1 -- I'll recommend <code>max()</code>.</p>\n</li>\n</ol>\n<hr />\n<pre><code>class Posts extends CI_Controller\n{ \n public function __construct()\n {\n parent::__construct();\n }\n\n private function _initPagination(string $baseUrl, int $totalRows, string $segment = 'page', ?int $pageNumber = 1): array\n {\n $this->load->library('pagination');\n $limit = 12;\n\n $this->pagination->initialize([\n 'base_url' => $baseUrl,\n 'query_string_segment' => $segment,\n 'enable_query_strings' => true,\n 'reuse_query_string' => true,\n 'total_rows' = $totalRows,\n 'per_page' => $limit,\n ]);\n\n return [$limit, $pageNumber - 1];\n }\n\n public function index(int $pageNumber = 1): void\n { \n $baseUrl = base_url('/');\n\n //call initialization method\n $rangeParameters = $this->_initPagination(\n $baseUrl,\n $this->Posts_model->get_num_rows(),\n 'page',\n max(1, $pageNumber),\n );\n\n $data = $this->Static_model->get_static_data()\n + [\n 'base_url' => $baseUrl,\n 'pages' => $this->Pages_model->get_pages(),\n 'categories' => $this->Categories_model->get_categories(),\n 'posts' = $this->Posts_model->get_posts(...$rangeParameters)\n ];\n\n $this->twig->addGlobal('maincss', base_url('themes/caminar/assets/css/main.css'));\n $this->twig->addGlobal('pagination', $this->pagination->create_links());\n $this->twig->display('themes/caminar/layout', $data);\n }\n ...\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T11:10:33.377",
"Id": "497875",
"Score": "0",
"body": "Very professional. Many thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T11:13:06.703",
"Id": "497876",
"Score": "0",
"body": "Please consider giving an answer to **[this question](https://stackoverflow.com/q/65003286/4512005)**. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T12:48:25.113",
"Id": "497888",
"Score": "0",
"body": "@mickmackusa Regarding Point 6. PhpStorm (as with most IDE's) does a fine job of finding spelling mistakes regardless of which \"case\" style you prefer. Which means, it works just as well with snake_case as it does with camelCase etc. I understand that is your own preference but that particular reason may be misleading to some folks. I use snake_case / camelCase where applicable, due to coding/style conventions being used, under PhpStorm and it plays nice with both."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T12:55:11.983",
"Id": "497889",
"Score": "0",
"body": "My point is that although camelCase smashes letters together, the IDE is smart enough to understanding/catch spelling mistakes, so I recommend the more concise variable naming convention. I have a habit of not using snake_case anywhere in my projects. This also gives an obvious separation between my entity names and native function calls. I am not misleading anyone; I said \"I prefer\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T22:50:14.833",
"Id": "498118",
"Score": "1",
"body": "@Raz Just so you know, I am still interested in figuring out your bug with POST'ing from the form to the controller via ajax. I think there is a vital detail that I am not being shown. Please show me (via 3v4l.org link or similar) 1. the exact generated source code of the form that is doing the post 2. The `Network > XHR > Response tab` text from the Comments/create controller that shows `exit(var_export(['stream' => $this->input->raw_input_stream, 'post' => $this->input->post(), 'slug' => $post_slug], true));` so that I can see that the controller is working."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T22:56:26.473",
"Id": "498119",
"Score": "0",
"body": "@Raz This idea just popped into my head... What if you are firing two `POST` requests! What if your ajax call goes first, sends all of the POST data, then clears the `$fields`, then your form's default behavior (which is not \"prevent\"ed) fires a second `POST` request -- now there are no field values! and you only actually see the results of the second request. This feels very likely to me. https://api.jquery.com/event.preventdefault/ See how many requests are being fired in your `Network > XHR > Response tab` when you submit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T08:17:26.680",
"Id": "498141",
"Score": "0",
"body": "@mickmackusa It needs not be prevented. I call the `submitHandler` method of the validator. It is standard use. But I will check."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T08:19:34.690",
"Id": "498142",
"Score": "0",
"body": "@Raz Okay, I wasn't sure (I don't use `submitHandler`). Have you made any progress? Any new clues?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T08:21:45.913",
"Id": "498143",
"Score": "0",
"body": "@mickmackusa There is one request, With status 200. I will solve it. I insist that this app turns up excellent. One day :)"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T06:49:05.813",
"Id": "252635",
"ParentId": "252596",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "252635",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T15:04:27.693",
"Id": "252596",
"Score": "1",
"Tags": [
"php",
"mvc",
"codeigniter",
"twig"
],
"Title": "Implementing Pagination with Twig in Codeigniter 3"
}
|
252596
|
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/252488/231235">std::array and std::vector Type Arbitrary Nested Iterable Generator Functions Implementation in C++</a> and the previous questions about recursive functions, including <a href="https://codereview.stackexchange.com/q/250743/231235">A Summation Function For Arbitrary Nested Vector Implementation In C++</a>, <a href="https://codereview.stackexchange.com/q/252053/231235">A recursive_count_if Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>, <a href="https://codereview.stackexchange.com/q/252225/231235">A recursive_count_if Function with Specified value_type for Various Type Arbitrary Nested Iterable Implementation in C++</a>, <a href="https://codereview.stackexchange.com/q/252325/231235">A recursive_count_if Function with Automatic Type Deducing from Lambda for Various Type Arbitrary Nested Iterable Implementation in C++</a> and <a href="https://codereview.stackexchange.com/q/252404/231235">A recursive_count_if Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++</a>. Besides the <code>std::array</code> and <code>std::vector</code> cases, I am trying to implement other functions <code>n_dim_deque_generator</code> and <code>n_dim_list_generator</code> which purpose are similar as <code>n_dim_array_generator</code> and <code>n_dim_vector_generator</code>. In other words, <code>n_dim_deque_generator</code> function can construct nested <code>std::deque</code>s with the given parameters and <code>n_dim_list_generator</code> function can construct nested <code>std::list</code>s with the given parameters.</p>
<p><strong>The usage description</strong></p>
<p>As similar to the usage of <code>n_dim_vector_generator</code>, there are four key parts in the usage <code>n_dim_deque_generator<2, int>(1, 3)</code>. The first number <code>2</code> represents the nested layers, the second parameter <code>int</code> represents the type of base elements, the third parameter <code>1</code> represents the input element which would be filled in, and the fourth parameter <code>3</code> represents the element count in each layer.</p>
<p><strong>The experimental implementation</strong></p>
<p>The experimental implementation of <code>n_dim_deque_generator</code> function and <code>n_dim_list_generator</code> function:</p>
<pre><code>template<std::size_t dim, class T>
auto n_dim_deque_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
std::deque<decltype(n_dim_deque_generator<dim - 1>(input, times))> output;
output.resize(times);
std::fill(std::begin(output), std::end(output), n_dim_deque_generator<dim - 1>(input, times));
return output;
}
}
template<std::size_t dim, class T>
auto n_dim_list_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
std::list<decltype(n_dim_list_generator<dim - 1>(input, times))> output;
output.resize(times);
std::fill(std::begin(output), std::end(output), n_dim_list_generator<dim - 1>(input, times));
return output;
}
}
</code></pre>
<p><strong>Test cases</strong></p>
<p>The test cases of <code>n_dim_deque_generator</code> function and <code>n_dim_list_generator</code> function are as below. The test cases of <code>n_dim_vector_generator</code> function and <code>n_dim_array_generator</code> function are also listed, for comparison purposes.</p>
<pre><code>constexpr std::size_t dims_setting = 8;
int input_element = 3;
constexpr std::size_t element_count = 2;
// n_dim_vector_generator function usage with recursive_reduce function and recursive_count_if function
auto test_vector1 = n_dim_vector_generator<dims_setting, int>(input_element, element_count);
std::cout << "recursive_reduce output: " << recursive_reduce(test_vector1, 0) << std::endl;
std::cout << "recursive_count_if output: " << recursive_count_if<dims_setting>(test_vector1, [](auto& i) {return i == 3; }) << std::endl;
// n_dim_array_generator function usage with recursive_reduce function and recursive_count_if function
auto test_array1 = n_dim_array_generator<dims_setting, element_count, int>(input_element);
std::cout << "recursive_reduce output: " << recursive_reduce(test_array1, 0) << std::endl;
std::cout << "recursive_count_if output: " << recursive_count_if<dims_setting>(test_array1, [](auto& i) {return i == 3; }) << std::endl;
// n_dim_deque_generator function usage with recursive_reduce function and recursive_count_if function
auto test_deque1 = n_dim_deque_generator<dims_setting, int>(input_element, element_count);
std::cout << "recursive_reduce output: " << recursive_reduce(test_deque1, 0) << std::endl;
std::cout << "recursive_count_if output: " << recursive_count_if<dims_setting>(test_deque1, [](auto& i) {return i == 3; }) << std::endl;
// n_dim_list_generator function usage with recursive_reduce function and recursive_count_if function
auto test_list1 = n_dim_list_generator<dims_setting, int>(input_element, element_count);
std::cout << "recursive_reduce output: " << recursive_reduce(test_list1, 0) << std::endl;
std::cout << "recursive_count_if output: " << recursive_count_if<dims_setting>(test_list1, [](auto& i) {return i == 3; }) << std::endl;
</code></pre>
<p>The output of this test is as follows.</p>
<pre><code>recursive_reduce output: 768
recursive_count_if output: 256
recursive_reduce output: 768
recursive_count_if output: 256
recursive_reduce output: 768
recursive_count_if output: 256
recursive_reduce output: 768
recursive_count_if output: 256
</code></pre>
<p><strong>Notes</strong></p>
<p>The <code>n_dim_vector_generator</code> function and <code>n_dim_array_generator</code> function have been updated as follows. Thanks to G. Sliepen for <a href="https://codereview.stackexchange.com/a/252490/231235">answering the previous question</a>.</p>
<pre><code>template<std::size_t dim, class T>
auto n_dim_vector_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
std::vector<decltype(n_dim_vector_generator<dim - 1>(input, times))> output;
output.reserve(times);
std::fill_n(std::back_inserter(output), times, n_dim_vector_generator<dim - 1>(input, times));
return output;
}
}
template<std::size_t dim, std::size_t times, class T>
auto n_dim_array_generator(T input)
{
if constexpr (dim == 0)
{
return input;
}
else
{
std::array<decltype(n_dim_array_generator<dim - 1, times>(input)), times> output;
std::fill(std::begin(output), std::end(output), n_dim_array_generator<dim - 1, times>(input));
return output;
}
}
</code></pre>
<p><a href="https://godbolt.org/z/vczahq" rel="nofollow noreferrer">A Godbolt link is here.</a></p>
<p>All suggestions are welcome.</p>
<p>The summary information:</p>
<ul>
<li><p>Which question it is a follow-up to?</p>
<p><a href="https://codereview.stackexchange.com/q/252488/231235">std::array and std::vector Type Arbitrary Nested Iterable Generator Functions Implementation in C++</a> and</p>
<p>the previous questions about recursive functions, including</p>
<ul>
<li><p><a href="https://codereview.stackexchange.com/q/250743/231235">A Summation Function For Arbitrary Nested Vector Implementation In C++</a>,</p>
</li>
<li><p><a href="https://codereview.stackexchange.com/q/252053/231235">A recursive_count_if Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>,</p>
</li>
<li><p><a href="https://codereview.stackexchange.com/q/252225/231235">A recursive_count_if Function with Specified value_type for Various Type Arbitrary Nested Iterable Implementation in C++</a>,</p>
</li>
<li><p><a href="https://codereview.stackexchange.com/q/252325/231235">A recursive_count_if Function with Automatic Type Deducing from Lambda for Various Type Arbitrary Nested Iterable Implementation in C++</a> and</p>
</li>
<li><p><a href="https://codereview.stackexchange.com/q/252404/231235">A recursive_count_if Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++</a></p>
</li>
</ul>
</li>
<li><p>What changes has been made in the code since last question?</p>
<p>The <code>n_dim_deque_generator</code> function and <code>n_dim_list_generator</code> function have been added.</p>
</li>
<li><p>Why a new review is being asked for?</p>
<p>I am not sure if it is a good idea to use <code>resize</code> function and <code>std::fill</code> function in both <code>n_dim_deque_generator</code> and <code>n_dim_list_generator</code> implementation. If there is any further possible improvement, please let me know.</p>
</li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T17:38:27.027",
"Id": "252605",
"Score": "1",
"Tags": [
"c++",
"recursion",
"c++20"
],
"Title": "std::deque and std::list Type Arbitrary Nested Iterable Generator Functions Implementation in C++"
}
|
252605
|
<p>I have code in Python 3 where I fetch data from the GitHub API, and I want some advice on the architecture of this code.</p>
<pre><code>import urllib.request, urllib.parse, urllib.error
import json
import sys
from collections import Counter
from datetime import datetime, timedelta, date
from tabulate import tabulate
from LanguagesRepoCounter import LanguagesCounter
from RepoListLanguages import RepoListLanguages
#getting the date of one mounth ago from today
One_Mouth_ago_date = datetime.date(datetime.now()) - timedelta(days=30)
url = 'https://api.github.com/search/repositories?q=created:%3E'+One_Mouth_ago_date.isoformat()+'&sort=stars&order=desc&page=1&per_page=100'
data_connection_request = urllib.request.urlopen(url)
unicoded_data = data_connection_request.read().decode()
try:
json_data = json.loads(unicoded_data)
except:
json_data = None
# testing retrieaved data
if not json_data or json_data["total_count"]<1:
print(json_data)
sys.exit('######## Failure To Retrieve ########')
#Counting the number of repo using every language
Lang_Dic_Count = LanguagesCounter(json_data)
# Getting the list of repo using every language
DicDataList = RepoListLanguages(json_data, Lang_Dic_Count)
# Displaye the repo's urls for every language
for key in DicDataList:
print(key, ' language used in')
for i in range(len(DicDataList[key])):
print(" ", DicDataList[key][i])
# Displaye the number of repos using every language in a table
table = []
for key in Lang_Dic_Count:
under_table=[]
under_table.append(key)
under_table.append(Lang_Dic_Count[key])
table.append(under_table)
print(tabulate(table, headers=('Language', 'number of Repo using it'), tablefmt="grid"))
</code></pre>
<p>and the first function is :</p>
<pre><code>def LanguagesCounter(Data):
''' Count how many times every programming language is used in the 100 most starred repos created in the last 30 days given in a parameter as json object, return a dict with languages as a keys and number of repo using this language as a value
'''
Languages_liste = []
for i in range(len(Data["items"])):
Languages_liste.append(Data["items"][i]["language"])
Lang_Dic_Count ={i:Languages_liste.count(i) for i in Languages_liste}
return Lang_Dic_Count
</code></pre>
<p>the third function is:</p>
<pre><code>def RepoListLanguages(Data, list):
'''
return the list of repositories from Data parameter for every programming language in the list parameter as a dictionary with the programming language as key and a list of repositories as value
'''
languagesRepo = {}
for key in list:
languagesRepo[key]= []
for repo in range(len(Data["items"])):
if (key == Data["items"][repo]["language"]):
languagesRepo[key].append(Data["items"][repo]["html_url"])
return languagesRepo
</code></pre>
<p>The code fetches the most starred repos from GitHub API that were created in the last 30 days, counts how many repos use every programming language, and lists the repo links for every language.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T17:53:36.617",
"Id": "497781",
"Score": "3",
"body": "I don't think that this: `'''Python` will run."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T20:09:57.130",
"Id": "497810",
"Score": "2",
"body": "since you are using 3rd party python modules, why not use one of the official libraries to interact with github as well? https://developer.github.com/v3/libraries/"
}
] |
[
{
"body": "<p>The two functions you broke out (<code>LanguagesCounter</code>, and <code>RepoListLanguages</code>) both could be simplified significantly using list comprehension. You seem to be thinking in terms of loops and appending to lists instead of generating them in one go which is more pythonic. Add in the <code>Counter</code> function from collections and RepoListLanguages becomes a relatively trivial one liner.</p>\n<p>Those are both at the top of the rewrite below so you can see them in action.</p>\n<p>Beyond that, the only real changes I made were using lower_camel_case per pep8 guidelines, changing a few variable names for clarity, and pulling the messy code at the bottom into functions. Functions and clear structure make reading the code much easier for anyone who needs to even if they don't change how it works.</p>\n<pre><code>import urllib.request, urllib.parse, urllib.error\nimport json\nimport sys\nfrom collections import Counter\nfrom datetime import datetime, timedelta, date\nfrom tabulate import tabulate\n\nfrom collections import Counter\n\n\ndef language_counter(data):\n return Counter(repo["language"] for repo in data["items"])\n\n\ndef repo_languages(data, list):\n return {\n key: [\n repo["html_url"] for repo in data["items"]\n if key == repo["language"]\n ]\n for key in list\n }\n\n\ndef new_url():\n last_month = datetime.date(datetime.now()) - timedelta(days=30)\n\n return 'https://api.github.com/search/repositories?q=created:%3E' + last_month.isoformat(\n ) + '&sort=stars&order=desc&page=1&per_page=100'\n\n\ndef get_data(url):\n data_connection_request = urllib.request.urlopen(url)\n\n unicoded_data = data_connection_request.read().decode()\n\n try:\n json_data = json.loads(unicoded_data)\n except:\n json_data = None\n\n return json_data\n\n\ndef validate_or_quit(json_data):\n if not json_data or json_data["total_count"] < 1:\n print(json_data)\n sys.exit('######## Failure To Retrieve ########')\n\n\ndef pretty_print_list(data):\n for key in data:\n print(key, ' language used in')\n for _, item in enumerate(data[key]):\n print(" " * 27, item)\n\n\ndef pretty_print_dict(data):\n data_list = [[key, value] for key, value in data.items()]\n print(\n tabulate(\n data_list,\n headers=('Language', 'number of Repo using it'),\n tablefmt="grid")\n )\n\n\nif __name__ == "__main__":\n json_data = get_data(new_url())\n validate_or_quit(json_data)\n\n lang_counts = language_counter(json_data)\n repo_langs = repo_languages(json_data, lang_counts)\n\n pretty_print_list(repo_langs)\n pretty_print_dict(lang_counts)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T21:11:56.807",
"Id": "497818",
"Score": "0",
"body": "Thank you for the advises, I want to know if is it a good practice to define all functions in the same file as you did in your recommendations ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T23:30:22.123",
"Id": "497825",
"Score": "1",
"body": "Depends on how large/complex your code is and if you expect to reuse portions. For a small project like this seems to be you can probably leave it in one file"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T19:42:08.983",
"Id": "252614",
"ParentId": "252606",
"Score": "4"
}
},
{
"body": "<p>The main improvements can be done in your two helper functions. Your first function could use the builtin <code>collections.Counter</code>:</p>\n<pre><code>from collections import Counter\n\ndef languages_counter(data):\n ''' Count how many times every programming language is used given in a parameter as json object, return a dict with languages as a keys and number of repo using this language as a value\n '''\n return Counter(repo["language"] for repo in data["items"])\n</code></pre>\n<p>And the second one could use <code>collections.defaultdict</code>:</p>\n<pre><code>from collections import defaultdict\n\ndef groupby_language(data):\n '''\n return the list of repositories from data parameter for every programming language as a dictionary with the programming language as key and a list of repositories as value\n '''\n repo_urls = defaultdict(list)\n for repo in data["items"]:\n repo_urls[repo["language"]].append(repo["html_url"])\n return repo_urls\n</code></pre>\n<p>Note that I followed Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, which recommends using <code>lower_case</code> for functions and variables.</p>\n<p>Alternatively, you could group the repos by language first, and use that afterwards:</p>\n<pre><code>def groupby(values, key):\n grouped = defaultdict(list)\n for x in values:\n grouped[x[key]].append(x)\n return grouped\n\ngrouped_repos = groupby(get_data(), "language")\ncounts = {language: len(repos)\n for language, repos in grouped_repos.items()}\nurls = {language: [repo["remote_url"] for repo in repos]\n for language, repos in grouped_repos.items()}\n</code></pre>\n<p>In your main code, you should put getting the data into its own function as well. It then becomes easier to change it.</p>\n<p>I would also use the <code>requests</code> module here, instead of <code>urllib</code>, it is a bit more user friendly and has advanced options like re-using a session for multiple requests, automatic URL-encoding and decoding, directly getting a JSON dictionary and checking the status code and raising an exception if it is not OK.</p>\n<pre><code>import requests\n\ndef get_data():\n one_month_ago = datetime.date(datetime.now()) - timedelta(days=30)\n url = "https://api.github.com/search/repositories"\n params = {"q": f">{one_month_ago.isoformat()}",\n "sort": "stars",\n "order": "desc",\n "page": 1,\n "per_page": 100}\n response = requests.get(url, params=params)\n response.raise_for_status()\n return response.json()["items"]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T21:12:46.213",
"Id": "497819",
"Score": "0",
"body": "Thank you, a very pedagogical answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-01T00:51:24.483",
"Id": "498431",
"Score": "0",
"body": "@Graipher I have similar question [here](https://codereview.stackexchange.com/questions/252737/post-json-using-http-and-verify-whether-all-actions-completed-successfully-or-no) where I needed some help on architecture/design of my code so wanted to see if you can help me out? Sorry for the ping like this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-01T06:07:23.923",
"Id": "498444",
"Score": "0",
"body": "@AndyP I will take a look when I have some time later."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-01T14:27:26.973",
"Id": "498471",
"Score": "0",
"body": "@Graipher Thanks really appreciate it."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T19:45:15.647",
"Id": "252615",
"ParentId": "252606",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "252615",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T17:46:34.657",
"Id": "252606",
"Score": "9",
"Tags": [
"python",
"web-scraping",
"api",
"web-services"
],
"Title": "Microservice that fetches data from REST repository endpoints on Github"
}
|
252606
|
<p>This is a depth-first search Kings Tour. I call it like this because the king must pass by all coordinates only touching them once (like a knights tour).
How could I improve?
Thank You</p>
<pre><code> # author @reivaJ
from collections import defaultdict
from itertools import product
import sys
import numpy as np
from random import choice
from operator import itemgetter
sys.setrecursionlimit(1500)
class BoardGraph(object):
'''Square room graph, connecting continous tile spaces'''
def __init__(self, height, width):
'''creates a graph for a square room of dimension height x width'''
self.width = width
self.height = height
self.nodes = list(product(range(height), range(width)))
self.edges = defaultdict(dict)
self.breed()
def breed(self):
for node in self.nodes:
for children in self.nodes:
if children != node and abs(node[0] - children[0]) <=1 and abs(node[1] - children[1]) <=1:
self.edges[node][children] = 0
def cornerWeight(self, child, corner):
value = abs(child[0]-corner[0]) + abs(child[1] - corner[1])
return value
def getCorner(self, node):
corners = [(0,0), (0, self.width - 1), (self.height-1, 0), (self.height-1, self.width-1)]
for corner in corners:
if abs(corner[0] - node[0]) < self.height/2 and abs(corner[1] - node[1]) < self.width/2:
return corner
def updateWeight(self, node, path):
corner = self.getCorner(node)
for children in self.childrenOf(node):
available_children = 0
for child in self.childrenOf(children):
if child not in path:
available_children += 1
available_children += self.cornerWeight(children, corner)
self.edges[node][children] = available_children
def childrenOf(self, node):
children = sorted(self.edges[node].items(), key = itemgetter(1))
return[child[0] for child in children]
def getEdges(self):
return self.edges.keys()
def printGraph(self):
for node, children in self.edges.items():
print ("Node:", node, " Children:", children)
class PathFinder(object):
def __init__(self, height, width, start):
self.height = height
self.width = width
self.graph = BoardGraph(height, width)
if start not in self.graph.getEdges():
raise ValueError ('Start possition must be within graph.')
self.start = start
self.path = self.goDeep(start)
def get_start(self):
return self.start
def get_graph(self):
return self.graph
def get_path(self):
return self.path
def goDeep(self, start, path=[]):
node = start
path.append(node)
if all(node in path for node in self.graph.getEdges()):
return path
self.graph.updateWeight(node, path)
for n in self.graph.childrenOf(node):
if n not in path:
new_path = self.goDeep(n, path)
if new_path != None:
return path
if len(path) != 1:
path.remove(node)
def representSolution(self):
model = np.zeros((self.height, self.width), dtype = int)
step = 1
for coordinate in self.path:
model[coordinate] = step
step += 1
print(model)
if __name__ == "__main__":
height = 10
width = 10
start = choice(list(product(range(height), range(width))))
p = PathFinder(height, width, start)
p.representSolution()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T21:07:53.873",
"Id": "497816",
"Score": "0",
"body": "you can also see it here"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T21:08:01.563",
"Id": "497817",
"Score": "0",
"body": "https://github.com/reivak720/kingsTour.git"
}
] |
[
{
"body": "<p>Your code looks good and seems to be working fine which is a great starting point!\nLet's try to see how things can be improved somehow.</p>\n<p><strong>Style</strong></p>\n<p>Python has a style guide called <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">https://www.python.org/dev/peps/pep-0008/</a> which is an interesting read. You may not follow it blindly but it is a good starting point to follow a few common conventions. For instance, method names usually use <code>snake_case</code>. (I'll come back to names later)</p>\n<p><strong>Rewriting <code>breed</code> with itertools</strong></p>\n<p>It looks like you know a bit about <code>itertools</code> as you've used <code>product</code>.\nThe double loop in in <code>breed</code> could be written with <code>product</code> as well but it is a good reason to try the other tools in the box.</p>\n<p>Indeed, as we do not want the pairs where <code>children</code> and <code>node</code> are the same, one could rely on <code>permutations</code> instead:</p>\n<pre><code> for (node, children) in itertools.permutations(self.nodes, 2):\n if abs(node[0] - children[0]) <= 1 and abs(node[1] - children[1]) <= 1:\n self.edges[node][children] = 0\n</code></pre>\n<p>but one could also use <code>combinations</code> and iterate over half as many pairs:</p>\n<pre><code> for (n1, n2) in itertools.combinations(self.nodes, 2):\n if abs(n1[0] - n2[0]) <= 1 and abs(n1[1] - n2[1]) <= 1:\n self.edges[n1][n2] = 0\n self.edges[n2][n1] = 0\n</code></pre>\n<p><strong>Renaming <code>cornerWeight</code></strong></p>\n<p><code>cornerWeight</code> looks a bit an obscure as a name. It actually corresponds to a pretty generic concept of distance. I've renamed it:</p>\n<pre><code>def dist_l1_norm(self, m, n):\n '''Distance using norm l1: https://en.wikipedia.org/wiki/Taxicab_geometry .'''\n return abs(m[0] - n[0]) + abs(m[1] - n[1])\n</code></pre>\n<p><strong>Simplify <code>getCorner</code></strong></p>\n<p><code>get_corner</code> iterates over 4 point candidates to find the closest one based on some coordinate checks. This can actually be used to generate the <code>x</code> and the <code>y</code> without going through multiple points:</p>\n<pre><code>def get_closest_corner(self, node):\n '''\n get the closest corner to a node\n '''\n x = 0 if node[0] < self.height/2 else self.height-1\n y = 0 if node[1] < self.width/2 else self.width-1\n return (x, y)\n</code></pre>\n<p>(I took this chance to rename it)</p>\n<p><strong>Making <code>update_weight</code> more concise</strong></p>\n<p>Warning: This may not be an advice applicable here as it can make things harder to understand but it is a probably a good thing to know anyway: instead of using many calls to <code>+=</code>, you can use the builtin <code>sum</code> over an iterable. Once applied, one can see that the variable <code>available_children</code> is not really required (except maybe for readibility purposes).</p>\n<p>You'd get:</p>\n<pre><code> corner = self.get_closest_corner(node)\n for children in self.childrenOf(node):\n self.edges[node][children] = \\\n self.dist_l1_norm(children, corner) + \\\n sum(child not in path for child in self.childrenOf(children))\n</code></pre>\n<p>(but again, here it may be better not to use this if you think it makes things harder to read)</p>\n<p><strong>Improving <code>goDeep</code></strong></p>\n<p>The <code>goDeep</code> method seems to be where the magic happens. Let's try to see how it can be improved.</p>\n<p>The name does not convey much meaning, I'd suggest <code>depth_first_search</code> but I would not be surprised if you could come up with something better.</p>\n<p>Having some recursive function that modifies the object passed as an argument can be a nice recipe to have impossible to debug behavior. My suggestion would be to keep the list <code>path</code> unchanged, for instand by copying it instead of updating it. Performing a bit of small changes to make sure things work, we'd have:</p>\n<pre><code>def depth_first_search(self, start, starting_path=[]):\n '''\n recursive depth-first search\n '''\n path = starting_path + [start]\n if all(node in path for node in self.graph.getNodes()):\n return path\n self.graph.update_weight(start, path)\n for n in self.graph.childrenOf(start):\n if n not in path:\n new_path = self.depth_first_search(n, path)\n if new_path != None:\n return new_path\n return None\n</code></pre>\n<hr />\n<p>I'll stop here as I am running out of things I can easily improve as I do not know much about the problem solved.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T06:36:53.137",
"Id": "497842",
"Score": "0",
"body": "Oh you can keep going if you have more."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T06:37:11.007",
"Id": "497843",
"Score": "0",
"body": "This is great. Thank You."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T06:42:31.123",
"Id": "497846",
"Score": "0",
"body": "There is really no original problem, we studied breath first and depth first but did no exercises, so I decided this was a good practice for mounting on my roomba, make it navigate threw every tile only touching it once. I needed a path finder, and this is my practice. It does tend to go to corners and abandoned places first, and tends to fiind the path in a 900 coordinate room."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T06:43:39.060",
"Id": "497847",
"Score": "0",
"body": "You can do that with sum? awesome. Real great advice. Thank you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T07:07:37.680",
"Id": "497851",
"Score": "0",
"body": "rubber ducky told be about that norm"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T07:08:11.773",
"Id": "497853",
"Score": "0",
"body": "now i know its name"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T23:01:07.837",
"Id": "252626",
"ParentId": "252612",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T19:16:04.090",
"Id": "252612",
"Score": "5",
"Tags": [
"python",
"graph"
],
"Title": "Kings Tour Python"
}
|
252612
|
<p>I'm trying to code a simple game called 'Atom'. The game is like this: At the start, you press 'Play' and one of the three boards (5x5, 6x6 or 7x7) are generated. There you have to guess where the hidden Atoms are through clicking on the squares on the left, right, top and bottom.</p>
<p>After pressing one of the squares a "line" is either sent to the other side or it comes back. If it goes through, there were no atoms on the way. If it comes back, it means, that an Atom is on the way.</p>
<p>Back to my code: it works without any problems but I have a little problem. Visual Studio shows me that the complexity of a few codes in are pretty high: from 10 to 20 or even up to 26.</p>
<p>How can I reduce the complexity of these codes? Or are there any other ways to write some parts of the code different?</p>
<pre class="lang-js prettyprint-override"><code>window.addEventListener("load", function() {
atom_game.start();
document.getElementById("play").addEventListener("click", function() {
atom_game.reset();
});
document.getElementById("solve").addEventListener("click", function() {
let win = atom_game.checkForWin();
const resultField = document.getElementById("result");
if(win){
resultField.innerText = "You win";
resultField.style.backgroundColor = "rgb(0, 255, 0)";
}
else{
resultField.innerText = "You lose";
resultField.style.backgroundColor = "rgb(255, 0, 0)";
}
});
});
const atom_game = {
board: [],
htmlBoard: [],
fieldSize: 8,
start(){
this.randomBoardSize(5, 7);
this.board = this.buildBoard();
this.htmlBoard = this.buildBoard();
this.buildHTMLBoard();
this.setBorder();
this.setAtoms();
this.setBoardStyle();
},
reset(){
const field = document.getElementsByClassName("field");
const resultField = document.getElementById("result");
const fieldLength = field.length
for(let i = 0; i < fieldLength; i++){
field[0].remove();
}
resultField.innerText = "";
resultField.style.backgroundColor = "rgb(255, 255, 255)";
this.start();
},
checkForWin(){
let winner = true;
for(let i = 0; i < this.fieldSize; i++){
for(let j = 0; j < this.fieldSize; j++){
if(this.htmlBoard[j][i].classList.contains("atom")){
if(this.htmlBoard[j][i].classList.contains("suspectAtom")){
this.setField(j, i, "correct");
}
else{
this.setField(j, i, "wrong");
winner = false
}
}
else if(this.htmlBoard[j][i].classList.contains("suspectAtom")){
if(!this.htmlBoard[j][i].classList.contains("atom")){
this.setField(j, i, "wrong");
winner = false
}
}
}
}
return winner;
},
randomBoardSize(min, max){
this.fieldSize = Math.floor(Math.random() * (max+1 - min) + min) + 2;
},
setBoardStyle(){
const field = document.getElementsByClassName("field");
const sizeProzent = 100 / this.fieldSize;
for (let i = 0; i < field.length; i++){
field[i].style.width = sizeProzent + "%";
field[i].style.height = sizeProzent + "%";
}
},
buildBoard() {
const board = [];
for(let y = 0; y < this.fieldSize; y++){
board.push([]);
for(let x = 0; x < this.fieldSize; x++){
board[y].push("null");
}
}
return board;
},
setBorder(){
for(let y = 0; y < this.fieldSize; y++){
for(let x = 0; x < this.fieldSize; x++){
if(x == y || (x === 0 && y === this.fieldSize-1) || (y === 0 && x === this.fieldSize-1)){
continue;
}
if(y == 0 || x == 0 || y == this.fieldSize-1 || x == this.fieldSize-1){
this.board[x][y] = "borderField";
this.htmlBoard[x][y].classList.add("borderField");
}
}
}
},
setAtoms(){
const min = 2;
const max = this.fieldSize - 2;
for(let i = 0; i < 5; i++){
let atomNearby = false;
let x = Math.floor(Math.random() * (max - min) + min);
let y = Math.floor(Math.random() * (max - min) + min);
for(let yTest = y-1; yTest <= y+1; yTest++){
for(let xTest = x-1; xTest <= x+1; xTest++){
if(this.htmlBoard[xTest][yTest].classList.contains("atom")){
atomNearby = true;
break
}
}
}
if(atomNearby === false){
this.setField(x, y, "atom");
}
}
},
buildHTMLBoard(){
const divBoard = document.querySelector("#board");
for(let y = 0; y < this.fieldSize; y++){
for(let x = 0; x < this.fieldSize; x++){
let field = document.createElement("div");
field.classList.add("field");
field.setAttribute("data-x", x);
field.setAttribute("data-y", y);
field.addEventListener("click", event => this.onClick(event));
divBoard.appendChild(field);
this.htmlBoard[x][y] = field;
}
}
},
onClick(event){
let t = window.setTimeout(this.clearBorder, 2000);
while(t--){
window.clearTimeout(t);
}
const clickedField = event.target;
const x = parseInt(clickedField.getAttribute("data-x"));
const y = parseInt(clickedField.getAttribute("data-y"));
if(clickedField.classList.contains("borderField")){
this.clearBorder();
if(x == 0) {
this.setField(x, y, "rightArrow");
this.calculateTrajectory(x, y, "right");
}
else if(y == 0){
this.setField(x, y, "downArrow");
this.calculateTrajectory(x, y, "down");
}
else if(x == this.fieldSize-1){
this.setField(x, y, "leftArrow");
this.calculateTrajectory(x, y, "left");
}
else if(y == this.fieldSize-1){
this.setField(x, y, "upArrow");
this.calculateTrajectory(x, y, "up");
}
}
else if(clickedField.classList.contains("suspectAtom")){
clickedField.classList.remove("suspectAtom");
}
else if(x > 1 && y > 1 && x < this.fieldSize-2 && y < this.fieldSize-2){
this.setField(x, y, "suspectAtom");
}
},
setField(x, y, val){
this.board[x][y] = val;
this.htmlBoard[x][y].classList.add(val);
},
clearBorder(){
let border = document.getElementsByClassName("field borderField");
const borderLength = border.length;
for(let i = 0; i < borderLength; i++){
border[i].className = "field borderField";
}
},
calculateTrajectory(x, y, direction){
const originalX = x;
const originalY = y;
const originalDirection = direction;
do {
let nearbyAtoms = [];
nearbyAtoms = this.checkForAtoms(x, y);
direction = this.calculateDirection(x, y, nearbyAtoms, direction)
//console.log(nearbyAtoms, direction, x, y);
switch(direction){
case "right":
x++;
break;
case "left":
x--;
break;
case "up":
y--;
break;
case "down":
y++;
break;
}
}while(!(x == 0 || y == 0 || x == this.fieldSize - 1 || y == this.fieldSize - 1))
this.setCorrectExitImage(originalX, originalY, x, y, originalDirection, direction);
},
checkForAtoms(x, y){
let nearbyAtoms = [];
let minY = y - 1;
let maxY = y + 1;
let minX = x - 1;
let maxX = x + 1;
minY = minY < 0 ? 0 : minY;
maxY = maxY > this.fieldSize-1 ? this.fieldSize-1 : maxY;
minX = minX < 0 ? 0 : minX;
maxX = maxX > this.fieldSize-1 ? this.fieldSize-1 : maxX;
//console.log(y, minY, maxY, " ", x, minX, maxX);
for(let i = minY; i <= maxY; i++){
for(let j = minX; j <= maxX; j++){
if(this.htmlBoard[j][i].classList.contains("atom")){
nearbyAtoms.push([j, i]);
}
}
}
return nearbyAtoms;
},
calculateDirection(x, y, nearbyAtoms, direction){
if(nearbyAtoms.length == 0){
return direction;
}
const nearbyAtomX = nearbyAtoms[0][0];
const nearbyAtomY = nearbyAtoms[0][1];
if(nearbyAtoms.length == 2){
return this.reverseDirection(direction)
}
else{
//console.log(nearbyAtomX, nearbyAtomY);
if(direction == "right" || direction == "left"){
if(nearbyAtomY == y){
return this.reverseDirection(direction);
}
else if(nearbyAtomY > y){
return "up";
}
else if(nearbyAtomY < y){
return "down";
}
}
else{
if(nearbyAtomX == x){
return this.reverseDirection(direction);
}
else if(nearbyAtomX > x){
return "left";
}
else if(nearbyAtomX < x){
return "right";
}
}
return direction
}
},
reverseDirection(direction){
switch(direction){
case "right":
return "left";
case "left":
return "right";
case "up":
return "down";
case "down":
return "up";
}
},
setCorrectExitImage(originalX, originalY, x, y, originalDirection, direction){
if(originalX == x && originalY == y){
if(originalDirection == "left" || originalDirection == "right"){
this.setField(x, y, "horizontalArrows");
}
else{
this.setField(x, y, "verticalArrows");
}
}
this.setField(x, y, direction + "Arrow");
}
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T05:38:39.867",
"Id": "497839",
"Score": "0",
"body": "Do you mean cyclomatic complexity? Not time and memory complexity, right? Although of course I suppose you won't mind improving either :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T09:27:14.150",
"Id": "497869",
"Score": "0",
"body": "I wrote this code in VisualStudio and theres a feature, which tells you how complex each methods are. And I have many methods over 10. As an example my method calculateDirection(...) has a complexity of 26 xD. And my question is: how can I reduce the complexity of this code? Or how can I write the code different but still does the same thing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T08:34:03.547",
"Id": "498021",
"Score": "1",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-28T23:19:46.373",
"Id": "534190",
"Score": "0",
"body": "I placed your code in my Visual Studio Code setup and received similar messages. I use [SonarLint](https://marketplace.visualstudio.com/items?itemName=SonarSource.sonarlint-vscode) (super annoying, but effective) and it complained at the level of nested if/for/while/try blocks in addition to complaining about complexity of the functions. It might be too complex for a single function to `check for win` when so many steps need to be taken to determine this. Refactoring could include extracting code out of the function and applying `DRY principles` to your code."
}
] |
[
{
"body": "<blockquote>\n<p>Do you mean cyclomatic complexity? Not time and memory complexity, right? Although of course I suppose you won't mind improving either :)</p>\n</blockquote>\n<p>it's cyclomatic, i.e. logic, complexity. I bet a donut that <code>checkForWin</code> has the worst score. The number and depth of logic and control branches seem to have the primary impact on score.</p>\n<hr />\n<p>It is best to focus on relative scores vice absolute numbers. Some understanding the scheme behind <a href=\"https://en.wikipedia.org/wiki/Cyclomatic_complexity\" rel=\"nofollow noreferrer\">cyclomatic complexity</a> can help but for goodness sake do not shred code in search of a arbitrary lower score. Instead, use it as a guide for possible refactoring. MSDN/Visual Studio documentation should have more to say about it too.</p>\n<hr />\n<p>Good Object Oriented design manages complexity. Good objects hide state and expose functionality.</p>\n<p>The atom game board should be an independent object encapsulating the square-iterating, with appropriate case-specific methods as needed. It may be quite complex but that complexity is isolated and confined, and gone from all other code.</p>\n<p>A high complexity score for a given method/function is fine if that complexity is exposed by useful functions, where client code does not have to access the board's structure directly which would perpetuate that complexity and add some more in dealing with it. And on, and on, ....</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T22:32:00.627",
"Id": "252680",
"ParentId": "252620",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T21:59:22.243",
"Id": "252620",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "Atom, a game where you guess where hidden Atoms are located"
}
|
252620
|
<p>I have tried to implement <a href="https://i.stack.imgur.com/JBOSD.jpg" rel="nofollow noreferrer">the following challenge</a>:</p>
<blockquote>
<h3>Personal Web Page Generator</h3>
<p>Write a program that asks the user for his or her name, then asks the user to enter a sentence that describes himself or herself. Here is an example of the program's screen:</p>
<p><code>Enter your name:</code> Julie Taylor<kbd>Enter</kbd><br />
<code>Describe yourself:</code> I am a computer science major, a member of the jazz club, and I hope to work as a mobile app developer after I graduate.<kbd>Enter</kbd></p>
<p>Once the user has entered the requested input, the program should create an HTML file, containing the input, for a simple webpage. Here is an example of the HTML content, using the sample input previously shown:</p>
<pre class="lang-html prettyprint-override"><code><html>
<head>
</head>
<body>
<center>
<h1>Julie Taylor</h1>
</center>
<hr />
I am a computer science major, a member of the Jazz club,
and I hope to work as a mobile app developer after I graduate.
<hr />
</body>
</html>
</code></pre>
</blockquote>
<p>I implemented this in C++. Here is my code:</p>
<pre class="lang-cpp prettyprint-override"><code>ofstream outfile_webpage;
string name, description;
outfile_webpage.open("Webpage.html");
cout << "Enter your name: ";
getline(cin,name);
cout << "Describe yourself: ";
getline(cin,description);
outfile_webpage << "<html>" << endl;
outfile_webpage << "<head>" << endl;
outfile_webpage << "</head>" << endl;
outfile_webpage << "<body>" << endl;
outfile_webpage << "\t<center>" << endl;
outfile_webpage << "\t\t<h1>" << name << "</h1>" << endl;
outfile_webpage << "\t</center>" << endl;
outfile_webpage << "\t<hr />" << endl;
outfile_webpage << "\t" << description << endl;
outfile_webpage << "\t<hr />" << endl;
outfile_webpage << "</body>" << endl;
outfile_webpage << "</html>" << endl;
outfile_webpage.close();
return 0;
</code></pre>
<p>This works just fine, but I see that there are a lot of repetitive lines. How can I reduce these repetitive lines?</p>
<p>Also, is there a way to make this code cleaner in another way, like by using a custom HTML template?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-22T04:57:41.277",
"Id": "497821",
"Score": "0",
"body": "You don't need to use `outfile_webpage` in every line. You can do `outfile_webpage<<\"foo\"<<endl` then in another line: `<<\"another foo\"`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T22:13:44.307",
"Id": "497822",
"Score": "0",
"body": "Using `endl` after every line unnecessarily causes the stream to flush. Use `'\\n'` and then manually `outfile_webpage.flush()` at the end."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-28T10:25:16.940",
"Id": "498217",
"Score": "0",
"body": "@Asesh Thanks for the suggestion"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-28T10:29:27.310",
"Id": "498219",
"Score": "0",
"body": "@Casey thanks for the suggestion. I got a clearer understanding of why we don't new endl"
}
] |
[
{
"body": "<p>There is a lot that can be improved here. Here are some ideas.</p>\n<h2>Don't abuse <code>using namespace std</code></h2>\n<p>Putting <code>using namespace std</code> at the top of every program is <a href=\"http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">a bad habit</a> that you'd do well to avoid.</p>\n<h2>Use all required <code>#include</code>s</h2>\n<p>This code fragment uses a number of features that require included library headers. In this case they appear to be:</p>\n<pre><code>#include <iostream>\n#include <fstream>\n#include <string>\n</code></pre>\n<p>It was not difficult to infer, but it helps reviewers if the code is complete.</p>\n<h2>Provide complete code to reviewers</h2>\n<p>This is not so much a change to the code as a change in how you present it to other people. Without the full context of the code and an example of how to use it, it takes more effort for other people to understand your code. This affects not only code reviews, but also maintenance of the code in the future, by you or by others. One good way to address that is by the use of comments. Another good technique is to include test code showing how your code is intended to be used.</p>\n<h2>Decompose your program into functions</h2>\n<p>All of the logic here is apparently in <code>main</code> in one long and repetitive chunk of code. It would be better to decompose this into separate functions.</p>\n<h2>Don't use <code>std::endl</code> if you don't really need it</h2>\n<p>The difference betweeen <code>std::endl</code> and <code>'\\n'</code> is that <code>'\\n'</code> just emits a newline character, while <code>std::endl</code> actually flushes the stream. This can be time-consuming in a program with a lot of I/O and is rarely actually needed. It's best to <em>only</em> use <code>std::endl</code> when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one. Avoiding the habit of using <code>std::endl</code> when <code>'\\n'</code> will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized.</p>\n<h2>Simplify and consolidate steps</h2>\n<p>Rather than having two separate lines to declare and then open the webpage file, do it in a single step:</p>\n<pre><code>std::ofstream webpage{"Webpage.html"};\n</code></pre>\n<h2>Use string concatenation</h2>\n<p>The program has many repeated lines where the <code>ostream operator<<</code> is used multiple times with a fixed string. Those multiple calls don't need to happen. You could simply rely on the fact that C++ merges separate constant strings automatically. For example, here is a recoded portion:</p>\n<pre><code>std::ofstream webpage{"Webpage.html"};\nwebpage << "<html>\\n" \n "<head>\\n"\n "</head>\\n"\n "<body>\\n"\n "\\t<center>\\n"\n "\\t\\t<h1>" << name << "</h1>\\n"\n "\\t</center>\\n"\n "\\t<hr />"\n "\\t" << description << "\\n"\n "\\t<hr />"\n "</body>"\n "</html>";\n</code></pre>\n<p>First, HTML parsers don't care about newlines, so it really doesn't matter much if they are present or not. Second, this is now a single explicit invocation of <code>ostream operator<<</code>.</p>\n<h2>Understand relevant standards</h2>\n<p>The HTML <code><center></code> tag is <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/center\" rel=\"nofollow noreferrer\">obsolete</a> and should not be used.</p>\n<h2>Adding features</h2>\n<p>Using an HTML template instead is a good idea and would keep the code generic while enabling customization of use. One way to do that would be to read in a file and then substitute special tags such as <code>@name@</code> and <code>@description@</code> but simply copying the rest verbatim.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-28T10:32:43.943",
"Id": "498220",
"Score": "0",
"body": "Thank you so much for the comprehensive suggestion. I'll make my code a lot better."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T22:40:09.857",
"Id": "252623",
"ParentId": "252621",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-22T04:50:33.680",
"Id": "252621",
"Score": "1",
"Tags": [
"html",
"c++",
"file"
],
"Title": "Cleaning up the code of a C++-based Personal Web Page Generator"
}
|
252621
|
<p><a href="https://leetcode.com/problems/stone-game/" rel="nofollow noreferrer">https://leetcode.com/problems/stone-game/</a></p>
<blockquote>
<p>Alex and Lee play a game with piles of stones. There are an even
number of piles arranged in a row, and each pile has a positive
integer number of stones piles[i].</p>
<p>The objective of the game is to end with the most stones. The total
number of stones is odd, so there are no ties.</p>
<p>Alex and Lee take turns, with Alex starting first. Each turn, a
player takes the entire pile of stones from either the beginning or
the end of the row. This continues until there are no more piles
left, at which point the person with the most stones wins.</p>
<p>Assuming Alex and Lee play optimally, return True if and only if Alex
wins the game.</p>
<p>Example 1:</p>
<p>Input: piles = [5,3,4,5] Output: true Explanation: Alex starts first,
and can only take the first 5 or the last 5. Say he takes the first 5,
so that the row becomes [3, 4, 5]. If Lee takes 3, then the board is
[4, 5], and Alex takes 5 to win with 10 points. If Lee takes the last
5, then the board is [3, 4], and Alex takes 4 to win with 9 points.
This demonstrated that taking the first 5 was a winning move for Alex,
so we return true.</p>
<p>Constraints:</p>
<p>2 <= piles.length <= 500 piles.length is even. 1 <= piles[i] <= 500
sum(piles) is odd.</p>
</blockquote>
<p>I am working on my recursion an dynamic programming skills. please review for performance</p>
<p>solution 1: recursion</p>
<pre class="lang-cs prettyprint-override"><code>public bool StoneGame(int[] piles)
{
return Helper(piles, 0, piles.Length - 1, 0, 0, true);
}
private bool Helper(int[] piles, int start, int end, int sumAlex, int sumLee, bool isAlex)
{
if (start >= end)
{
return sumAlex > sumLee;
}
if (isAlex)
{
return Helper(piles, start + 1, end, sumAlex + piles[start], sumLee, false)
|| Helper(piles, start, end - 1, sumAlex + piles[end], sumLee, false);
}
else
{
return Helper(piles, start + 1, end, sumAlex, sumLee + piles[start], true)
|| Helper(piles, start, end - 1, sumAlex, sumLee + piles[end], true);
}
}
</code></pre>
<p>Solution 2: DP</p>
<pre class="lang-cs prettyprint-override"><code>public class Solution
{
private int[,] dp;
public bool StoneGame3(int[] piles)
{
dp = new int[piles.Length, piles.Length];
for (int i = 0; i < piles.Length; i++)
{
for (int j = 0; j < piles.Length; j++)
{
dp[i, j] = -1;
}
}
//begin or end of the row
int s = 0;
int e = piles.Length - 1;
Helper(s, e, true, piles);
return dp[0, piles.Length - 1] > 0;
}
private int Helper(int s, int e, bool isAlex, int[] piles)
{
if (s > e)
{
return 0;
}
if (s == e)
{
return piles[s];
}
if (dp[s, e] != -1)
{
return dp[s, e];
}
if (isAlex)
{
dp[s, e] = Math.Max(piles[s] + Helper(s + 1, e, !isAlex, piles), piles[e] + Helper(s, e - 1, !isAlex, piles));
}
else
{
//we remove what lee is picking and we will take the min so we will have the max stones for alex
dp[s, e] = Math.Min(-piles[s] + Helper(s + 1, e, !isAlex, piles), -piles[e] + Helper(s, e - 1, !isAlex, piles));
}
return dp[s, e];
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T22:26:25.217",
"Id": "252622",
"Score": "3",
"Tags": [
"c#",
"programming-challenge",
"recursion",
"dynamic-programming"
],
"Title": "LeetCode: Stone Game C#"
}
|
252622
|
<p>This is a small frontend frame for a React app that is built then served statically.</p>
<p>Because the app uses <code>React-Router</code> for browser-based routing but the server doesn't know anything about the app I added some code to the backend that reads the list of routes the app uses from a json file and creates dummy handlers for each that place a <code>redirect=/path</code> cookie and redirect to the main page. That code is left out for brevity and to focus on the frontend.</p>
<p>Meanwhile, the Javascript React frontend in this question sets ups the app's <code>React-Router</code> routes based on the same external json file. The main page checks whether there is a redirect cookie set by the server and if so sends the user to that page.</p>
<p>The overall effect between the frontend and backend is that a user can go directly to <code>app.com/widget/4</code> and without them knowing the server bounces them to the main page to start the browser-routing session and then back to the correct url</p>
<p>routes.json:</p>
<pre><code>{
"routes": [
{"path":"/widget/:widgetId", "component": "WidgetContainer", "redirect": true},
{"path":"/", "component": "MainPageContainer", "exact": true}
]
}
</code></pre>
<p>index.js:</p>
<pre><code>import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route } from "react-router-dom";
import ParseRoutes from "./Utils/ParseRoutes"
import { routes } from "./routes.json"
function AppContainer() {
const routeProps = ParseRoutes(routes)
return (
<Router>
{routeProps.map((props, i) => (<Route key={i} {...props} /> ))}
</Router>
)
}
ReactDOM.render(<AppContainer />, document.getElementById("root"))
</code></pre>
<p>ParseRoutes.js:</p>
<pre><code>import MainPageContainer from "../Components/MainPage"
import WidgetContainer from "../Components/Widget"
const stringToComp = {
MainPageContainer: MainPageContainer,
WidgetContainer: WidgetContainer
}
const ParseRoutes = (routes) => (
routes.map((props) => ({...props, component: stringToComp[props.component]}))
)
export default ParseRoutes
</code></pre>
<p>RedirectIfRequested.js:</p>
<pre><code>import React from "react"
import { Redirect } from "react-router-dom"
const getCookieValue = (a) => {
var b = document.cookie.match('(^|;)\\s*' + a + '\\s*=\\s*([^;]+)')
return b ? b.pop() : ''
}
const RedirectIfRequested = () => {
const redirectTo = getCookieValue("redirect")
if ( redirectTo ) {
document.cookie = "redirect=''; max-age=-1"
return <Redirect to={redirectTo} />
}
return null
}
export default RedirectIfRequested
</code></pre>
<p>MainPage.js:</p>
<pre><code>import React from "react"
import RedirectIfRequested from "../Utils/RedirectIfRequested.js"
export default function MainPageContainer(props) {
const redirect = RedirectIfRequested()
return redirect ? redirect : <MainPage />
}
function MainPage(props) {
return <div>Main Page</div>
}
</code></pre>
<p>Widget.js:</p>
<pre><code>import React from "react"
import { useParams } from "react-router-dom"
export default function WidgetContainer(props) {
const id = useParams().widgetId
return <div> Widget {id} accessed via react-router </div>
}
</code></pre>
|
[] |
[
{
"body": "<p>In general, your code does a good job at naming variables/functions, and at splitting logic up in ways that make sense.</p>\n<p>However, there are a few places where you are inconsistent with your code style - maybe using a linter would help out:</p>\n<ul>\n<li>In some files you indent with 2 spaces. Other files are indented with 4.</li>\n<li>There's a number of import statements that have an extra space between the words. e.g. <code>import ParseRoutes from "./Utils/ParseRoutes"</code></li>\n</ul>\n<p>A note on casing: Generally, we use TitleCase for classes and components only. camelCase is used for almost everything else. A file (or folder with an index.js) with a default export of a class or component may use TitleCase too. However, folders like "Util" or "Components" should probably all be in lowercase. Your "getCookieValue()" function is properly cased, but in the same file, your "RedirectIfRequested()" function is not - RedirectIfRequested is not a class or component. (there's a couple other examples like that).</p>\n<p>The local variables in getCookieValue() could probably be named better then "a" and "b". Maybe rename "a" to "cookieKey" and "b" to "match".</p>\n<p>.pop() is not a common way to get a group from a regex. If you want to get the second group, just say that with code: <code>match[2]</code>. Note that since you don't actually care about the value of the first group in your regex, you can use a non-capturing group instead (the syntax is <code>(?:...)</code>). For example, if your regex is <code>a(b|B)c(d|D)e</code>, then b/B is group 1 and d/D is group 2, but if its <code>a(?:b|B)c(d|D)e</code>, then you can't get b/B, and d/D is group 1. You don't have to use non-capture groups, but I just want to make sure you know that that's an option.</p>\n<hr />\n<p>Finally, and most importantly, all of this routing logic you made is actually not needed. The proper way to configure a server to handle single-page-application (SPA) routing is as follows:</p>\n<p>Lets assume your SPA exits at <code>example.com/my-app</code>, and your app has routes such as <code>example.com/my-app/</code> (the home page) and <code>example.com/my-app/widget/2</code>. You need to configure your server to return the same react bundle no matter which route they hit, as long as its within <code>example.com/my-app</code>. So, going to <code>example.com/my-app/does-not-exist</code> will give you the same javascript bundle as going to <code>example.com/my-app/widget/2</code>. (Note that this is not the same as a redirection). Finally, javascript can check which URL you used (was it /my-app/does-not-exist/ or /my-app/widget/2) and route based on that information - something that react-router will do for you. If the route doesn't exist, just show a 404 page from your React app.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T21:24:19.870",
"Id": "500575",
"Score": "0",
"body": "The regex variables/pop was the one piece I copied pasted from stack overflow and has already been fixed since the question was posted. Do you have any resource or know what even the right terms to google would be to workout which react chunks should be served when? Writing JavaScript is fine but whenever babel/webpack/building it comes up 'yarn run build' is about all I know"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T01:17:48.047",
"Id": "500588",
"Score": "0",
"body": "https://reactjs.org/docs/code-splitting.html Is this the direction you're talking about for splitting bundles?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T16:39:27.377",
"Id": "500658",
"Score": "1",
"body": "@Coupcoup code-splitting is a good practice, but it's not needed to fix the issue your code was trying to fix. Try the following link: https://create-react-app.dev/docs/deployment/#serving-apps-with-client-side-routing - I don't know if you use create-react-app or not, but the link should contain relevant information either way. once you have that fixed, and if you're also wanting to do code splitting to make page-loads quicker, than yes, the link you have is a great resource."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-24T18:33:37.363",
"Id": "500667",
"Score": "0",
"body": "Thanks for the pointer! That was actually an incredibly easy change (like replacing one function call) to once it clicked to serve `index.html` instead of redirect to it"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-23T02:39:18.703",
"Id": "253809",
"ParentId": "252625",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "253809",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T22:55:42.783",
"Id": "252625",
"Score": "2",
"Tags": [
"javascript",
"react.js"
],
"Title": "React App with external route table and cookie-based routing"
}
|
252625
|
<p>I was wondering if it is possible to speed up this script? The source file has 90,000 rows, and it has to create a separate forecast for 1200 unique dealers using fbprophet. I'm new to python so I'm not sure if there is something obvious I'm missing, or if it's just going to have to take a really long time. If any sees a simple solution that would speed it up, I would appreciate any insight. Thank you</p>
<p>Additional details about code:
The code takes a CSV file that has 3 columns(Month, Dealer, and Sales) and creates a filter essentially for each unique dealer name, and then uses Fbprophet to forecast the future results of each dealer. Then it combines all the information in a CSV file. It's 90,000+ rows of data typically, and normally 1200 unique dealers that need to be forecasted. The historical data is 7 years of history.</p>
<pre><code>from pandas import read_csv
from pandas import to_datetime
from pandas import DataFrame
from fbprophet import Prophet
from matplotlib import pyplot
import pandas as pd
# load data
data = read_csv('X.csv', header=0)
# prepare expected column names
data.columns = ['ds','Dealer', 'y']
data['ds']= to_datetime(data['ds'])
results = pd.DataFrame()
for dealer in data['Dealer'].unique():
df_filtered = data[data['Dealer']==dealer]
prophet_df = df_filtered[['ds', 'y']]
# define the model
model = Prophet()
# fit the model
model.fit(prophet_df)
# define the period for which we want a prediction
future = list()
for h in range(11, 13):
date = '2020-%02d' % h
future.append([date])
for i in range(1, 13):
date = '2021-%02d' % i
future.append([date])
for j in range(1, 13):
date = '2022-%02d' % j
future.append([date])
for k in range(1, 13):
date = '2023-%02d' % k
future.append([date])
future = DataFrame(future)
future.columns = ['ds']
future['ds']= to_datetime(future['ds'])
# use the model to make a forecast
forecast = model.predict(future)
forecast['Dealer'] = dealer
# forecast.head(5)
results = results.append(forecast)
results.to_csv('X1.csv')
</code></pre>
<p>Link to Sample Data: <a href="https://docs.google.com/spreadsheets/d/1lrkRQ9juDm7WZahsPV8oq2Rh7UFlFxCDpP4AgiTxTzU/edit?usp=sharing" rel="nofollow noreferrer">https://docs.google.com/spreadsheets/d/1lrkRQ9juDm7WZahsPV8oq2Rh7UFlFxCDpP4AgiTxTzU/edit?usp=sharing</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T23:21:00.280",
"Id": "497823",
"Score": "1",
"body": "Have you made any attempt to vectorize your code? Because whatever solution gets posted will be 1-2 orders of magnitude faster via vectorization"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T23:25:15.193",
"Id": "497824",
"Score": "1",
"body": "https://towardsdatascience.com/one-simple-trick-for-speeding-up-your-python-code-with-numpy-1afc846db418"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T00:00:15.257",
"Id": "497827",
"Score": "0",
"body": "What kind of dealer/forecast are we talking about? Financials?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T00:03:44.960",
"Id": "497828",
"Score": "0",
"body": "Thanks, @Coupcoup. I'll do some research on vectorization, I haven't heard that term before. Thanks also for the link."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T00:06:29.930",
"Id": "497829",
"Score": "0",
"body": "@reinderien It's projecting sales in a dealer's territory. (but there can be decimals in the historical data, because territories are shared) But essentially it just shows the total sales that each dealer get credit for over the last 7 years."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T00:08:02.013",
"Id": "497830",
"Score": "0",
"body": "Art dealer? Exotic bird dealer? Cursed artefact dealer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T00:10:41.177",
"Id": "497831",
"Score": "1",
"body": "I wish it was that exciting. It's for tractor and construction equipment dealers"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T00:11:29.187",
"Id": "497832",
"Score": "1",
"body": "If you could post a small sample of the csv or a link to a portion it I might give it a stab. As-is though the problem's not impossible but pretty hard to reason about"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T00:31:18.030",
"Id": "497833",
"Score": "0",
"body": "Thanks Coup this is a sample of the data\nhttps://docs.google.com/spreadsheets/d/1lrkRQ9juDm7WZahsPV8oq2Rh7UFlFxCDpP4AgiTxTzU/edit?usp=sharing"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T02:19:45.090",
"Id": "497835",
"Score": "1",
"body": "are you sure the code works correctly? `df_filtered` is created but never used"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T04:10:27.960",
"Id": "497836",
"Score": "1",
"body": "My apologies, thanks for letting me know. It should be \n prophet_df = df_filtered[['ds', 'y']]\non the line below. I corrected it."
}
] |
[
{
"body": "<p>Took some work but got a 25-30% speedup (down from roughly 5.2 to 3.8 seconds) on the sample data you provided along with cleaner code. I'm hoping that when you scale it across the full data the gains will be larger but tbd</p>\n<p>So what are the changes?</p>\n<ol>\n<li><p>Move whatever possible outside loops. Your <code>future</code> value never changes but you recreate it (relatively inefficiently) and do other <code>DataFrame</code> manipulation every loop which would be 1,200 times total. Not the biggest drain but it's there.</p>\n</li>\n<li><p>List comprehension can be a bit faster than going through regular loops and multiple assignments. Everything I could pull into a single function like <code>pd.read_csv</code> or <code>pd.date_range</code> or list comprehension I did</p>\n</li>\n<li><p>Slightly faster <code>Dataframe</code> filtering by setting <code>df.index = "dealer"</code> and using <code>df.loc[np.in1d(df.index, dealer)][['ds', 'y']]</code>. If you really want to squeeze out performance that's the fastest way I can find but probably not worth the hit to readability in normal code. Still, I left it in.</p>\n</li>\n</ol>\n<p>Are those three improvements? Sure. They'll add up over enough data but they're still shaving fractions of a second off. The real resource killer is <code>Prophet</code> doing the modeling/forecasting itself which leads to</p>\n<ol start=\"4\">\n<li>Parallelizating <code>Prophet</code> with <code>multiprocessing.Pool.imap</code>. Instead of a loop creating the future range and then the filtering and then modeling and forecasting the data for each unique dealer now it's going to utilize multiple processors to work on each forcast more-or-less simultaneously. Probably not all 1,200 at once but more than 1. That's what accounts for most of the speedup and why hopefully you'll get even larger gains like maybe 2-4x (that's very loose guess, no promises) on the full data.</li>\n</ol>\n<p>Rewrite:</p>\n<pre><code>from fbprophet import Prophet\nimport pandas as pd\nimport numpy as np\nfrom multiprocessing import Pool, cpu_count\n\n\ndef forecast_data(args):\n (df, dealer, dates) = args\n\n model = Prophet()\n model.fit(df.loc[np.in1d(df.index, dealer)][['ds', 'y']])\n\n return model.predict(dates)\n\n\nif __name__ == "__main__":\n df = pd.read_csv('X.csv', header=0, names=['ds', 'dealer', 'y'],\n parse_dates=['y'], index_col="dealer")\n\n date_range = pd.date_range('2020-11', '2024-12', freq='MS')\n date_range = pd.DataFrame(date_range, columns=['ds'])\n\n p = Pool(cpu_count())\n\n results = pd.concat(\n [result for result in p.imap(\n forecast_data,\n [(df, dealer, date_range) for dealer in df.index.unique()]\n )])\n\n results.to_csv('X2.csv')\n</code></pre>\n<p>P.S. If you wonder why <code>forecast_data</code> takes a tuple and unpacks it it's because I tried to write a memoized factory function that took <code>df</code> and <code>dates</code> are arguments and returned <code>forecast(dealer)</code> but that caused <code>multiprocessing</code> to have a pickle about using a local pickle.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T07:31:03.860",
"Id": "252637",
"ParentId": "252628",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "252637",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T23:19:13.503",
"Id": "252628",
"Score": "4",
"Tags": [
"performance",
"python-3.x"
],
"Title": "Forecasts for construction equipment dealers"
}
|
252628
|
<p>I'm making a bot for PlayStation 5.
And restock is coming soon so I want to make my bot faster.
The approximate duration is 4.90 seconds.
Is there any way to make this faster?
I found that I should write this in C or C ++ for better results.</p>
<pre><code>#startup
chrome_options = Options()
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(options=chrome_options)
driver = webdriver.Chrome('chromedriver')
driver.maximize_window()
driver.get("https://www.games.rs/ps4-konzole/16794-konzola-playstation-4-1tb-pro-black-dualshock-fifa-21")
</code></pre>
<p>Cena and Kupi are unnecessary.
Program clicks to accept cookies.
Then scrolling cuz it needs to.
And then refreshing page until text in button is "Add to Cart".</p>
<pre><code>#order
start_time = time.time()
kupi = driver.find_element_by_xpath('//*[@class="block product-attributes-wrapper clearfix"]/ul[1]/li[1]/div[1]/div[1]')
cena = driver.find_element_by_xpath('//*[@class="block product-attributes-wrapper clearfix"]/ul[1]/li[1]/div[1]/div[1]')
driver.find_element_by_xpath('//*[@id="modal-cookie-info"]/div/div/div/div/button').click()
driver.execute_script("window.scrollTo(712, 200);", kupi)
while True:
try:
driver.find_element_by_xpath('//button[text()="Dodaj u korpu"]')
except NoSuchElementException:
driver.refresh()
else:
driver.find_element_by_xpath('//button[text()="Dodaj u korpu"]').click()
break
driver.find_element_by_xpath('//*[@id="miniCartContent"]/div[1]/a').click()
driver.execute_script("window.scrollTo(0 , 900);", )
</code></pre>
<p>Lastly login for informations and completing order.</p>
<pre><code>#login
driver.find_element_by_xpath('//*[@id="order_address_content"]/div/div/div[2]/div[2]/div[1]/div[1]/div[2]/div/div/a').click()
time.sleep(0.2)
email = driver.find_element_by_css_selector('#login_email')
email.send_keys("mail")
password = driver.find_element_by_id('login_password')
password.send_keys("pass")
driver.find_element_by_xpath('//*[@id="login_modal"]/div/div/form/div[3]/button').click()
time.sleep(0.2)
driver.execute_script("window.scrollTo(0 , 1600);", )
driver.find_element_by_xpath('//*[@class="delivery-options list-unstyled"]/li[3]/div[1]/div[1]').click()
time.sleep(0.5)
driver.execute_script("window.scrollTo(0 , 2500);", )
driver.find_element_by_xpath('//*[@id="submit_order_one_page"]').click()
</code></pre>
<p>This prints duration of the program.</p>
<p><code>print("--- %s seconds ---" % (time.time() - start_time)) </code></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T21:02:30.467",
"Id": "497954",
"Score": "1",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<p>Just a short review from me:</p>\n<p>The artificial delays (<code>time.sleep(0.5)</code>) are superfluous and not safe. They slow you down sometimes, they fail sometimes, because the pages take longer than usual to load.\nInstead you can use Selenium selector functions, to wait until an element appears (or disappears). For example, you could have something like this:</p>\n<pre><code>element = WebDriverWait(driver, 10).until(\n EC.element_to_be_clickable((By.XPATH, "//button[text()="Dodaj u korpu"]")))\n)\n</code></pre>\n<p>Here, we wait for an element to be in clickable state, but set a timeout of 10 seconds for the condition to be realized. You have a solid range of similar options available. Check out the doc: <a href=\"https://selenium-python.readthedocs.io/waits.html\" rel=\"nofollow noreferrer\">Waits</a></p>\n<p>Likewise, you can get rid of the exception handling block (NoSuchElementException). My advice is to replace the sleeps with adequate wait functions, depending on the conditions you want to test. This should make your code more reliable and probably a bit faster, because it's not going to wait for longer than necessary.</p>\n<p>Since your concern is speed: I would say 4.90 seconds is not bad but I don't know your constraints. Have you benchmarked your code to find out what is taking time ? Use the timeit module or - recommended link: <a href=\"https://realpython.com/python-timer/\" rel=\"nofollow noreferrer\">Python Timer Functions: Three Ways to Monitor Your Code</a> to set up your own timing class.</p>\n<p>From experience, Selenium takes time to load, so perhaps you might as well leave it running in the background and use a loop to refresh the page at regular intervals, while being gentle and taking care not to overload the site.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T20:41:18.180",
"Id": "252675",
"ParentId": "252631",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "252675",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T00:59:55.237",
"Id": "252631",
"Score": "2",
"Tags": [
"python",
"selenium"
],
"Title": "How to make selenium in python faster"
}
|
252631
|
<p>I have a dataset <code>('sample_data.csv')</code> of the form below:</p>
<pre><code>timestamp,cell_id,crnti,enodeb_id,uplane_downlink.cqi_wideband_mean,uplane_downlink.distance_initial_km,uplane_downlink.non_gbr_dl_bytes,time_sec,timestamp_y,uplane_uplink.non_gbr_ul_bytes
1606208553171,1,1487,1002107,7,27,134,1606208553,1606208553256,146
1606208557195,1,1487,1002107,6,27,388,1606208557,1606208557369,577
1606208557236,1,2631,1002107,10,27,251,1606208557,1606208557351,194
1606208561301,1,1487,1002107,6,27,140,1606208561,1606208561463,245
1606208561339,1,2631,1002107,11,27,159,1606208561,1606208561381,108
1606208565415,1,1487,1002107,7,27,99,1606208565,1606208565472,54
1606208565435,1,2631,1002107,10,27,64,1606208565,1606208565495,54
1606208569518,1,1487,1002107,6,27,101,1606208569,1606208569601,289
1606208569533,1,2528,1002107,7,16,57,1606208569,1606208569621,0
1606208571263,1,2631,1002107,10,27,0,1606208571,1606208571263,8500
1606208573557,1,2528,1002107,8,16,0,1606208573,1606208573557,0
1606208575838,1,1487,1002107,7,27,0,1606208575,1606208575838,50
</code></pre>
<p>Here the column <code>crnti</code> represents an user and the column <code>time_sec</code> gives a timestamp for this user's session. Sessions that are separated by less than 9 secs are considered continuation (small session of a longer session). My end goal is to summarize session properties for each user. In the summary I want to show</p>
<ol>
<li><p>Session duration → calculated as <code>(last = max(time_sec)) - (first=min (time_sec))</code> for a dataframe that is a filtered DF (including only records that are less than 9 sec apart) for a crnti. In the code below I do it as:</p>
<pre><code>session_summary['session_duration'] = int(session_summary['last'])-int(session_summary['first'])
</code></pre>
</li>
<li><p>Sum of <code>uplane_uplink.non_gbr_ul_bytes</code> across all small sessions for a user → calculated as sum of all values in the filtered df (session_summary):</p>
<pre><code>session_summary = sub_session.astype(int).groupby(['crnti', 'cell_id', 'enodeb_id']).agg(distance_initial_km = ('uplane_downlink.distance_initial_km', 'mean'),
first = ('time_sec', 'min'),
last = ('time_sec', 'max'),
cqi = ('uplane_downlink.cqi_wideband_mean', 'mean'),
non_gbr_dl_bytes = ('uplane_downlink.non_gbr_dl_bytes', 'sum'),
non_gbr_ul_bytes = ('uplane_uplink.non_gbr_ul_bytes', 'sum'))
</code></pre>
</li>
<li><p>Sum of <code>uplane_downlink.non_gbr_dl_bytes</code> across all small sessions for a user → calculation described above</p>
</li>
<li><p>Mean of <code>cqi_wideband_mean</code> → calculation described above</p>
</li>
<li><p>Mean of <code>uplane_downlink.distance_initial_km</code> → calculation described above</p>
</li>
</ol>
<p>As an example for rnti = 1487. Here is the summary - <a href="https://i.stack.imgur.com/xAmUu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xAmUu.png" alt="enter image description here" /></a></p>
<p>I have the following code that gets me the expected output. However my dataset is pretty big (6M rows) and this approach is not scalable and takes way too long. I came across the concept of <a href="https://engineering.upside.com/a-beginners-guide-to-optimizing-pandas-code-for-speed-c09ef2c6a4d6" rel="nofollow noreferrer">vectorization</a> using numpy or pandas and want to implement it, but not sure where to start. Any pointers are appreciated.</p>
<p>Working but slow code:</p>
<pre><code>import pandas as pd
import numpy as np
comb_dl_ul_full_191 = pd.read_csv('sample_data.csv')
column_names = ['crnti', 'enodeb_id', 'cell_id', 'uplane_downlink.cqi_wideband_mean', 'uplane_downlink.distance_initial_km', 'uplane_downlink.non_gbr_dl_bytes',
'time_sec',
'uplane_uplink.non_gbr_ul_bytes']
all_sessions_summary = pd.DataFrame()
enbs = [1002107] ## this is an array. For simplicity I am only showing one element. Creating it as shown below
#enbs = np.unique(comb_dl_ul_full['enodeb_id'].to_list())
comb_dl_ul_full_191 = comb_dl_ul_full_191.astype(int) # converting all to INT
for enb in enbs:
cells = [1] # this is an array. For simplicity I am only showing one element. Creating it as shown below
#cells = np.unique(comb_dl_ul_full_191[comb_dl_ul_full_191['enodeb_id']==enb]['cell_id'].to_list())
for cell in cells:
dd = comb_dl_ul_full_191[(comb_dl_ul_full_191['enodeb_id']==enb) & (comb_dl_ul_full_191['cell_id']==cell)]
rntis = np.unique(dd['crnti'].to_list())
dd.sort_values(by=['time_sec'], inplace=True)
for rnti in rntis:
d = dd[(dd['enodeb_id']==enb) & (dd['crnti']==rnti) & (dd['cell_id']==cell)]
f = d['time_sec'].to_list()
timedeltas = [int(f[i-1])-int(f[i]) for i in range(1, len(f))]
session_summary = pd.DataFrame()
session_summary_overall = pd.DataFrame()
count=0
i=0
while i < len(timedeltas):
if timedeltas[i] > -9:
sub_session = pd.DataFrame(columns=column_names)
d = d[column_names]
sub_session = sub_session.append(d.iloc[[i]])
for j in range(i, len(timedeltas)):
if timedeltas[j] > -9:
sub_session = sub_session.append(d.iloc[[j+1]])
else:
break
count = int(len(sub_session['time_sec']))
sub_session.astype(int)
session_summary = sub_session.astype(int).groupby(['crnti', 'cell_id', 'enodeb_id']).agg(distance_initial_km = ('uplane_downlink.distance_initial_km', 'mean'),
first = ('time_sec', 'min'),
last = ('time_sec', 'max'),
cqi = ('uplane_downlink.cqi_wideband_mean', 'mean'),
non_gbr_dl_bytes = ('uplane_downlink.non_gbr_dl_bytes', 'sum'),
non_gbr_ul_bytes = ('uplane_uplink.non_gbr_ul_bytes', 'sum'))
session_summary['session_duration'] = int(session_summary['last'])-int(session_summary['first'])
session_summary = session_summary.reset_index()
session_summary_overall = session_summary_overall.append(session_summary, ignore_index=True)
i=i+count
else:
sub_session = pd.DataFrame(columns=column_names)
sub_session = sub_session.append(d.iloc[[i]])
session_summary = sub_session.astype(int).groupby(['crnti', 'cell_id', 'enodeb_id']).agg(distance_initial_km = ('uplane_downlink.distance_initial_km', 'mean'),
first = ('time_sec', min),
last = ('time_sec', max),
cqi = ('uplane_downlink.cqi_wideband_mean', 'mean'),
non_gbr_dl_bytes = ('uplane_downlink.non_gbr_dl_bytes', 'sum'),
non_gbr_ul_bytes = ('uplane_uplink.non_gbr_ul_bytes', 'sum'))
session_summary['session_duration'] = 4.096
session_summary = session_summary.reset_index()
session_summary_overall = session_summary_overall.append(session_summary, ignore_index=True)
count = count+1
i=i+1
all_sessions_summary = all_sessions_summary.append(session_summary_overall, ignore_index=True)
</code></pre>
<p>Output using data_set:</p>
<pre><code>,crnti,cell_id,enodeb_id,distance_initial_km,first,last,cqi,non_gbr_dl_bytes,non_gbr_ul_bytes,session_duration
0,1487,1,1002107,27,1606208553,1606208575,6.5,862,1361,22
1,2528,1,1002107,16,1606208569,1606208573,7.5,57,0,4
2,2631,1,1002107,27,1606208557,1606208571,10.25,474,8856,14
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T04:13:11.393",
"Id": "497837",
"Score": "1",
"body": "Those variable names, woof. I'm looking at it and tbh it's a mess. Can you clarify how each of those 5 variables you want should be calculated? Like what does session duration mean in terms of the sample data? If I can get a better handle on what you're calculations look like I can try and write some vectorized versions from scratch for you to see. Maybe not all of them but enough to get you started on syntax and general approach"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T04:18:09.257",
"Id": "497838",
"Score": "1",
"body": "@Coupcoup - sorry for the long names. thanks for looking into this. I will add some info re calculations for the variables"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T06:42:08.647",
"Id": "497845",
"Score": "1",
"body": "@Coupcoup - Please let me know if you need any other clarifications. Again thanks for your help with this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T07:43:00.200",
"Id": "497859",
"Score": "0",
"body": "Looks a lot better. I just finished answering another question on vectorised processing if you want to check that out in the meanwhile otherwise I can give this a go tomorrow"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T07:56:02.253",
"Id": "497862",
"Score": "0",
"body": "Ack, thanks. Will take a look"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T23:34:42.690",
"Id": "497975",
"Score": "0",
"body": "@Coupcoup - Looked at ur other answer for vectorisation. trying to adapt my logic. No success yet. Will keep trying"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T23:37:47.653",
"Id": "497978",
"Score": "0",
"body": "Alright, got some more free time today on this cooped-up thanksgiving. Let me give it a shot"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T03:55:02.503",
"Id": "497996",
"Score": "0",
"body": "This first line `comb_dl_ul_full_191 = comb_dl_ul_full_191.astype(int)` throws `comb_dl_ul_full_191 is undefinied`. I managed to organize some of the later code while watching some gilmore girls with the gf but I need to know what that's supposed to be set to initially to actually run it and test performance improvements"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T03:59:21.717",
"Id": "497997",
"Score": "1",
"body": "lol. thanks a lot. you can assume `comb_dl_ul_full_191` to be the sample dataset that I provided. You will need to load it as dataframe."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T04:06:06.277",
"Id": "497998",
"Score": "1",
"body": "can you rewrite the first few lines before the `for` statement so that your code runs when you copy-paste it into a new file? I can't get what's posted here to run"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T04:07:38.680",
"Id": "497999",
"Score": "0",
"body": "sure, working on it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T04:22:59.953",
"Id": "498000",
"Score": "0",
"body": "@Coupcoup - added some more steps."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T22:02:40.523",
"Id": "498117",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/116701/discussion-between-rfguy-and-coupcoup)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T13:26:29.863",
"Id": "498158",
"Score": "0",
"body": "Hey rfguy, you'll need to change the title of your post as it doesn't fit the guidelines of this site. The title should represent what the code does, not what you want reviewed :) Otherwise people can't know if they have experience or interest in helping you! I've taken the liberty of adding the \"vectorization\" tag to your post, which should get your more visibililty"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T18:09:12.203",
"Id": "498185",
"Score": "0",
"body": "@IEatBagels - Noted. Thanks"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "15",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T03:37:39.190",
"Id": "252633",
"Score": "3",
"Tags": [
"python",
"numpy",
"pandas",
"vectorization"
],
"Title": "Implement vectorization instead of nested loops on dataframe"
}
|
252633
|
<p>This code is a revised version of the implementation which asked for an advice on improvement. Original post here: <a href="https://codereview.stackexchange.com/questions/252232/counting-unival-subtrees">Counting unival subtrees</a>
Credits to: [Deduplicator], [Reinderien], [Toby Speight], [chux].</p>
<p>The revised version was applied following changes:</p>
<ol>
<li>Merge <code>insertRight(), insertLeft()</code> function into <code>createNode</code> function</li>
<li>free resources after use</li>
<li>used <code>const</code> if referenced memory address value is not altered.</li>
<li>fix <code>isTreeUniv()</code> into recursive version</li>
<li>get rid of globals</li>
</ol>
<p>Revised code:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct stTree
{
struct stTree *left;
struct stTree *right;
int value;
} stTree;
stTree* createNode(int value, stTree *leftNode, stTree *rightNode)
{
stTree *node = malloc(sizeof *node);
if (!node) abort();
node->left = leftNode;
node->right = rightNode;
node->value = value;
return node;
}
bool isUnivSubTimpl(const stTree *node, const stTree *parent, size_t *count)
{
if (!node) return 1; //node without child count as unival subT
bool r = isUnivSubTimpl(node->left, node, count) &isUnivSubTimpl(node->right, node, count);
*count += r;
return (r &node->value == parent->value);
}
size_t countUnivSubT(const stTree *node)
{
size_t count = 0;
isUnivSubTimpl(node, node, &count);
return count;
}
static stTree* findBottomLeft(stTree *node)
{
while (node->left)
node = node->left;
return node;
}
bool freeTree(stTree *node)
{
if (!node) return true;
stTree *bottomLeft = findBottomLeft(node);
while (node)
{
if (node->right)
{
bottomLeft->left = node->right;
bottomLeft = findBottomLeft(bottomLeft);
}
stTree *old = node;
node = node->left;
free(old);
}
return true;
}
int main(void)
{
//build a tree
stTree *rootNode =
createNode(0,
createNode(1, NULL, NULL),
createNode(0,
createNode(1,
createNode(1, NULL, NULL),
createNode(1, NULL, NULL)
),
createNode(0, NULL, NULL)));
printf("total universal subree: %u\n", countUnivSubT(rootNode));
if (freeTree(rootNode))
printf("memory released\n");
}
</code></pre>
|
[] |
[
{
"body": "<p>Good job - it's nice to see improvements from the reviews you've received.</p>\n<p>I would recommend using logical <code>&&</code> rather than bitwise <code>&</code> in the computation <code>r &node->value == parent->value</code>. Results should be the same, but programmers expect to see logical operators with boolean values.</p>\n<p>The computation of <code>r</code> cannot use <code>&&</code> as is, because the right-hand side does need to be evaluated for its side-effects, even when the left-hand side is false. I'd consider rewriting as separate expressions, so a future maintainer doesn't "correct" the <code>&</code> to <code>&&</code>:</p>\n<pre><code>bool l_un = isUnivSubTimpl(node->left, node, count); /* updates *count */\nbool r_un = isUnivSubTimpl(node->right, node, count); /* updates *count */\nbool r = l_un && r_un;\n</code></pre>\n<p>Identifiers beginning with <code>is</code> are reserved for Standard Library extension, so I'd advise changing the name <code>isUnivSubTimpl</code>, particularly as it has external linkage.</p>\n<p>It isn't clear to me why <code>freeTree()</code> returns a <code>bool</code>, as it only ever returns <code>true</code>.</p>\n<p>Building the tree could be simplified a little with</p>\n<pre><code>stTree *createLeafNode(int value)\n{\n return createNode(value, NULL, NULL);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T07:44:45.850",
"Id": "498136",
"Score": "0",
"body": "Thank you for the advice. I didn't know that standard library function naming convention."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T09:19:14.197",
"Id": "252642",
"ParentId": "252634",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T05:40:33.973",
"Id": "252634",
"Score": "3",
"Tags": [
"c",
"interview-questions",
"tree"
],
"Title": "Counting unival subtrees - Follow Up"
}
|
252634
|
<p><a href="https://leetcode.com/problems/minimum-path-sum/" rel="nofollow noreferrer">Link here</a></p>
<p>I'll include a solution in Python and C++ and you can review one. I'm mostly interested in reviewing the C++ code which is a thing I recently started learning; those who don't know C++ can review the Python code. Both solutions share similar logic, so the review will apply to any.</p>
<hr />
<h2>Problem statement</h2>
<blockquote>
<p>Given a <span class="math-container">\$ m \times n \$</span> grid filled with non-negative numbers, find a
path from top left to bottom right, which minimizes the sum of all
numbers along its path.</p>
</blockquote>
<p><strong>Note:</strong> You can only move either down or right at any point in time.</p>
<p><strong>Example:</strong></p>
<pre><code>[1, 3, 1]
[1, 5, 1]
[4, 2, 1]
</code></pre>
<p><strong>Output:</strong> 7</p>
<p><strong>Explanation:</strong> Because the path <span class="math-container">\$ 1 \to 3 \to 1 \to 1 \to 1 \$</span> minimizes the sum.</p>
<p>In the python implementation, there is <code>PathFinder</code> class that has some extra methods for visualizing the resulting minimum or maximum path (for fun purposes), the problem requirements are covered only by the first 2 methods <code>_get_possible_moves()</code> and <code>get_path_sum()</code>.</p>
<h3><code>path_sum.py</code></h3>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
class PathFinder:
"""
Path maximizer / minimizer
"""
def __init__(self, matrix, start_point=(0, 0)):
"""
Initialize finder settings.
Args:
matrix: 2D list
start_point: x, y coordinates to start from.
"""
x1, y1 = start_point
self.matrix = matrix[x1:][y1:]
self.seen = {}
self.x_size = len(self.matrix)
self.y_size = len(self.matrix[0])
self.end_x = self.x_size - 1
self.end_y = self.y_size - 1
self.initial_frame, self.processed_frame = (None, None)
def _get_possible_moves(self, x, y):
"""
Get possible next moves.
Args:
x: x coordinate.
y: y coordinate.
Returns:
possible_moves.
"""
possible_moves = []
if x < self.end_x:
possible_moves.append([x + 1, y])
if y < self.end_y:
possible_moves.append([x, y + 1])
return possible_moves
def get_path_sum(self, x, y, mode='min'):
"""
Get minimum / maximum path sum following right and down steps only.
Args:
x: x coordinate.
y: y coordinate.
mode: 'min' or 'max'
Returns:
Minimum or Maximum path sum.
"""
assert mode in ('min', 'max'), f'Invalid mode {mode}'
if (x, y) in self.seen:
return self.seen[x, y]
current = self.matrix[x][y]
if x == self.end_x and y == self.end_y:
return current
possible_moves = self._get_possible_moves(x, y)
results = [
current + self.get_path_sum(*possible, mode) for possible in possible_moves
]
current_best = min(results) if mode == 'min' else max(results)
self.seen[x, y] = current_best
return current_best
def _create_frames(self):
"""
Create pandas DataFrame to preview path followed.
Returns:
Initial frame and a copy.
"""
pd.set_option('expand_frame_repr', False)
initial_frame = pd.DataFrame(self.matrix)
return initial_frame, initial_frame.copy()
def _modify_coordinate(self, x, y):
"""
Mark a coordinate that is in the min/max path.
Args:
x: x coordinate.
y: y coordinate.
Returns:
None
"""
n = self.processed_frame.loc[x, y]
self.processed_frame.loc[x, y] = f'({n})'
def _update_xy(self, x, y):
"""
Follow and mark 1 step of the path.
Args:
x: x coordinate.
y: y coordinate.
Returns:
x, y update.
"""
current_n = self.matrix[x][y]
current_best = self.seen[x, y]
right_best = self.seen[x, y + 1]
down_best = self.seen[x + 1, y]
if current_best - right_best == current_n:
self._modify_coordinate(x, y + 1)
return x, y + 1
if current_best - down_best == current_n:
self._modify_coordinate(x + 1, y)
return x + 1, y
def draw_path(self):
"""
Draw path followed using seen values.
Returns:
2 pandas DataFrames one containing path and another empty.
"""
self.initial_frame, self.processed_frame = self._create_frames()
x, y = 0, 0
self._modify_coordinate(x, y)
while x <= self.end_x or y <= self.end_y:
if y == self.end_y:
for i in range(x + 1, self.x_size):
self._modify_coordinate(i, y)
break
if x == self.end_x:
for i in range(y + 1, self.y_size):
self._modify_coordinate(x, i)
break
x, y = self._update_xy(x, y)
return self.initial_frame, self.processed_frame
if __name__ == '__main__':
m = [
[7, 1, 3, 5, 8, 9, 9, 2, 1, 9, 0, 8, 3, 1, 6, 6, 9, 5],
[9, 5, 9, 4, 0, 4, 8, 8, 9, 5, 7, 3, 6, 6, 6, 9, 1, 6],
[8, 2, 9, 1, 3, 1, 9, 7, 2, 5, 3, 1, 2, 4, 8, 2, 8, 8],
[6, 7, 9, 8, 4, 8, 3, 0, 4, 0, 9, 6, 6, 0, 0, 5, 1, 4],
[7, 1, 3, 1, 8, 8, 3, 1, 2, 1, 5, 0, 2, 1, 9, 1, 1, 4],
[9, 5, 4, 3, 5, 6, 1, 3, 6, 4, 9, 7, 0, 8, 0, 3, 9, 9],
[1, 4, 2, 5, 8, 7, 7, 0, 0, 7, 1, 2, 1, 2, 7, 7, 7, 4],
[3, 9, 7, 9, 5, 8, 9, 5, 6, 9, 8, 8, 0, 1, 4, 2, 8, 2],
[1, 5, 2, 2, 2, 5, 6, 3, 9, 3, 1, 7, 9, 6, 8, 6, 8, 3],
[5, 7, 8, 3, 8, 8, 3, 9, 9, 8, 1, 9, 2, 5, 4, 7, 7, 7],
[2, 3, 2, 4, 8, 5, 1, 7, 2, 9, 5, 2, 4, 2, 9, 2, 8, 7],
[0, 1, 6, 1, 1, 0, 0, 6, 5, 4, 3, 4, 3, 7, 9, 6, 1, 9],
]
finder = PathFinder(m)
print(finder.get_path_sum(0, 0))
print(finder.draw_path()[1])
</code></pre>
<p><strong>Out:</strong></p>
<pre><code>Minimum: 85
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
0 (7) (1) (3) (5) 8 9 9 2 1 9 0 8 3 1 6 6 9 5
1 9 5 9 (4) (0) 4 8 8 9 5 7 3 6 6 6 9 1 6
2 8 2 9 1 (3) (1) 9 7 2 5 3 1 2 4 8 2 8 8
3 6 7 9 8 4 (8) (3) (0) 4 0 9 6 6 0 0 5 1 4
4 7 1 3 1 8 8 3 (1) (2) (1) (5) (0) (2) 1 9 1 1 4
5 9 5 4 3 5 6 1 3 6 4 9 7 (0) 8 0 3 9 9
6 1 4 2 5 8 7 7 0 0 7 1 2 (1) 2 7 7 7 4
7 3 9 7 9 5 8 9 5 6 9 8 8 (0) (1) (4) (2) 8 2
8 1 5 2 2 2 5 6 3 9 3 1 7 9 6 8 (6) 8 3
9 5 7 8 3 8 8 3 9 9 8 1 9 2 5 4 (7) 7 7
10 2 3 2 4 8 5 1 7 2 9 5 2 4 2 9 (2) 8 7
11 0 1 6 1 1 0 0 6 5 4 3 4 3 7 9 (6) (1) (9)
</code></pre>
<p>In the c++ implementation, I used the same algorithm, there is <code>std::vector<std::vector<int>> seen</code> that has the previously calculated sum per location and as this vector does not grow in size, I thought maybe replacing it with a <code>std::array<std::array<int, m >, n></code> where m, n are the matrix dimensions but I get <code>non-type template argument is not a constant expression</code> and I learned that this might not be possible. The proper way is replacing m, n with actual numbers, otherwise it won't work, so I went with the vector.</p>
<h3><code>path_sum.h</code></h3>
<pre class="lang-cpp prettyprint-override"><code>#ifndef LEETCODE_PATH_SUM_H
#define LEETCODE_PATH_SUM_H
#include <vector>
#include <string>
int path_sum(const std::vector<std::vector<int>> &matrix, int x, int y,
std::vector<std::vector<int>> &seen, int empty_value = -1,
const std::string& mode = "min");
#endif //LEETCODE_PATH_SUM_H
</code></pre>
<h3><code>path_sum.cpp</code></h3>
<pre class="lang-cpp prettyprint-override"><code>#include "path_sum.h"
#include <algorithm>
#include <iostream>
int path_sum(const std::vector<std::vector<int>> &matrix, int x, int y,
std::vector<std::vector<int>> &seen, int empty_value,
const std::string &mode) {
int seen_value{seen[x][y]};
if (seen_value != empty_value)
return seen_value;
auto x_end = matrix.size() - 1;
auto y_end = matrix[0].size() - 1;
int current = matrix[x][y];
if (x == x_end && y == y_end)
return current;
std::vector<int> results;
if (x < x_end)
results.push_back(
current + path_sum(matrix, x + 1, y, seen, empty_value, mode));
if (y < y_end)
results.push_back(
current + path_sum(matrix, x, y + 1, seen, empty_value, mode));
int current_best;
switch (results.size()) {
case 1:
seen[x][y] = results[0];
return results[0];
case 2:
int n1{results[0]};
int n2{results[1]};
current_best = (mode == "min") ? std::min(n1, n2) : std::max(n1, n2);
}
seen[x][y] = current_best;
return current_best;
}
int main() {
std::vector<std::vector<int>> matrix{
{7, 1, 3, 5, 8, 9, 9, 2, 1, 9, 0, 8, 3, 1, 6, 6, 9, 5},
{9, 5, 9, 4, 0, 4, 8, 8, 9, 5, 7, 3, 6, 6, 6, 9, 1, 6},
{8, 2, 9, 1, 3, 1, 9, 7, 2, 5, 3, 1, 2, 4, 8, 2, 8, 8},
{6, 7, 9, 8, 4, 8, 3, 0, 4, 0, 9, 6, 6, 0, 0, 5, 1, 4},
{7, 1, 3, 1, 8, 8, 3, 1, 2, 1, 5, 0, 2, 1, 9, 1, 1, 4},
{9, 5, 4, 3, 5, 6, 1, 3, 6, 4, 9, 7, 0, 8, 0, 3, 9, 9},
{1, 4, 2, 5, 8, 7, 7, 0, 0, 7, 1, 2, 1, 2, 7, 7, 7, 4},
{3, 9, 7, 9, 5, 8, 9, 5, 6, 9, 8, 8, 0, 1, 4, 2, 8, 2},
{1, 5, 2, 2, 2, 5, 6, 3, 9, 3, 1, 7, 9, 6, 8, 6, 8, 3},
{5, 7, 8, 3, 8, 8, 3, 9, 9, 8, 1, 9, 2, 5, 4, 7, 7, 7},
{2, 3, 2, 4, 8, 5, 1, 7, 2, 9, 5, 2, 4, 2, 9, 2, 8, 7},
{0, 1, 6, 1, 1, 0, 0, 6, 5, 4, 3, 4, 3, 7, 9, 6, 1, 9}
};
std::vector<std::vector<int>> seen(matrix.size(),
std::vector<int>(matrix[0].size(), -1));
std::cout << "Minimum: " << path_sum(matrix, 0, 0, seen);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T17:24:33.723",
"Id": "497924",
"Score": "1",
"body": "One word: Dijkstra."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T17:27:35.513",
"Id": "497925",
"Score": "0",
"body": "I thought about using it but felt like an overkill for such a simple exercise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T18:18:25.227",
"Id": "497930",
"Score": "1",
"body": "Then you wrote this and though it would have been simpler to write Dijkstra?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T18:29:57.290",
"Id": "497931",
"Score": "0",
"body": "It felt more intuitive, but i agree Dijkstra is well suited for these things"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T00:21:29.930",
"Id": "497981",
"Score": "1",
"body": "Doesn't get accepted, produces `ModuleNotFoundError: No module named 'pandas'`. It's also lacking the `Solution` class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T05:55:34.403",
"Id": "498006",
"Score": "0",
"body": "@superb rain I indicated above that you only need the first 2 methods only which don't use pandas. And since this class `Solution` thing is useless and a bad practice, I don't include it in my questions"
}
] |
[
{
"body": "<h2>Python</h2>\n<ul>\n<li><strong>Naming</strong>: <code>self.x_size</code> and <code>self.y_size</code> can be shorten to <code>self.m</code> and <code>self.n</code>, following from the problem description.</li>\n<li><strong>Initialization</strong>:\n<pre class=\"lang-py prettyprint-override\"><code>x1, y1 = start_point\nself.matrix = matrix[x1:][y1:]\n</code></pre>\nI think that can be safely changed to:\n<pre class=\"lang-py prettyprint-override\"><code>self.matrix = matrix\n</code></pre>\n</li>\n<li><strong>Documentation</strong>:\n<pre><code>def _get_possible_moves(self, x, y):\n """\n Get possible next moves.\n Args:\n x: x coordinate.\n y: y coordinate.\n\n Returns:\n possible_moves.\n """\n</code></pre>\nPersonally, I don't find it useful. Would be better to explain what are the possible moves.</li>\n</ul>\n<h2>Performance</h2>\n<pre><code>Runtime: 208 ms, faster than 5.31% of Python3 online submissions for Minimum Path Sum.\nMemory Usage: 20.6 MB, less than 5.07% of Python3 online submissions for Minimum Path Sum.\n</code></pre>\n<p>The recursive approach is nice but typically slower than the iterative one. In this case, building an iterative solution using dynamic programming seems to be faster. This is an example:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def get_path_sum(matrix):\n m, n = len(matrix), len(matrix[0])\n \n for row in range(1,m):\n matrix[row][0] = matrix[row-1][0] + matrix[row][0]\n \n for col in range(1,n):\n matrix[0][col] = matrix[0][col] + matrix[0][col-1]\n \n for row in range(1,m):\n for col in range(1,n):\n matrix[row][col] = min(matrix[row][col-1],matrix[row-1][col]) + matrix[row][col]\n\n return matrix[-1][-1]\n</code></pre>\n<p>Runtime from LeetCode:</p>\n<pre><code>Runtime: 92 ms\nMemory Usage: 15.6 MB\n</code></pre>\n<h2>Memoization in advance</h2>\n<p>As I mentioned in the comments, the dynamic programming solution has some advantages (in terms of performances) compared to your recursive solution:</p>\n<ol>\n<li>There is no recursion overhead</li>\n<li>It doesn't use additional data structures like <code>seen</code></li>\n<li>It has <span class=\"math-container\">\\$n*m\\$</span> iterations, while your solution does <span class=\"math-container\">\\$2*n*m\\$</span> recursive calls.</li>\n</ol>\n<p>The last point can be improved by doing the memoization in advance:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def get_path_sum(self, x, y, mode='min'):\n # ...\n # Here remove the memoization: if (x, y) in self.seen\n # ...\n results = []\n for move in self._get_possible_moves(x, y):\n # Call recursive function only if needed\n if move in self.seen:\n results.append(current + self.seen[move])\n else:\n results.append(current + self.get_path_sum(*move, mode))\n # ...\n</code></pre>\n<p>Now, the number of recursive calls is <span class=\"math-container\">\\$n*m\\$</span> (ignoring the borders of the matrix). Note that <code>_get_possible_moves</code> returns a list of tuples or even better a generator (like <a href=\"https://codereview.stackexchange.com/a/252689/227157\">@superbrain answer</a>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T12:39:35.457",
"Id": "497886",
"Score": "0",
"body": "Why the recursive approach is slow? and `self.matrix = matrix[x1:][y1:]` is meant for cases where start coordinates are not `(0, 0)` being the default value, it's not required though, thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T13:13:36.740",
"Id": "497892",
"Score": "1",
"body": "@bullseye what I am saying is that taken an iterative and a recursive implementation of the same function, the iterative is [typically faster](https://stackoverflow.com/a/2651200/8484783). However, the example I provided is not really your function translated to iterative, so maybe not the best evidence."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T13:17:58.517",
"Id": "497893",
"Score": "0",
"body": "Yes, I fully understand what you're saying, I'm just wondering why the recursive approach is not as fast, I mean in terms of complexity, what is the complexity for both approaches?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T14:04:14.820",
"Id": "497896",
"Score": "1",
"body": "@bullseye the iterative solution has no \"recursive overhead\" and doesn't use additional data structures like `seen` and `possible_moves`, maybe that's why. Also your solution has two recursive calls for each element, mitigated with memoization but still."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T18:45:25.853",
"Id": "497933",
"Score": "2",
"body": "Especially in Python. Remember that Python has no proper tail calls. Actually, tail-call-optimization is forbidden."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T00:31:09.490",
"Id": "497983",
"Score": "1",
"body": "@bullseye `matrix[x1:][y1:]` doesn't even work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T03:14:41.077",
"Id": "497994",
"Score": "0",
"body": "@bullseye FYI I added a section about memoization."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T05:58:29.293",
"Id": "498007",
"Score": "0",
"body": "@Mark thanks, I'll check"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T12:21:27.897",
"Id": "252648",
"ParentId": "252638",
"Score": "3"
}
},
{
"body": "<p>Well, as <a href=\"/u/227157\">Marc</a> said, your current recursive algorithm is wasteful.</p>\n<p>The way he uses dynamic programming has an advantage, namely you can easily trace the path taken, but also a decided disadvantage, you are destroying the input-matrix.</p>\n<p>If you don't care about extracting the way taken, you only need two rows (or columns, symmetry is nice) for calculations.</p>\n<p>Now, your inexperience with C++ (and more experience with Python) shows, so let's dissect that solution:</p>\n<ol>\n<li><p>Creating a header-file for the main file is uncommon. Especially in your case, where you don't need forward-declarations at all.</p>\n</li>\n<li><p>You shouldn't pass a <code>std::vector</code> by constant reference unless you must. Pass a <a href=\"//en.cppreference.com/w/cpp/container/span\" rel=\"nofollow noreferrer\"><code>std::span</code></a> (or <code>gsl::span</code> pre-C++20) by value instead.<br />\nSee "<em><a href=\"//stackoverflow.com/questions/45723819/what-is-a-span-and-when-should-i-use-one\">What is a “span” and when should I use one?</a></em>" for more details.</p>\n</li>\n<li><p>You should use a type for dense matrices. Not only would it be more semantic, but also far more efficient.</p>\n<p>A vector-of-vectors is far more amorph, backed by many independent allocations, and using far more expensive indirection. Thus, you cannot efficiently read an arbitrary cell, or move from cell to cell.</p>\n<p>There are many matrix-classes even on this site, and some are sufficient.</p>\n</li>\n<li><p>For passing the coordinate-pair <code>x</code> and <code>y</code> you could use a dedicated point-class, or a <code>std::pair</code>. If you unclutter the rest, one can justify passing them separately though.</p>\n</li>\n<li><p>Making the caller allocate your scratch space causes all kinds of headaches and inconvenience, aside from being a bad break of proper abstraction. Desist from burdening the caller.</p>\n</li>\n<li><p>If you pass a string just for reading it, and it doesn't <em>have</em> to be nul-terminated, pass a <a href=\"//en.cppreference.com/w/cpp/string/basic_string_view\" rel=\"nofollow noreferrer\"><code>std::string_view</code></a> by value, not a <code>std::string</code> by constant reference. It's more efficient and versatile.</p>\n</li>\n<li><p>Passing a string for selecting a mode is such a scripting thing to do. In C++, if a <code>bool</code> is insufficiently explicit, we use an enum. Much more efficient and type-safe, especially if it's an enum-class.</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T18:03:28.303",
"Id": "497928",
"Score": "0",
"body": "1. It's my fault, it's not the main file, I just added main() for posting it here, I have it separately on my laptop. 2. Why I shouldn't pass a vector by reference? and what is std::span? 3. did not get what you mean 4. should I use a std::pair or shouldn't I? 5.What's the proper way? I need you to ellaborate on most of the points if possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T18:41:26.000",
"Id": "497932",
"Score": "1",
"body": "Elaborated most. Re 5: If not the caller, there is only the callee."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T17:10:53.170",
"Id": "252666",
"ParentId": "252638",
"Score": "2"
}
},
{
"body": "<p>This looks simpler:</p>\n<pre><code>#include <vector>\n#include <iostream>\n\nusing Row = std::vector<int>;\nusing Matrix = std::vector<Row>;\n\nint getMinCostToParent(Matrix const& matrix, int y, int x)\n{\n // The min cost to the parent is the min cost\n // to either the parent above you or to your left.\n // If you are on the edge of the use the other value.\n\n return (x == 0 && y == 0) ? 0\n : (x == 0) ? matrix[y-1][x]\n : (y == 0) ? matrix[y][x-1]\n : std::min(matrix[y-1][x], matrix[y][x-1]);\n}\n\nint path_sum(Matrix matrix)\n{\n // Pass `matrix` by value to get a copy.\n // As we are going to overwrite its content.\n\n // For each square calculate the min cost to get there.\n for (int y = 0; y < matrix.size(); ++y) {\n for (int x = 0; x < matrix[y].size(); ++x) {\n matrix[y][x] = getMinCostToParent(matrix, y, x) + matrix[y][x];\n }\n }\n // The bottom right square contains the total cost.\n return matrix.back().back();\n}\n\n\nint main() {\n Matrix matrix{\n {7, 1, 3, 5, 8, 9, 9, 2, 1, 9, 0, 8, 3, 1, 6, 6, 9, 5},\n {9, 5, 9, 4, 0, 4, 8, 8, 9, 5, 7, 3, 6, 6, 6, 9, 1, 6},\n {8, 2, 9, 1, 3, 1, 9, 7, 2, 5, 3, 1, 2, 4, 8, 2, 8, 8},\n {6, 7, 9, 8, 4, 8, 3, 0, 4, 0, 9, 6, 6, 0, 0, 5, 1, 4},\n {7, 1, 3, 1, 8, 8, 3, 1, 2, 1, 5, 0, 2, 1, 9, 1, 1, 4},\n {9, 5, 4, 3, 5, 6, 1, 3, 6, 4, 9, 7, 0, 8, 0, 3, 9, 9},\n {1, 4, 2, 5, 8, 7, 7, 0, 0, 7, 1, 2, 1, 2, 7, 7, 7, 4},\n {3, 9, 7, 9, 5, 8, 9, 5, 6, 9, 8, 8, 0, 1, 4, 2, 8, 2},\n {1, 5, 2, 2, 2, 5, 6, 3, 9, 3, 1, 7, 9, 6, 8, 6, 8, 3},\n {5, 7, 8, 3, 8, 8, 3, 9, 9, 8, 1, 9, 2, 5, 4, 7, 7, 7},\n {2, 3, 2, 4, 8, 5, 1, 7, 2, 9, 5, 2, 4, 2, 9, 2, 8, 7},\n {0, 1, 6, 1, 1, 0, 0, 6, 5, 4, 3, 4, 3, 7, 9, 6, 1, 9}\n };\n std::cout << "Minimum: " << path_sum(matrix) << "\\n";\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T23:29:41.587",
"Id": "252687",
"ParentId": "252638",
"Score": "2"
}
},
{
"body": "<p>I'd make</p>\n<pre><code> def _get_possible_moves(self, x, y):\n possible_moves = []\n if x < self.end_x:\n possible_moves.append([x + 1, y])\n if y < self.end_y:\n possible_moves.append([x, y + 1])\n return possible_moves\n</code></pre>\n<p>a generator:</p>\n<pre><code> def _get_possible_moves(self, x, y):\n if x < self.end_x:\n yield x + 1, y\n if y < self.end_y:\n yield x, y + 1\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T00:27:05.667",
"Id": "252689",
"ParentId": "252638",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "252648",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T07:49:45.500",
"Id": "252638",
"Score": "2",
"Tags": [
"python",
"c++",
"programming-challenge"
],
"Title": "Leetcode minimum path sum"
}
|
252638
|
<p>Is there a neater way of handling the option response from <code>req.cookie()</code> in this code block (line 3 onwards)? Id like to avoid the nested if statements, and multiple returns if at all possible. <code>req.cookie()</code> returns an <code>Option<Cookie></code> and the <code>Cookie</code> struct has a value function. If the cookie is present but has the wrong value, i want to return a bad request, however i also want to return a bad request if the cookie is not present at all. If the cookie value is OK, i want to continue and do further work:</p>
<pre><code>#[get("/callback")]
async fn callback(req: HttpRequest, client: web::Data<BasicClient>, web::Query(cb): web::Query<Callback>) -> Result<HttpResponse> {
if let Some(state_cookie) = req.cookie(STATE_COOKIE_NAME) {
if state_cookie.value() != cb.state {
return Ok(HttpResponse::BadRequest().finish())
}
} else {
return Ok(HttpResponse::BadRequest().finish())
}
let token_result = client.exchange_code(AuthorizationCode::new(cb.code)).request(http_client);
return match token_result {
Ok(token_details) => Ok(handle_success(token_details)),
Err(token_error) => Ok(handle_error(token_error))
}
}
</code></pre>
|
[] |
[
{
"body": "<p>There is a way without multiple returns and nested <code>if</code> statements.</p>\n<p>You have three control flow pathways in your program, related to three states of <code>state_cookie</code> respectively:</p>\n<ul>\n<li>cookie is <code>Some</code> and <code>state_cookie.value() == cb.state</code></li>\n<li>cookie is <code>Some</code> and <code>state_cookie.value() != cb.state</code></li>\n<li>cookie is <code>None</code></li>\n</ul>\n<p>For the first, we proceed, whereas for second and third we branch to do the same return. Do the 2. and 3. have anything in common? They cover all except one value.</p>\n<p>You may be coming from a language where data types lack expressiveness. Many languages don't have <code>Option</code> at all. In Rust, we have deep operations on Algebraic Data Types like <code>Option</code>.</p>\n<p>To postpone comparison and branching until we have all information, we do a <code>map</code> on the <code>Option</code>: <code>req.cookie(STATE_COOKIE_NAME).map(|sc| sc.value())</code>. Then, a simple comparison divides our function into two control flow paths. As an extra, for self-documenting code, we make a short-lived binding for <code>state_cookie_value</code>:</p>\n<pre><code>#[get("/callback")]\nasync fn callback(req: HttpRequest, client: web::Data<BasicClient>, web::Query(cb): web::Query<Callback>) -> Result<HttpResponse> {\n let state_cookie_value = req.cookie(STATE_COOKIE_NAME).map(|sc| sc.value());\n if state_cookie_value != Some(cb.state) {\n return Ok(HttpResponse::BadRequest().finish());\n }\n\n let token_result = client.exchange_code(AuthorizationCode::new(cb.code)).request(http_client);\n\n match token_result {\n Ok(token_details) => Ok(handle_success(token_details)),\n Err(token_error) => Ok(handle_error(token_error))\n }\n}\n</code></pre>\n<p>This is basically all in this code.</p>\n<p>I believe this may obscure the code's meaning for the reader, but you can as well write the <code>match</code> statement as:</p>\n<p><code>Ok(token_result.map_or_else(handle_error, handle_success))</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T10:03:37.690",
"Id": "252747",
"ParentId": "252639",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "252747",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T08:14:23.973",
"Id": "252639",
"Score": "2",
"Tags": [
"rust",
"optional"
],
"Title": "Rust idiomatic option handling"
}
|
252639
|
<p>I made a snake game in HTML/CSS/JavaScript. I want to make my code better and shorter.</p>
<p>Here is my codes:</p>
<p>index.html:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>Snake Game</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<p class="score" draggable="true"></p>
<canvas class="canvas" height="400" width="400"></canvas>
<script src="index.js"></script>
<script src="rclick0.js"></script>
</body>
</html>
</code></pre>
<p>index.css:</p>
<pre><code>body {
background-color: #FFFFFF;
}
p {
font-size: 24px;
}
canvas {
background-color: #3C3C3C;
cursor: none;
}
</code></pre>
<p>index.js:</p>
<pre><code>function Food() {
this.x;
this.y;
this.pickLocation = function() {
this.x = (Math.floor(Math.random() *
columns - 1) + 1) * scale;
this.y = (Math.floor(Math.random() *
rows - 1) + 1) * scale;
}
this.draw = function() {
ctx.fillStyle = "#FF1E00";
ctx.fillRect(this.x, this.y, scale, scale)
}
}
function Snake() {
this.x = (Math.floor(Math.random() *
columns - 1) + 1) * scale;
this.y = (Math.floor(Math.random() *
rows - 1) + 1) * scale;
this.xSpeed = scale * 1;
this.ySpeed = 0;
this.total = 0;
this.tail = [];
this.draw = function() {
ctx.fillStyle = "#FFFFFF";
for (let i = 0; i<this.tail.length; i++) {
ctx.fillRect(this.tail[i].x,
this.tail[i].y, scale, scale);
}
ctx.fillRect(this.x, this.y, scale, scale);
}
this.update = function() {
for (let i = 0; i<this.tail.length - 1; i++) {
this.tail[i] = this.tail[i + 1];
}
this.tail[this.total - 1] =
{ x: this.x, y: this.y };
this.x += this.xSpeed;
this.y += this.ySpeed;
if (this.x > canvas.width) {
this.x = 0;
}
if (this.y > canvas.height) {
this.y = 0;
}
if (this.x < 0) {
this.x = canvas.width;
}
if (this.y < 0) {
this.y = canvas.height;
}
}
this.changeDirection = function(direction) {
switch (direction) {
case 'w':
this.xSpeed = 0;
this.ySpeed = -scale * 1;
break;
case 's':
this.xSpeed = 0;
this.ySpeed = scale * 1;
break;
case 'a':
this.xSpeed = -scale * 1;
this.ySpeed = 0;
break;
case 'd':
this.xSpeed = scale * 1;
this.ySpeed = 0;
break;
}
}
this.eat = function(food) {
if (this.x === food.x &&
this.y === food.y) {
this.total++;
return true;
}
return false;
}
this.checkCollision = function() {
for (var i = 0; i<this.tail.length; i++) {
if (this.x === this.tail[i].x &&
this.y === this.tail[i].y) {
this.total = 0;
this.tail = [];
}
}
}
}
const canvas = document.querySelector(".canvas");
const ctx = canvas.getContext("2d");
const scale = 10;
const rows = canvas.height / scale;
const columns = canvas.width / scale;
var snake;
(function setup() {
snake = new Snake();
food = new Food();
food.pickLocation();
window.setInterval(() => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
food.draw();
snake.update();
snake.draw();
if (snake.eat(food)) {
food.pickLocation();
}
snake.checkCollision();
document.querySelector('.score')
.innerText = snake.total;
}, 250);
}());
window.addEventListener('keydown', ((evt) => {
const direction = evt.key.replace('Arrow', '');
snake.changeDirection(direction);
}));
</code></pre>
<p>rclick0.js:</p>
<pre><code>document.addEventListener('contextmenu', event => event.preventDefault());
</code></pre>
<p>(This code may be updated in my <a href="https://github.com/ArianKG" rel="nofollow noreferrer">GitHub</a> account.)</p>
|
[] |
[
{
"body": "<h2>Strict Mode</h2>\n<p>Always include the directive "use strict"; as the first line of the JS file, or use modules which are automatically in strict mode.</p>\n<p>Strict mode will throw errors for many of the common bad coding patterns (such as undeclared variables)</p>\n<h2>Always declare variables.</h2>\n<p>You have the variable <code>food</code> that is undeclared, it is thus added to the global scope. This can result in hard to spot bug as the variable may be change elsewhere</p>\n<h2>Use the space available.</h2>\n<p>Indent chained lines. For example</p>\n<pre><code>document.querySelector('.score')\n.innerText = snake.total;\n</code></pre>\n<p>Indent the second line to show that the two lines are related.</p>\n<pre><code>document.querySelector('.score')\n .innerText = snake.total;\n\n// or better\n \ndocument.querySelector('.score').innerText = snake.total; \n\n \n</code></pre>\n<p>The longest line you have is less than 60 characters. You have broken many lines in two that where under 80 characters.</p>\n<p>Unless you are stuck coding on a tiny display using an editor without line wrap there is no good reason to break up lines under 80 characters (personally I break lines not due to length but when there are too many abstractions, eg a function call with many arguments)</p>\n<h2>Code noise</h2>\n<p>Code noise is code that does nothing, does something in a long winded way, repeates the same or similar code</p>\n<h3>Superfluous noise</h3>\n<p>You do some odd math in several places</p>\n<p><code>a - 1 + 1</code> the <code>- 1 + 1</code> is superfluous</p>\n<p><code>a * 1</code> the <code>* 1</code> is superfluous</p>\n<p><code>window.</code> is the global this and 99% of the time you don't need it\neg</p>\n<p><code>window.addEventListener('keydown', ((evt) => {</code> can be <code>addEventListener('keydown', ((evt) => {</code></p>\n<p>and <code>window.setInterval(() => {</code> becomes just <code>setInterval(() => {</code></p>\n<h3>Long winded noise</h3>\n<p>You can floor positive integers using bitwise or. <code>Math.floor(Math.random() * columns</code> becomes <code>Math.random() * columns | 0</code></p>\n<p>Learn to use closure and avoid the 61 times you have <code>this.</code> in your code</p>\n<p>You check the bounds of movement with 4 <code>if</code> statements adding 12 lines of code. The same can be done in two lines of code (see rewrite)</p>\n<p>You use a switch statement to change directions. Create an object with named directions and you can remove 18 lines of noisy code. (see rewrite)</p>\n<p>Use <code>for of</code> when you only need each item and use <code>for;;</code> when you need the index of each item</p>\n<h3>DRY code to reduce noise</h3>\n<p><strong>Use functions</strong></p>\n<p>The random coordinate can be made a functions. eg <code>randInt = range => Math.random() * range | 0</code>, or both values as one function <code>const randPos = () => [(Math.random() * columns | 0) * scale, (Math.random() * rows | 0) * scale];</code></p>\n<p><strong>Use modern Javascript</strong></p>\n<p>Destructuring assignments: <code>var [x, y] = randPos();</code> (see rewrite)</p>\n<p>Object property shorthand: <code>{x: x, y: y}</code> becomes <code>{x, y}</code></p>\n<p>Object function shorthand: <code>obj.blah = function() {}; obj.foo = function() {}</code> can be <code>obj = { blah(){},foo(){} }</code></p>\n<p><strong>Store data</strong></p>\n<p><code>canvas.width, canvas.height</code> don't change in your code so store the values so you don't have the type <code>canvas.</code> each time you want a size value</p>\n<h2>The rewrite</h2>\n<p>The code's behavior has not been changes. It is intended to be a module. <code><script src="snakeGame.jsm" type="module"></script></code></p>\n<p>(There are some potential bugs in the code that the rewrite has not addressed). The rewrite is as an example only and has been checked for syntax errors, but has not been run.</p>\n<p>The rewrite is 67 lines compared to the 120 lines of your original. The most reliable metric used to determine application fitness is <a href=\"https://en.wikipedia.org/wiki/Source_lines_of_code\" rel=\"nofollow noreferrer\">source code line count</a>. Less code is easier to read, understand and maintain. Has fewer bugs</p>\n<pre><code>"use strict"; // Not needed if you have this code in a module\nconst FOOD_COL = "#FF1E00";\nconst SNAKE_COL = "#FFFFFF";\nconst SCALE = 10;\nconst START_DIR = "w";\nconst directions = {w: {x: 0, y: -1}, s: {x: 0, y: 1}, a: {x: -1, y: 0}, d: {x: 1, y: 0}};\nconst canvas = document.querySelector(".canvas");\nconst score = document.querySelector(".score");\nconst ctx = canvas.getContext("2d");\nconst W = canvas.width, H = canvas.height;\nconst randInt = (r) => Math.random() * r | 0;\nconst randPos = () => [randInt(W / SCALE) * SCALE, randInt(H / SCALE) * SCALE];\naddEventListener('keydown', (evt) => {snake.direction = evt.key});\n\nvar snake = Snake(), food = Food();\nfood.place();\nscore.innerText = 0;\nsetInterval(() => {\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n food.draw();\n snake.update();\n snake.draw();\n snake.eat(food) && (food.place(), score.innerText = snake.score);\n snake.collision();\n}, 250);\n\nfunction Food(x, y) {\n return {\n place() { [x, y] = randPos() },\n isAt(xx, yy) { return xx === x && yy === y },\n draw() {\n ctx.fillStyle = FOOD_COL;\n ctx.fillRect(x, y, SCALE, SCALE)\n }\n };\n}\n\nfunction Snake() {\n var [x, y] = randPos();\n var total = 0, tail = [], dir = directions[START_DIR];\n return {\n get score() { return total },\n set direction(direction) { dir = directions[direction] ?? dir },\n draw() {\n ctx.fillStyle = SNAKE_COL;\n for (const t of tail) { ctx.fillRect(t.x, t.y, SCALE, SCALE) }\n ctx.fillRect(x, y, SCALE, SCALE);\n },\n update() {\n for (let i = 0; i < tail.length - 1; i++) { tail[i] = tail[i + 1] }\n tail[total - 1] = {x, y};\n x = ((x + dir.y * SCALE) + W) % W;\n y = ((y + dir.x * SCALE) + H) % H;\n },\n eat(food) { return food.isAt(x, y) ? (total++, true) : false },\n collision() {\n for (const t of tail) {\n if (x === t.x && y === t.y) {\n total = 0;\n tail = [];\n return;\n }\n }\n },\n };\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T05:52:55.290",
"Id": "252694",
"ParentId": "252641",
"Score": "2"
}
},
{
"body": "<p>I suggest making domain logic more explicit to improve the readability of the code. By reading the definition of the <code>update</code> function that recalculates state and do rendering on each tick, you should get a good understanding of what game rules are without implementation details.</p>\n<p>For this type of applications (games), I advise using an object-oriented style to represent entities and a functional style for specific calculations.</p>\n<p>Also, I would recommend using dependency injection to make boundaries between objects more clear and to make objects testable. That means not relying on the parent scope heavily.</p>\n<p>Although my solution is bigger than yours, I tried making it as readable as possible. I didn't post all files, only the most important ones. Here it is.</p>\n<p><em>index.mjs</em></p>\n<pre><code>import {makeSnake} from './snake.mjs';\nimport {makeFood, makeFoods} from './food.mjs';\nimport {makeScore} from './score.mjs';\nimport {makeField} from './field.mjs';\nimport {makeRenderer} from "./renderer.mjs";\nimport {right} from "./directions.mjs";\nimport {update} from "./update.mjs";\nimport {onNewDir} from "./keyboard.mjs";\n\nconst canvas = document.querySelector('.canvas');\nconst ctx = canvas.getContext('2d');\n\nconst renderer = makeRenderer({ctx, scale: 40});\nconst field = makeField(renderer.pxToCells(canvas.width), renderer.pxToCells(canvas.height));\nconst randomFood = () => makeFood(field.randomCell());\nconst snake = makeSnake({row: 5, col: 3}, [], right);\nconst foods = makeFoods(randomFood());\nconst score = makeScore();\n\nonNewDir((dir) => {\n snake.changeDir(dir);\n});\n\nupdate(ctx, () => {\n snake.move(field);\n\n if (snake.canEat(foods.active())) {\n snake.eat();\n score.add();\n foods.activate(randomFood());\n }\n\n if (snake.canEatSelf()) {\n snake.loseTail();\n score.reset();\n }\n\n score.render(document.querySelector('.score'));\n snake.render(renderer);\n foods.active().render(renderer);\n});\n</code></pre>\n<p><em>snake.mjs</em></p>\n<pre><code>import { left, right, up, down } from "./directions.mjs";\nimport {sameCell} from "./cells.mjs";\n\nconst newPos = ({row, col}, dir, speed) => {\n return {\n [left]: {row, col: (col - speed)},\n [right]: {row, col: (col + speed)},\n [up]: {row: row - speed, col},\n [down]: {row: row + speed, col},\n }[dir];\n};\n\nconst insert = (arr, index, el) => arr.splice(index, 0, el);\nconst insertFirst = (arr, el) => insert(arr, 0, el);\nconst remove = (arr, index) => arr.splice(index, 1);\nconst removeLast = (arr) => remove(arr, arr.length - 1);\n\nconst makeLastPos = (cell) => ({\n get() {\n return cell;\n },\n\n update(head, tail) {\n cell = tail.length > 0 ? {...tail[length - 1]} : {...head};\n }\n\n});\n\nexport const makeSnake = (head, tail, dir, speed = 1) => {\n const lastPos = makeLastPos();\n\n return {\n move(field) {\n if (tail.length > 0) {\n insertFirst(tail, head);\n removeLast(tail);\n }\n\n head = field.normalize(newPos(head, dir, speed));\n lastPos.update(head, tail);\n },\n\n render(renderer) {\n renderer.drawSquare(head, '#FFFFFF');\n tail.forEach((cell) => renderer.drawSquare(cell, '#FFFFFF'));\n },\n\n changeDir(d) {\n dir = d;\n },\n\n canEat(food) {\n return sameCell(head, food);\n },\n\n eat() {\n tail.push(lastPos.get());\n },\n\n canEatSelf() {\n return tail.some((cell) => sameCell(head, cell)) && !sameCell(head, lastPos.get());\n },\n\n loseTail() {\n tail = [];\n }\n }\n}\n</code></pre>\n<p><em>food.mjs</em></p>\n<pre><code>export const makeFood = ({row, col}) => {\n return {\n row, col,\n\n render(renderer) {\n renderer.drawSquare({row, col}, '#FF1E00');\n },\n }\n}\n\nexport const makeFoods = (food) => {\n return {\n activate(f) {\n food = f;\n },\n\n active() {\n return food;\n }\n }\n}\n</code></pre>\n<p><em>score.mjs</em></p>\n<pre><code>export const makeScore = (val = 0) => {\n return {\n add() {\n val += 1;\n },\n\n reset() {\n val = 0;\n },\n\n render(el) {\n el.innerText = val.toString();\n }\n }\n}\n</code></pre>\n<p><em>field.mjs</em></p>\n<pre><code>const random = (from, to) => Math.floor(Math.random() * to) + from;\n\nexport const makeField = (rows, columns) => {\n return {\n normalize({row, col}) {\n const calc = (max, val) => {\n if (val > max) return 0;\n if (val < 0) return max;\n return val;\n };\n\n return {row: calc(rows, row), col: calc(columns, col)};\n },\n\n randomCell() {\n return { row: random(0, rows - 1), col: random(0, columns - 1) };\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-28T20:55:34.877",
"Id": "252796",
"ParentId": "252641",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "252694",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T09:13:39.547",
"Id": "252641",
"Score": "2",
"Tags": [
"javascript",
"html",
"css",
"snake-game"
],
"Title": "A snake game in HTML/CSS/JavaScript"
}
|
252641
|
<p>I write a function using PHP and MySQL, to get PDO connection, query and array of placeholders to execute query and return result.</p>
<p>I test this function and it has good response when result for <code>SELECT</code> has empty result or has error; do you see any problems, or have tips to say about this?</p>
<p>Do you have any tips about this to test or check?</p>
<h3>Function and test code</h3>
<pre><code>function db_query_pdo( PDO $pd, $q,$ar )
{
// $pd Pdo connection object, $q query string , $ar array of placeholders
try
{
$stmt = $pd->prepare($q);
$x=$stmt->execute($ar);
$rs=$stmt->fetchAll();
if(!empty($rslt))
return $rslt;
else
return $x;
}
catch (Exception $ex)
{
echo 'Query failed';
// exit(); uncomment this lines if needed in future
// echo $ex->getCode();
// echo $ex->getMessage();
// throw $ex;
}
}
// TEST CODE
$pdo_cnctn=db_con_pdo(); // is a pdo connection function that worked correctly and return connection object
$id=133;
$id2=77;
$query='SELECT * FROM `users` WHERE u_id=:uid OR u_id=:uid2;
';
$vals=[
'uid' => $id,
'uid2' => $id2
];
$res= db_query_pdo($pdo_cnctn,$query,$vals);
//$res[] = $stmt->fetch();
if(!is_bool($res))
{
var_dump($res);
}
else
{
// $$pdo_cnctn->rollBack();
echo 'Not Found';
goto end_point;
}
//some codes
end_point:
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T15:44:50.557",
"Id": "497906",
"Score": "1",
"body": "Please do not edit the question after an answer has been provided. Everyone needs to see what the person that wrote the answer saw."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T15:52:24.840",
"Id": "497908",
"Score": "0",
"body": "OK, Thanks.\nHow can I increase the number of views of the post over a long time?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T16:18:28.390",
"Id": "497914",
"Score": "0",
"body": "You can ask follow up questions, which is a new question based on the old question with a link to the old question. You can also answer questions and ask new questions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T05:07:19.013",
"Id": "498002",
"Score": "0",
"body": "@pacmaninbw OK, thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T05:56:30.370",
"Id": "510296",
"Score": "0",
"body": "In this forum, editing a question does not change its order in any list. Having optimal tags can help (up to the limit of 5). And a good title helps catch attention."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T05:59:51.403",
"Id": "510297",
"Score": "0",
"body": "In Perl, the package `DBIx::DWIW` is a good simplification _for Perl&MySQL_. It minimizes keystrokes without losing functionality."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T19:37:01.357",
"Id": "510540",
"Score": "0",
"body": "@rick-james in tags I added PHP so its obvious. why use perl instead of php when perl is a danger in executing robots and worms of hackers or any malwares?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T20:50:02.497",
"Id": "510549",
"Score": "0",
"body": "I was pointing out a package that does some of what you are looking for. Unfortunately, I do not know of an equivalent PHP package."
}
] |
[
{
"body": "<p>First of all, it's a very good thing that you came to the idea of such a function. Sadly, but out of many people asking questions on Stack Overflow, only a handful ever come to such an idea. It means you're a natural born programmer, with an eye for the sub-optimal code and the desire to make it better.</p>\n<p>The regular routine with prepared statements is not that optimal indeed, you need two function calls instead of one. Some drivers already have such a function to execute the prepared query in one go, <code>pg_query_params()</code> for example. But for PDO we have to create one of our own.</p>\n<h3>The function</h3>\n<p>However, the code for such a function should be much, much simper. Basically it's just three lines</p>\n<pre><code>function db_query_pdo( PDO $pd, $q, $ar )\n{\n $stmt = $pd->prepare($q);\n $stmt->execute($ar);\n return $stmt;\n}\n</code></pre>\n<p>surprisingly, that's all you really need. The rest is either harmful, superfluous or can be achieved by other means.</p>\n<pre><code>$query='SELECT * FROM `users` WHERE u_id=:uid OR u_id=:uid2';\n$vals=[\n 'uid' => $id,\n 'uid2' => $id2\n];\n\n$res = db_query_pdo($pdo_cnctn,$query,$vals)->fetchAll();\nif($res)\n{\n var_dump($res);\n}\nelse\n{\n echo 'Not Found';\n}\n</code></pre>\n<p>See, the calling code is almost the same, but the function became</p>\n<p>a) much cleaner<br />\nb) much more versatile, as you can chain any PDOStatement method to it, not limited to the return value of fetchAll()</p>\n<p>Say, you've got a <em>delete</em> query and want to know whether it deleted any rows? No problemo!</p>\n<pre><code>if (db_query_pdo($pdo_cnctn,"DELETE FROM t WHERE id=?",[1])->rowCount()) {\n echo "deleted";\n}\n</code></pre>\n<p>or you want a fetchAll() but with different modifier:</p>\n<pre><code>$ids = db_query_pdo($pdo_cnctn,"SELECT id FROM t WHERE id<?",[10] )->fetchAll(PDO::FETCH_COLUMN);\n</code></pre>\n<p>or you want to get a single value</p>\n<pre><code>$exists = db_query_pdo($pdo_cnctn,"SELECT 1 FROM t WHERE email=?",[$email] )->fetchColumn();\n</code></pre>\n<p>etc., etc., etc.</p>\n<h3>The error reporting</h3>\n<p>To be honest, all that try catch business in your function is completely off the track. Especially that commented out section, "uncomment this lines if needed in future". Seriously? Are you really going to comment these lines back and forth? That's not how a good program should be written. It shouldn't require anything like this.</p>\n<p>Besides, this approach is based on the two <strong>wrong notions</strong> which, sadly, are extremely popular among PHP folks:</p>\n<ul>\n<li>"an error must be thrown only in some circumstances". That's but a grave delusion. A programmer desperately needs the error message no matter that. An error must be thrown every time, no exceptions. As a matter of fact, in the production environment the error message is much more important than in the dev. Without the error message a programmer will never have an idea what's going wrong</li>\n<li>"a database function should decide what to do with its errors". This is a funny one. There is nothing special in the database interactions. But for some reason PHP users diligently wrap their database functions in a distinct handling code. At the same time completely neglecting every single other line in the code. It just makes no sense. A database error is no different from a filesystem error. And as you don't wrap every <code>include</code> in a distinct try catch, you should never do it for a db function either.</li>\n</ul>\n<p>All the error handling business should occur elsewhere. You can read more about <a href=\"https://phpdelusions.net/articles/error_reporting\" rel=\"nofollow noreferrer\">error reporting basics</a> from my article.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T12:56:04.637",
"Id": "497890",
"Score": "0",
"body": "thanks a lot, I'll wait for other answers and will choose the best.You're good man,I hope you're always healthy"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T05:48:00.860",
"Id": "498004",
"Score": "0",
"body": "Please, no. Don't recommend anyone to extend PDO class. This separate function makes much more sense because it works for all PDO instances, not just instances of a custom subclass."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T05:50:48.630",
"Id": "498005",
"Score": "0",
"body": "@sidoco cc read my above comment please"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T06:53:47.167",
"Id": "498008",
"Score": "0",
"body": "@slepic which function, his or mine? Can you explain more in new answer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T06:54:50.573",
"Id": "498009",
"Score": "0",
"body": "@slepic all right all right, deleted. no more fuss"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T07:01:19.467",
"Id": "498012",
"Score": "0",
"body": "@YourCommonSense\nWhats your opinion about this: [PDO class](https://paste.gg/p/anonymous/db36d928fba14c26b2d259813e24383a)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T07:01:37.043",
"Id": "498013",
"Score": "0",
"body": "@slepic\nWhats your opinion about this: [PDO class](https://paste.gg/p/anonymous/db36d928fba14c26b2d259813e24383a)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T07:04:42.397",
"Id": "498014",
"Score": "0",
"body": "@sidoco that's just a sketch, impossible to say anything. Make it complete, use for some time in the real life code, then you will see"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T15:26:41.307",
"Id": "498069",
"Score": "0",
"body": "@sidoco i think the class you linked is crap. Anyway I mean the 3 line db_query_pdo function as shown by YCS, the one stripped off the error handling nonsense..."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T10:57:55.553",
"Id": "252646",
"ParentId": "252643",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "252646",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T09:23:57.800",
"Id": "252643",
"Score": "5",
"Tags": [
"php",
"mysql",
"pdo"
],
"Title": "function for PDO queries and return result - tested - any tips?"
}
|
252643
|
<p>I have a main-class that takes a list of sources and returns two objects for each source; one with the required data and one analytics tool.</p>
<p>The <code>Analytics</code>-class has different methods depending on what source it is. The <code>Data</code>-class extracts data from different paths and cleans the data in different ways depending on the source. Importing/exporting is made through pandas <code>read_excel()</code>. The analytics tool outputs some calculations based on what source the data comes from.</p>
<pre><code>class Main_class():
def __init__(self, sources = ['a','b','c']):
self.data_sources = {}
self.analytics = {}
for s in sources:
self.data_sources[s] = Data(s)
self.analytics[s] = Analytics(s, self.data_sources[s])
</code></pre>
<p>Right now, my solution is to have one <code>Data</code>-class and one <code>Analytics</code>-class which has <code>if</code>-statements to adapt the functionality of the class depending on the source. This is not a scalable or otherwise good solution, I basically have checks <strong>in both classes</strong> where I say</p>
<pre><code>acceptable_sources = ['a', 'b', 'c']
if source not in acceptable_sources:
raise ValueError(f"Only acceptable sources are: {acceptable_sources}")
</code></pre>
<p>Then, I need more checks to set the <code>self.variables</code> correctly, here's an example from the <code>Data</code>-class</p>
<pre><code>self.data = {}
if source == 'a': # if it's a, then there's 3 sources
self.data[a] = pd.read_excel('a_1.xlsx')
self.data[a] = pd.read_excel('a_2.xlsx')
self.data[a] = pd.read_excel('a_2.xlsx')
elif source == 'b': # if it's b, then there's 2 sources
self.data[a] = pd.read_excel('b_1.xlsx')
self.data[a] = pd.read_excel('b_2.xlsx')
</code></pre>
<p>This is problematic, since there will be a lot of <code>if</code>-statements as the number of sources increase, but it might be the best solution, I'm not sure. Using the same idea in my Analytics-class, there will be a lot of unused functions for each source-case. Let's say there are 30 functions for source <code>a</code>, 25 functions for source <code>b</code> and 40 functions for source <code>c</code>. Some of these functions might be shared across sources, and some will be unique. So whichever source I use, there will be a lot of unused methods which seems like a waste.</p>
<p>My first thought was to make <code>Analytics</code> and <code>Data</code> into abstract classes and create unique classes for each compatible source, but then I wouldn't be able to instantiate them in the <code>for</code>-loop in my main class. Then I thought that I could include them in a <code>Class_holder</code> which basically checks which class I want to instantiate, and if it exists to return an object of that class. So for example if I have X possible sources, the <code>Class_holder</code> would be able to handle and return X different classes, and if it doesn't exist return an error. It would look something like</p>
<pre><code>from analytics import A, B, C # classes I should create with correct methods
class Class_holder:
def __init__(self, source, data):
self.acceptable_sources = ['a', 'b', 'c']
if source in acceptable_sources:
raise ValueError(f"Only acceptable sources are: {acceptable_sources}")
self.source = source
self.data = data
def return_analytics_class(self):
if self.source == 'a':
return A(self.data)
elif self.source == 'b':
return B(self.data)
elif self.source == 'c':
return C(self.data)
</code></pre>
<p>And the classes I have called <code>A</code>, <code>B</code>, <code>C</code> could either be a combination of <code>Data</code> and <code>Analytics</code>, or I could separate it by having one <code>Data</code> and one <code>Analytics</code>-class for each source, then the <code>Class_holder.return_class()</code> would return a tuple with two classes. For the <code>Class_holder</code>-solution I would have to change my <code>Main</code> to something like</p>
<pre><code>from a_file import Data
from another_file import Class_holder
class Main_class():
def __init__(self, sources = ['a','b','c'])
self.data_sources = {}
for s in sources:
self.data_souces[s] = Data(s)
self.analytics = {}
for s in sources:
self.analytics[s] = Class_holder(s, self.data_sources[s]).return_analytics_class()
</code></pre>
<p>But then I'm back to my original problem, where I need to have checks in both <code>Data</code> and <code>Class_holder</code> to see if the sources are compatible, however this might solve the problem of only instantiating the correct analytics-functions for each source.</p>
<p>It just doesn't feel like an optimal way of doing this kind of task, so I'm turning to codereview to ask for a bit of guidance, if you know any design pattern or other solution for this kind of problem, I would greatly appreciate it.</p>
|
[] |
[
{
"body": "<p>Presuming that you are using Python 3.6 ore newer, I would use abstract base classes and use the <code>__init_subclass__()</code> method to automatically register new subclasses and the sources they handle. A classmethod on the baseclass can then look up the appropriate subclass based on the source.</p>\n<p>If the decision on which subclass to use is more complicated, each subclass can have a <code>can_you_handle(self, source)</code> method that returns True if is can handle the source. The base class <code>from_source()</code> method calls <code>can_you_handle()</code> on each subclass until it finds one that can handle the source.</p>\n<p>Here's a base class:</p>\n<pre><code>class Data:\n registry = {}\n \n def __init__(self, source):\n self.source = source\n\n \n def __init_subclass__(cls, **kwargs):\n for source in cls.sources:\n if source not in Data.registry:\n Data.registry[source] = cls\n \n else:\n other_cls = Data.registry[source].__name__\n message = f"class '{other_cls}' already registered for source '{source}'."\n raise ValueError(message)\n\n super().__init_subclass__(**kwargs)\n \n \n @classmethod\n def from_source(self, source):\n try:\n cls = Data.registry[source]\n return cls(source)\n \n except KeyError:\n raise ValueError(f"Unkown source: {source}") from None\n \n def __str__(self):\n return f"{type(self).__name__}('{self.source}')"\n</code></pre>\n<p>Some subclasses:</p>\n<pre><code>class Data_A(Data):\n sources = 'a','b'\n \n def method_for_source_A(self):\n print('doing something with Data_A')\n \nclass Data_C(Data):\n sources = 'c','d','e'\n\n def method_for_source_C(self):\n print('doing something with Data_C')\n</code></pre>\n<p>Check the registry was populated:</p>\n<pre><code>print(Data.registry)\n</code></pre>\n<p>prints:</p>\n<pre><code>{'a': __main__.Data_A, 'b': __main__.Data_A, 'c': __main__.Data_C,\n 'd': __main__.Data_C, 'e': __main__.Data_C}\n</code></pre>\n<p>Try it out:</p>\n<pre><code>data = Data.from_source('b')\nprint(f"{str(data)} using {data.source}")\n\ndata = Data.from_source('e')\nprint(f"{str(data)} using {data.source}")\n\ndata = Data.from_source('q')\nprint(f"{str(data)} using {data.source}")\n</code></pre>\n<p>prints:</p>\n<pre><code>Data_A('b') using b\nData_C('e') using e\n---------------------------------------------------------------------------\nValueError Traceback (most recent call last)\n<ipython-input-82-072d12d66274> in <module>\n 5 print(f"{str(data)} using {data.source}")\n 6 \n----> 7 data = Data.from_source('q')\n 8 print(f"{str(data)} using {data.source}")\n\n<ipython-input-70-bd84ab43455a> in from_source(self, source)\n 20 \n 21 except KeyError:\n---> 22 raise ValueError(f"Unkown source: {source}") from None\n 23 \n 24 def __str__(self):\n\nValueError: Unkown source: q\n</code></pre>\n<p>Try defining a subclass with a duplicated source:</p>\n<pre><code>class Data_F(Data):\n sources = 'f','e'\n\n def method_for_source_F(self):\n print('doing something with Data_F')\n</code></pre>\n<p>result:</p>\n<pre><code>---------------------------------------------------------------------------\nValueError Traceback (most recent call last)\n<ipython-input-124-39d1c8d7edf7> in <module>\n----> 1 class Data_F(Data):\n 2 sources = 'f','e'\n 3 \n 4 def method_for_source_F(self):\n 5 print('doing something with Data_F')\n\n<ipython-input-120-08031ccf6700> in __init_subclass__(cls, **kwargs)\n 14 other_cls = Data.registry[source].__name__\n 15 message = f"class '{other_cls}' already registered for source '{source}'."\n---> 16 raise ValueError(message) from None\n 17 \n 18 super().__init_subclass__(**kwargs)\n\nValueError: class 'Data_C' already registered for source 'e'.\n</code></pre>\n<p><code>class Analytics</code> would be handled in an analogous manner.</p>\n<p>Your main class would then look like this:</p>\n<pre><code>class Main_class():\n def __init__(self, sources = ['a','b','c']):\n self.data_sources = {}\n self.analytics = {}\n\n for s in sources:\n data = Data.from_source(s)\n self.data_sources[s] = data\n\n analytic = Analytics.from_source(s)\n self.analytics[s] = analytic(data)\n</code></pre>\n<p>One more thing, <code>__init_subclass__()</code> takes keyword arguments. So you could write the code above like this (I just prefer using class variables as shown above):</p>\n<pre><code> def __init_subclass__(cls, sources, **kwargs): # changed this line\n for source in sources: # and this one\n if source not in Data.registry:\n Data.registry[source] = cls\n \n else:\n other_cls = Data.registry[source].__name__\n message = f"class '{other_cls}' already registered for source '{source}'."\n raise ValueError(message)\n\n super().__init_subclass__(**kwargs)\n</code></pre>\n<p>And then the subclasses would look like this:</p>\n<pre><code>class Data_A(Data, sources=('a','b')): # source in now a keyword argument\n \n def method_for_source_A(self):\n print('doing something with Data_A')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T00:19:55.180",
"Id": "497980",
"Score": "0",
"body": "This is exactly what I was looking for, thank you so much for helping out! You've used a lot of things I haven't seen before, [this](https://stackoverflow.com/questions/12179271/meaning-of-classmethod-and-staticmethod-for-beginner/14605349#14605349) answer helped me understand some of it. I'll definitely study and use this, and I'll probably look into using more inheritance between classes, for example if classes B,C,D has 3 shared functions, maybe they could inherit from class A which has these functions predefined (assuming that classes A,B,C,D are all subclasses to Data)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T05:08:26.293",
"Id": "498003",
"Score": "1",
"body": "I was going to mention using \"mixins\" as a way to refactor common features from Data subclasses, but the answer was rather long already."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T08:48:14.400",
"Id": "498025",
"Score": "0",
"body": "Thanks for mentioning it atleast, I hadn't heard of mixins before so I'll definitely check it out. And if I have any questions I'll create a new ticket for it."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T21:36:56.903",
"Id": "252678",
"ParentId": "252645",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "252678",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T10:07:50.693",
"Id": "252645",
"Score": "3",
"Tags": [
"python",
"object-oriented",
"design-patterns"
],
"Title": "Design pattern for creating similar but different classes"
}
|
252645
|
<p>I wrote this code to speed up my daily work. I want to ask for help on how to further accelerate this code.</p>
<h3>Operation of the code</h3>
<p>It copies 1-1 worksheets from 3 different workbooks to 3 worksheets of the new workbook. Inserts, copies, and formats different columns. Then, by examining different criteria on a worksheet called "lista", type red 1s in specific cells or copy text.</p>
<h3>What I've done so far for speed up</h3>
<p>-Switching application functions on and off (like Application.ScreenUpdating)</p>
<p>-where it is possible using With - end with</p>
<p>-Delimitation of operation area with "lastrow".</p>
<p>-Usage vbNullString instead of ""</p>
<p>Get running the macro with a list of 180,000 lines takes 3-3.5 hours for done.</p>
<h3>Environmental parameters</h3>
<ul>
<li>Windows 10 Home</li>
<li>Intel Core i7-930 2.8Ghz</li>
<li>16GB RAM</li>
<li>516GB SSD</li>
<li>Excel 2013</li>
</ul>
<p>Do you see any opportunity to accelerate?</p>
<p>The entire code:</p>
<pre><code>Option Explicit
Sub Gyogyit()
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.EnableEvents = False
ActiveSheet.DisplayPageBreaks = False
Dim egyedilap, gyogylap, segedlap, listlap As Worksheet
Dim closedBook As Workbook
Dim listlastrow, gyogylastrow, listlastrow2, egyedilastrow As Long
Dim aoszl, Prob, kitolt, a, x, y, Z, v, w, af, dd, coutaj, egmunk, egmunk2, kozfog, kozfog2, j, nm, eufogl, eufogl2, vangyogy, vanegyedi, alap As Integer
Dim n As Date
Dim p, q, ag, ah, ak, an, ao, ap, aq, megbkim, apolh, korhdat, korhnev, imporsz, jarvaz, nevkod, jarvnev, betmk, betfog, kozfogl, kozfogl2, muhnev, munkhelygyogy, betmunkgyogy, betfoglszovgyogy, korhegyedi, megbkimegyed, korfelvegyed, kormegngyogy, korfeldatgyogy, apolhelygyogy, megbkimgyogy, apolhelyegyed As String
Dim StartTime As Double
Dim MinutesElapsed As String
Dim gyogyult, otthon As Boolean
StartTime = Timer
Set listlap = ThisWorkbook.Worksheets("lista")
Set gyogylap = ThisWorkbook.Worksheets("BE_gyogy")
Set segedlap = ThisWorkbook.Worksheets("segedlap")
Set egyedilap = ThisWorkbook.Worksheets("egyedi")
Application.DisplayAlerts = False
listlap.Range("I:K").Delete
Set closedBook = Workbooks.Open("C:\Users\tulaj\Documents\makróhozalap másolata\lista_okt-26.xlsx")
closedBook.Sheets(1).Range("A:AM").Copy listlap.Range("I:AU")
closedBook.Close SaveChanges:=False
Set closedBook = Workbooks.Open("C:\Users\tulaj\Documents\makróhozalap másolata\BE_gyogy.xlsx")
closedBook.Sheets(1).Range("A:DD").Copy gyogylap.Range("B:DF")
closedBook.Close SaveChanges:=False
Set closedBook = Workbooks.Open("C:\Users\tulaj\Documents\makróhozalap másolata\egyedi.xlsx")
closedBook.Sheets(1).Range("A:DY").Copy egyedilap.Range("B:DZ")
closedBook.Close SaveChanges:=False
Application.DisplayAlerts = True
With egyedilap
.Activate
.Range("E:E").Copy Range("A:A")
.Columns("A:A").NumberFormat = "0"
End With
With gyogylap
.Activate
.Range("I:I").Copy Range("A:A")
.Columns("A:A").NumberFormat = "0"
End With
gyogylastrow = gyogylap.Cells(Rows.Count, 1).End(xlUp).Row
egyedilastrow = egyedilap.Cells(Rows.Count, 1).End(xlUp).Row
With listlap
.Activate
.Columns("AG").Insert Shift:=xlToRight
.Range("AG1").Value = "Eü. fogl."
.Columns("AK").Insert Shift:=xlToRight
.Range("AK1").Value = "Import orsz."
.Columns("AO").Insert Shift:=xlToRight
.Range("AO1").Value = "Járvány neve"
.Range("AT:AT").Copy Range("A:A")
.Columns("A:A").NumberFormat = "0"
.Range("A1").Value = "TAJ"
.Columns("AS:AS").NumberFormat = "yyyy/mm/dd"
listlastrow = listlap.Cells(Rows.Count, 1).End(xlUp).Row
For x = 2 To listlastrow
If .Range("A" & x).Value = vbNullString Then
.Range("A" & x).Value = "nincs"
End If
Next x
For kitolt = 2 To listlastrow
On Error Resume Next
a = .Range("A" & kitolt)
n = .Range("N" & kitolt)
p = .Range("P" & kitolt)
q = .Range("Q" & kitolt)
x = .Range("X" & kitolt)
y = .Range("Y" & kitolt)
Z = .Range("Z" & kitolt)
v = .Range("V" & kitolt)
w = .Range("W" & kitolt)
j = .Range("J" & kitolt)
ag = .Range("AG" & kitolt)
ak = .Range("AK" & kitolt)
an = .Range("AN" & kitolt)
ao = .Range("AO" & kitolt)
With Application.WorksheetFunction
vangyogy = .CountIf(gyogylap.Range("A:A"), a)
vanegyedi = .CountIf(egyedilap.Range("A:A"), a)
korfeldatgyogy = .VLookup(a, gyogylap.Range("A2:CM" & gyogylastrow), 46, False)
kormegngyogy = .VLookup(a, gyogylap.Range("A2:CM" & gyogylastrow), 47, False)
korhegyedi = .VLookup(a, egyedilap.Range("A2:DZ" & egyedilastrow), 32, False)
korfelvegyed = .VLookup(a, egyedilap.Range("A2:DZ" & egyedilastrow), 33, False)
If vangyogy = 1 Then
megbkimgyogy = .VLookup(a, gyogylap.Range("A2:CM" & gyogylastrow), 49, False)
apolhelygyogy = .VLookup(a, gyogylap.Range("A2:CM" & gyogylastrow), 33, False)
Else
megbkimgyogy = vbNullString
apolhelygyogy = vbNullString
End If
If vanegyedi <> vbNullString Then
megbkimegyed = .VLookup(a, egyedilap.Range("A2:DZ" & egyedilastrow), 35, False)
apolhelyegyed = .VLookup(a, egyedilap.Range("A2:DZ" & egyedilastrow), 12, False)
Else
megbkimegyed = vbNullString
apolhelyegyed = vbNullString
End If
betfoglszovgyogy = .VLookup(a, gyogylap.Range("A2:CM" & gyogylastrow), 19, False)
eufogl = .CountIf(segedlap.Range("M:M"), betfoglszovgyogy)
betmunkgyogy = .VLookup(a, gyogylap.Range("A2:CM" & gyogylastrow), 20, False)
eufogl2 = .CountIf(segedlap.Range("M:M"), betmunkgyogy)
munkhelygyogy = .VLookup(a, gyogylap.Range("A2:CM" & gyogylastrow), 21, False)
kozfogl = .CountIf(segedlap.Range("K:K"), betmunkgyogy)
kozfogl2 = .CountIf(segedlap.Range("K:K"), betfoglszovgyogy)
nevkod = .VLookup(a, gyogylap.Range("A2:CM" & gyogylastrow), 11, False)
otthon = ((apolhelygyogy = "Otthon" And vanegyedi <> 1) Or _
(apolhelygyogy = vbNullString And vanegyedi = 1 And apolhelyegyed = "Otthon") Or _
(apolhelygyogy = "Otthon" And vanegyedi = 1 And apolhelyegyed = "Otthon"))
gyogyult = ((megbkimgyogy = "Gyógyult" And vanegyedi <> 1) Or _
(megbkimegyed = "gyógyult" And vanegyedi = 1 And megbkimgyogy = vbNullString) Or _
(megbkimegyed = "gyógyult" And vanegyedi = 1 And megbkimgyogy = "Gyógyult"))
End With
If a <> vbNullString And a <> 0 And a <> "nincs" Then
If q = vbNullString And _
v = vbNullString And _
w = vbNullString And _
x = vbNullString And _
Z = vbNullString And _
korfeldatgyogy = vbNullString And _
kormegngyogy = vbNullString And _
korhegyedi = vbNullString And _
korfelvegyed = vbNullString And _
nevkod <> "comtu001" And _
nevkod <> "voviv001" And _
nevkod <> "rocal006" Then
alap = 1
'Debug.Print alap
If p = vbNullString And _
(vangyogy = 1 Or vanegyedi = 1) = True And _
alap = 1 And _
otthon = True Then
.Range("P" & kitolt).Value = 1
.Range("P" & kitolt).Font.Color = RGB(210, 65, 65)
End If
If y = vbNullString And _
(vangyogy = 1 Or vanegyedi = 1) = True And _
j < 64 And _
Date - n > 13 And _
p = 1 And _
gyogyult = True Then
.Range("Y" & kitolt).Value = 1
.Range("Y" & kitolt).Font.Color = RGB(210, 65, 65)
End If
alap = 0
End If
'Debug.Print kitolt '& " " & alap & " " & vangyogy & " " & vanegyedi & " " & otthon & " " & gyogyult & " " & megbkimgyogy & " " & megbkimegyed
End If
If ak = vbNullString Then
.Range("AK" & kitolt).Value = Application.WorksheetFunction.VLookup(a, gyogylap.Range("A2:CM" & gyogylastrow), 54, False)
.Range("AK" & kitolt).Font.Color = RGB(210, 65, 65)
End If
If an = vbNullString Then
.Range("AN" & kitolt).Value = Application.WorksheetFunction.VLookup(a, gyogylap.Range("A2:CM" & gyogylastrow), 87, False)
.Range("AN" & kitolt).Font.Color = RGB(210, 65, 65)
End If
If ao = vbNullString Then
.Range("AO" & kitolt).Value = Application.WorksheetFunction.VLookup(a, gyogylap.Range("A2:CM" & gyogylastrow), 88, False)
.Range("AO" & kitolt).Font.Color = RGB(210, 65, 65)
End If
If ag = vbNullString Then
If eufogl = 1 Then
.Range("AG" & kitolt).Value = betmunkgyogy
.Range("AH" & kitolt).Value = munkhelygyogy
.Range("AF" & kitolt).Value = 1
.Range("AG" & kitolt).Font.Color = RGB(210, 65, 65)
.Range("AH" & kitolt).Font.Color = RGB(210, 65, 65)
.Range("AF" & kitolt).Font.Color = RGB(210, 65, 65)
ElseIf eufogl2 = 1 And a <> vbNullString And a <> "0" And a <> "nincs" Then
.Range("AG" & kitolt).Value = betfoglszovgyogy
.Range("AH" & kitolt).Value = munkhelygyogy
.Range("AF" & kitolt).Value = 1
.Range("AG" & kitolt).Font.Color = RGB(210, 65, 65)
.Range("AH" & kitolt).Font.Color = RGB(210, 65, 65)
.Range("AF" & kitolt).Font.Color = RGB(210, 65, 65)
End If
End If
If aq = vbNullString Then
If kozfogl = 1 Then
.Range("AQ" & kitolt).Value = betmunkgyogy
.Range("AP" & kitolt).Value = munkhelygyogy
.Range("AQ" & kitolt).Font.Color = RGB(210, 65, 65)
.Range("AP" & kitolt).Font.Color = RGB(210, 65, 65)
ElseIf kozfogl2 = 1 And a <> vbNullString And a <> "0" And a <> "nincs" Then
.Range("AQ" & kitolt).Value = betfoglszovgyogy
.Range("AP" & kitolt).Value = munkhelygyogy
.Range("AQ" & kitolt).Font.Color = RGB(210, 65, 65)
.Range("AP" & kitolt).Font.Color = RGB(210, 65, 65)
End If
End If
Next kitolt
Range("H2").Select
ActiveCell.FormulaR1C1 = "=COUNTIF(C[+7],RC[+7])"
Range("E2").Select
ActiveCell.FormulaR1C1 = "=CONCATENATE(RC[39],RC[40])"
End With
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayStatusBar = True
Application.EnableEvents = True
ActiveSheet.DisplayPageBreaks = True
MinutesElapsed = format((Timer - StartTime) / 86400, "hh:mm:ss")
MsgBox "This code ran successfully in " & MinutesElapsed & " minutes", vbInformation
End Sub
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T13:34:02.680",
"Id": "497894",
"Score": "1",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T13:58:39.850",
"Id": "497895",
"Score": "1",
"body": "Thank you Mast! I revised the title."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T22:49:15.230",
"Id": "497972",
"Score": "0",
"body": "@BCdotWEB thank you! Title revised."
}
] |
[
{
"body": "<p>One improvement to consider is reducing the number of <code>VLookup</code> calls and the multiple creations of identical <code>Ranges</code>. Create the evaluation <code>Ranges</code> outside of the loop (they do not change per loop) and then find the row of interest only once per loop using <code>Match</code>. Assign all of your variables based on the row value. This substantially reduces the number of <code>Ranges</code> created and <code>VLookup</code>/<code>Match</code> calls. I've added new code and commented out the lines that they replace inside the <code>With Application.WorksheetFunction</code> block.</p>\n<pre><code> 'Create the evaluation ranges once - outside of the loop\n Dim gyogylapRange As Range\n Set gyogylapRange = gyogylap.Range("A1:CM" & gyogylastrow)\n\n Dim egyedilapRange As Range\n Set egyedilapRange = egyedilap.Range("A1:DZ" & egyedilastrow)\n \n 'Create the ranges for detecting the two rows of interest per loop\n Dim gyogylapRowDetectionRange As Range\n Set gyogylapRowDetectionRange = gyogylap.Range("A:A")\n\n Dim egyedilapRowDetectionRange As Range\n Set egyedilapRowDetectionRange = egyedilap.Range("A:A")\n \n For kitolt = 2 To listlastrow\n On Error Resume Next\n\n ...\n\n With Application.WorksheetFunction\n Dim rowFoundIn As Long\n \n vangyogy = .CountIf(gyogylapRowDetectionRange, a)\n rowFoundIn = .Match(a, gyogylapRowDetectionRange , 0)\n\n korfeldatgyogy = gyogylap.Cells(rowFoundIn, 46)\n kormegngyogy = gyogylap.Cells(rowFoundIn, 47)\n betfoglszovgyogy = gyogylap.Cells(rowFoundIn, 19)\n betmunkgyogy = gyogylap.Cells(rowFoundIn, 20)\n munkhelygyogy = gyogylap.Cells(rowFoundIn, 21)\n nevkod = gyogylap.Cells(rowFoundIn, 11)\n If vangyogy = 1 Then\n megbkimgyogy = gyogylap.Cells(rowFoundIn, 49)\n apolhelygyogy = gyogylap.Cells(rowFoundIn, 33)\n Else\n megbkimgyogy = vbNullString\n apolhelygyogy = vbNullString\n End If\n \n vanegyedi = .CountIf(egyedilapRowDetectionRange , a)\n\n rowFoundIn = .Match(a, egyedilapRowDetectionRange , 0)\n korhegyedi = egyedilap.Cells(rowFoundIn, 32)\n korfelvegyed = egyedilap.Cells(rowFoundIn, 33)\n If vanegyedi <> vbNullString Then\n megbkimegyed = egyedilap.Cells(rowFoundIn, 35)\n apolhelyegyed = egyedilap.Cells(rowFoundIn, 12)\n Else\n megbkimegyed = vbNullString\n apolhelyegyed = vbNullString\n End If\n \n ' vangyogy = .CountIf(gyogylap.Range("A:A"), a)\n ' vanegyedi = .CountIf(egyedilap.Range("A:A"), a)\n ' korfeldatgyogy = .VLookup(a, gyogylap.Range("A2:CM" & gyogylastrow), 46, False)\n ' kormegngyogy = .VLookup(a, gyogylap.Range("A2:CM" & gyogylastrow), 47, False)\n ' korhegyedi = .VLookup(a, egyedilap.Range("A2:DZ" & egyedilastrow), 32, False)\n ' korfelvegyed = .VLookup(a, egyedilap.Range("A2:DZ" & egyedilastrow), 33, False)\n ' If vangyogy = 1 Then\n ' megbkimgyogy = .VLookup(a, gyogylap.Range("A2:CM" & gyogylastrow), 49, False)\n ' apolhelygyogy = .VLookup(a, gyogylap.Range("A2:CM" & gyogylastrow), 33, False)\n ' Else\n ' megbkimgyogy = vbNullString\n ' apolhelygyogy = vbNullString\n ' End If\n ' If vanegyedi <> vbNullString Then\n ' megbkimegyed = .VLookup(a, egyedilap.Range("A2:DZ" & egyedilastrow), 35, False)\n ' apolhelyegyed = .VLookup(a, egyedilap.Range("A2:DZ" & egyedilastrow), 12, False)\n ' Else\n ' megbkimegyed = vbNullString\n ' apolhelyegyed = vbNullString\n ' End If\n ' betfoglszovgyogy = .VLookup(a, gyogylap.Range("A2:CM" & gyogylastrow), 19, False)\n eufogl = .CountIf(segedlap.Range("M:M"), betfoglszovgyogy)\n ' betmunkgyogy = .VLookup(a, gyogylap.Range("A2:CM" & gyogylastrow), 20, False)\n eufogl2 = .CountIf(segedlap.Range("M:M"), betmunkgyogy)\n ' munkhelygyogy = .VLookup(a, gyogylap.Range("A2:CM" & gyogylastrow), 21, False)\n kozfogl = .CountIf(segedlap.Range("K:K"), betmunkgyogy)\n kozfogl2 = .CountIf(segedlap.Range("K:K"), betfoglszovgyogy)\n ' nevkod = .VLookup(a, gyogylap.Range("A2:CM" & gyogylastrow), 11, False)\n otthon = ((apolhelygyogy = "Otthon" And vanegyedi <> 1) Or _\n (apolhelygyogy = vbNullString And vanegyedi = 1 And apolhelyegyed = "Otthon") Or _\n (apolhelygyogy = "Otthon" And vanegyedi = 1 And apolhelyegyed = "Otthon"))\n gyogyult = ((megbkimgyogy = "Gyógyult" And vanegyedi <> 1) Or _\n (megbkimegyed = "gyógyult" And vanegyedi = 1 And megbkimgyogy = vbNullString) Or _\n (megbkimegyed = "gyógyult" And vanegyedi = 1 And megbkimgyogy = "Gyógyult"))\n End With\n\n ...\n\n Next kitolt\n</code></pre>\n<p>Some other comments for you to consider. Most of these comments/changes are not focused on efficiency as much as maintainability and readability.</p>\n<p>There are a a number of coding practices that will make your code easier to read, understand, and maintain. In this case, the two most important would be the <em>Single Responsibility Principle</em> (SRP) and <em>Don't Repeat Yourself</em> (<a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a>). SRP is the 'S' in <a href=\"https://en.wikipedia.org/wiki/SOLID\" rel=\"nofollow noreferrer\">SOLID</a> coding practices and will improve the structure and reliability of your code dramatically. SRP encourages the use of small modules and methods focused on a single purpose.</p>\n<p>SRP</p>\n<p>In the code above, <code>Sub Gyogyit()</code> contains every responsibility for the tasks that it performs. To be fair, getting code organized in groups of single responsibilities is difficut to achieve. Especially in early versions. So, starting from the current implementation, it is easier to think of SRP as simply meaning <em>divide and conquer</em>. So, evaluate what are the biggest chunks of code that can be removed from <code>Gyogyit</code> and placed in their own dedicated subroutine or function.</p>\n<p>The first thing done by <code>Gyogyit</code> is to turn off a number of flags to improve speed. And, these flags <em>always</em> need to be turned back 'on' before the the subroutine exits. Managing these flags is one of the responsibilities of <code>Gyogyit</code>. I would recommend making this the only responsibility of <code>Gyogyit</code> so that it is clear that the flags are toggled before and after the operations.</p>\n<pre><code> Sub Gyogit()\n\n On Error GoTo ErrorExit\n\n Application.Calculation = xlCalculationManual\n Application.ScreenUpdating = False\n Application.DisplayStatusBar = False\n Application.EnableEvents = False\n ActiveSheet.DisplayPageBreaks = False\n\n Gyogyit2 'the remainder of the code\n\n ErrorExit:\n Application.Calculation = xlCalculationAutomatic\n Application.ScreenUpdating = True\n Application.DisplayStatusBar = True\n Application.EnableEvents = True\n ActiveSheet.DisplayPageBreaks = True\n\n End Sub\n</code></pre>\n<p>Now the reader doesn't have to scroll the entire length of the module to know that the flags are all reset. If you ever add or remove another flag, it is obvious where to introduce it.</p>\n<p>You mention using <code>With</code> statements to speed up the process. As far as I know, <code>With</code> statements will not change the execution speed of the code. They assist in avoiding repetitous qualifying expressions. They certainly have a place in the DRY coding practice. Because <code>Gyogyit2</code> is such a long subroutine, the <code>With</code> statements reduce clarity because they span so many lines. <code>With listalap</code> and its associated <code>End With</code> are 177 lines apart. From a purely readability perspective, it is best to use a <code>With</code> statement in such a way that is easy to see the start and finish without scrolling so many lines. So, to keep the <code>With listalap</code> statement it is possible to refactor the 177 to procedure calls in order to significantly reduce the length.</p>\n<p>First: the content of the loop is 130 lines. Moving the content of the loop to its own subroutine will be a big improvement. This yields:</p>\n<pre><code> With listlap\n .Activate\n .Columns("AG").Insert Shift:=xlToRight\n .Range("AG1").Value = "Eü. fogl."\n .Columns("AK").Insert Shift:=xlToRight\n .Range("AK1").Value = "Import orsz."\n .Columns("AO").Insert Shift:=xlToRight\n .Range("AO1").Value = "Járvány neve"\n .Range("AT:AT").Copy Range("A:A")\n .Columns("A:A").NumberFormat = "0"\n .Range("A1").Value = "TAJ"\n .Columns("AS:AS").NumberFormat = "yyyy/mm/dd"\n \n listlastrow = listlap.Cells(Rows.Count, 1).End(xlUp).row\n Dim x As Long\n For x = 2 To listlastrow\n If .Range("A" & x).Value = vbNullString Then\n .Range("A" & x).Value = "nincs"\n End If\n Next x\n End With\n \n Dim kitolt As Long\n For kitolt = 2 To listlastrow\n KitoltLoop listlap, kitolt, gyogylap.Range("A2:CM" & gyogylastrow), egyedilap.Range("A2:DZ" & egyedilastrow)\n Next kitolt\n</code></pre>\n<p>The <code>With</code> statement is now only 22 lines and it can be 'seen' without scrolling. Also, note that the loop no longer needs to be within the <code>With</code> statement. And, the purpose of the <code>With</code> statement becomes very clear - it is used to simplify the expressions that initialize/prepare the <code>listlap</code> worksheet.</p>\n<p>This now leaves the 130 line <code>KitlotLoop</code> subroutine:\nNesting: Nested <code>If</code> and <code>With</code> statements make readability more difficult. In general, I might suggest that as soon as you have to nest beyond the second level, it is time to consider a different organization of logic. So, first step within the loop is to reduce nesting. Second, I would attempt to make the <em>VERY</em> long <code>Boolean</code> expressions into functions that return a <code>Boolean</code> - and give those functions a name that represents what it 'is' that you are evaluating. There are also numerous expressions that are different only by one 'thing'. These are candidates for simplifying by replacing them with a procedure and is consistent with the DRY coding practice.</p>\n<p>In situations where there are numerous related variables there is a better way to organize them. By defining <code>UserDefinedTypes</code>, the variables can be organized and moved as a group rather than individually. Organizing the variable this way helps to make procedure parameter lists more manageable.</p>\n<p>So, applying all the above suggestion, the following is an alternative implementation of the code. Just by making all procedures 'smaller', there is progress to the goal of SRP. Also note that the wall of variables has disappeared as they are declared within the <code>UserDefinedTypes</code> or within supporting procedures. There is certainly more that can be done.</p>\n<pre><code> Option Explicit\n\n Private Type ImportantCells\n a As String\n p As String\n q As String\n v As String\n w As String\n x As String\n y As String\n z As String\n ag As String\n ak As String\n an As String\n ao As String\n aq As String\n End Type\n\n Private Type ImportantRowData\n korfeldatgyogy As String\n kormegngyogy As String\n korhegyedi As String\n korfelvegyed As String\n megbkimegyed As String\n apolhelyegyed As String\n apolhelygyogy As String\n megbkimgyogy As String\n betfoglszovgyogy As String\n eufogl As String\n betmunkgyogy As String\n eufogl2 As String\n munkhelygyogy As String\n kozfogl As String\n kozfogl2 As String\n nevkod As String\n otthon As Boolean\n gyogyult As Boolean\n End Type\n\n Private Type WorksheetAttributes\n wksht As Worksheet\n evalRange As Range\n rowDetectRange As Range\n lastRow As Long\n End Type\n\n Private ColoredCellColor As Long\n\n Sub Gyogit()\n\n Dim StartTime As Double\n Dim MinutesElapsed As String\n\n StartTime = Timer\n ColoredCellColor = RGB(210, 65, 65)\n\n On Error GoTo ErrorExit\n\n Application.Calculation = xlCalculationManual\n Application.ScreenUpdating = False\n Application.DisplayStatusBar = False\n Application.EnableEvents = False\n ActiveSheet.DisplayPageBreaks = False\n\n Gyogyit2\n\n ErrorExit:\n\n Application.Calculation = xlCalculationAutomatic\n Application.ScreenUpdating = True\n Application.DisplayStatusBar = True\n Application.EnableEvents = True\n ActiveSheet.DisplayPageBreaks = True\n \n MinutesElapsed = Format((Timer - StartTime) / 86400, "hh:mm:ss")\n MsgBox "This code ran successfully in " & MinutesElapsed & " minutes", vbInformation\n End Sub\n\n Private Sub Gyogyit2()\n\n Dim listlastrow As Long\n Dim listlap As Worksheet\n Dim segedlap As Worksheet\n Dim gyogylastrow, listlastrow2, egyedilastrow As Long\n \n Set listlap = ThisWorkbook.Worksheets("lista")\n Set segedlap = ThisWorkbook.Worksheets("segedlap")\n \n Dim gyogylapAttributes As WorksheetAttributes\n gyogylapAttributes.wksht = ThisWorkbook.Worksheets("BE_gyogy")\n \n Dim egyedilapAttributes As WorksheetAttributes\n egyedilapAttributes.wksht = ThisWorkbook.Worksheets("egyedi")\n \n CopyWorkbooks listlap, gyogylapAttributes, egyedilapAttributes\n \n With egyedilapAttributes.wksht\n .Activate\n .Range("E:E").Copy Range("A:A")\n .Columns("A:A").NumberFormat = "0"\n End With\n \n With gyogylapAttributes.wksht\n .Activate\n .Range("I:I").Copy Range("A:A")\n .Columns("A:A").NumberFormat = "0"\n End With\n \n gyogylapAttributes.lastRow = gyogylapAttributes.wksht.Cells(Rows.Count, 1).End(xlUp).row\n egyedilapAttributes.lastRow = egyedilapAttributes.wksht.Cells(Rows.Count, 1).End(xlUp).row\n \n listlastrow = listlap.Cells(Rows.Count, 1).End(xlUp).row\n \n InitializeListlap listlap, listlastrow\n\n Set gyogylapAttributes.evalRange = gyogylapAttributes.wksht.Range("A1:CM" & gyogylastrow)\n\n Set egyedilapAttributes.evalRange = egyedilapAttributes.wksht.Range("A1:DZ" & egyedilastrow)\n \n Set gyogylapAttributes.rowDetectRange = gyogylapAttributes.wksht.Range("A:A")\n\n Set egyedilapAttributes.rowDetectRange = egyedilapAttributes.wksht.Range("A:A")\n \n Dim kitolt As Long\n For kitolt = 2 To listlastrow\n KitoltEvaluation listlap, segedlap, kitolt, gyogylapAttributes, egyedilapAttributes 'gyogylapRange, egyedilapRange, gyogylapRowDetectionRange, egyedilapRowDetectionRange\n Next kitolt\n \n Range("H2").Select\n ActiveCell.FormulaR1C1 = "=COUNTIF(C[+7],RC[+7])"\n Range("E2").Select\n ActiveCell.FormulaR1C1 = "=CONCATENATE(RC[39],RC[40])"\n End Sub\n\n Private Sub KitoltEvaluation(ByRef listlap As Worksheet, ByRef segedlap As Worksheet, ByVal kitolt As Long, _\n gyogylapAttributes As WorksheetAttributes, egyedilapAttributes As WorksheetAttributes)\n\n Dim vangyogy As Long\n Dim vanegyedi As Long\n \n On Error Resume Next\n\n Dim keyCell As ImportantCells\n keyCell = SetKeyCellValues(listlap, kitolt)\n \n Dim keyData As ImportantRowData\n \n Dim gyogylapRow As Long\n Dim egyedilapRow As Long\n \n With Application.WorksheetFunction\n vangyogy = .CountIf(gyogylapAttributes.rowDetectRange, keyCell.a)\n gyogylapRow = .Match(keyCell.a, gyogylapAttributes.rowDetectRange, 0)\n vanegyedi = .CountIf(egyedilapAttributes.rowDetectRange, keyCell.a)\n egyedilapRow = .Match(keyCell.a, egyedilapAttributes.rowDetectRange, 0)\n End With\n \n SetKeyDataValues listlap, segedlap, keyData, gyogylapAttributes.wksht, gyogylapRow, vangyogy, egyedilapAttributes.wksht, egyedilapRow, vanegyedi\n \n FormatAndAssignCells listlap, gyogylapAttributes, keyData, keyCell, gyogylapRow, kitolt, vangyogy, vanegyedi\n \n End Sub\n\n Private Function SetKeyDataValues(ByRef listlap As Worksheet, ByRef segedlap As Worksheet, keyData As ImportantRowData, _\n gyogylap As Range, gyoglapRow As Long, vangyogy As Long, _\n egyedilap As Range, egyedilapRow As Long, vanegyedi As Long) As ImportantRowData\n \n keyData.korfeldatgyogy = gyogylap.Cells(gyoglapRow, 46)\n keyData.kormegngyogy = gyogylap.Cells(gyoglapRow, 47)\n keyData.betfoglszovgyogy = gyogylap.Cells(gyoglapRow, 19)\n keyData.betmunkgyogy = gyogylap.Cells(gyoglapRow, 20)\n keyData.munkhelygyogy = gyogylap.Cells(gyoglapRow, 21)\n keyData.nevkod = gyogylap.Cells(gyoglapRow, 11)\n If vangyogy = 1 Then\n keyData.megbkimgyogy = gyogylap.Cells(gyoglapRow, 49)\n keyData.apolhelygyogy = gyogylap.Cells(gyoglapRow, 33)\n Else\n keyData.megbkimgyogy = vbNullString\n keyData.apolhelygyogy = vbNullString\n End If\n \n keyData.korhegyedi = egyedilap.Cells(egyedilapRow, 32)\n keyData.korfelvegyed = egyedilap.Cells(egyedilapRow, 33)\n If vanegyedi <> vbNullString Then\n keyData.megbkimegyed = egyedilap.Cells(egyedilapRow, 35)\n keyData.apolhelyegyed = egyedilap.Cells(egyedilapRow, 12)\n Else\n keyData.megbkimegyed = vbNullString\n keyData.apolhelyegyed = vbNullString\n End If\n \n With Application.WorksheetFunction\n keyData.eufogl = .CountIf(segedlap.Range("M:M"), keyData.betfoglszovgyogy)\n keyData.eufogl2 = .CountIf(segedlap.Range("M:M"), keyData.betmunkgyogy)\n keyData.kozfogl = .CountIf(segedlap.Range("K:K"), keyData.betmunkgyogy)\n keyData.kozfogl2 = .CountIf(segedlap.Range("K:K"), keyData.betfoglszovgyogy)\n End With\n \n keyData.otthon = Evaluation3(keyData.apolhelygyogy, vanegyedi, "Otthon")\n \n keyData.gyogyult = Evaluation3(keyData.megbkimgyogy, vanegyedi, "Gyógyult")\n End Function\n\n Private Sub FormatAndAssignCells(ByRef listlap As Worksheet, ByRef gyogylapAttributes As WorksheetAttributes, keyData As ImportantRowData, keyCell As ImportantCells, gyogylapRow As Long, ByVal kitolt As Long, _\n vangyogy As Long, vanegyedi As Long)\n \n Dim alap As Long\n If Evaluation2(keyCell.a) Then\n If AllVbNullString(keyCell.q, keyCell.v, keyCell.w, keyCell.x, keyCell.z, _\n keyData.korfeldatgyogy, keyData.kormegngyogy, keyData.korhegyedi) And _\n keyData.nevkod <> "comtu001" And _\n keyData.nevkod <> "comtu001" And _\n keyData.nevkod <> "voviv001" And _\n keyData.nevkod <> "rocal006" Then\n \n FormatP listlap, kitolt, keyCell, vangyogy = 1 Or vanegyedi = 1, keyData, alap\n \n FormatY listlap, kitolt, keyCell, vangyogy = 1 Or vanegyedi = 1, keyData\n \n End If\n End If\n \n With listlap\n If keyCell.ak = vbNullString Then\n SetValueAndColor .Range("AK" & kitolt), gyogylapAttributes.evalRange.Cells(gyogylapRow, 54)\n End If\n \n If keyCell.an = vbNullString Then\n SetValueAndColor .Range("AN" & kitolt), gyogylapAttributes.evalRange.Cells(gyogylapRow, 87)\n End If\n \n If keyCell.ao = vbNullString Then\n SetValueAndColor .Range("AO" & kitolt), gyogylapAttributes.evalRange.Cells(gyogylapRow, 88)\n End If\n \n If keyCell.ag = vbNullString Then\n If keyData.eufogl = 1 Then\n SetValueAndColor .Range("AG" & kitolt), keyData.betmunkgyogy\n SetValueAndColor .Range("AH" & kitolt), keyData.munkhelygyogy\n SetValueAndColor .Range("AF" & kitolt), 1\n ElseIf keyData.eufogl2 = 1 And Evaluation2(keyCell.a) Then\n SetValueAndColor .Range("AG" & kitolt), keyData.betfoglszovgyogy\n SetValueAndColor .Range("AH" & kitolt), keyData.munkhelygyogy\n SetValueAndColor .Range("AF" & kitolt), 1\n End If\n End If\n \n If keyCell.aq = vbNullString Then 'Note: aq was never assigned in the original code so thi always evaluated as True\n If keyData.kozfogl = 1 Then\n SetValueAndColor .Range("AQ" & kitolt), keyData.betmunkgyogy\n SetValueAndColor .Range("AP" & kitolt), keyData.munkhelygyogy\n ElseIf keyData.kozfogl2 = 1 And Evaluation2(keyCell.a) Then\n SetValueAndColor .Range("AQ" & kitolt), keyData.betfoglszovgyogy\n SetValueAndColor .Range("AP" & kitolt), keyData.munkhelygyogy\n End If\n End If\n End With\n End Sub\n\n Private Function SetKeyCellValues(ByRef listlap As Worksheet, ByVal kitolt As Long) As ImportantCells\n Dim keyCell As ImportantCells\n With listlap\n keyCell.a = .Range("A" & kitolt)\n keyCell.p = .Range("P" & kitolt)\n keyCell.q = .Range("Q" & kitolt)\n keyCell.x = .Range("X" & kitolt)\n keyCell.y = .Range("Y" & kitolt)\n keyCell.z = .Range("Z" & kitolt)\n keyCell.v = .Range("V" & kitolt)\n keyCell.w = .Range("W" & kitolt)\n keyCell.ag = .Range("AG" & kitolt)\n keyCell.ak = .Range("AK" & kitolt)\n keyCell.an = .Range("AN" & kitolt)\n keyCell.ao = .Range("AO" & kitolt)\n keyCell.aq = .Range("AQ" & kitolt) 'Note: aq was never assigned in the original code\n End With\n \n SetKeyCellValues = keyCell\n End Function\n \n Private Sub SetValueAndColor(rangeOfInterest As Range, theValue As Variant)\n rangeOfInterest.Value = theValue\n rangeOfInterest.Font.Color = ColoredCellColor\n End Sub\n \n Private Function AllVbNullString(ParamArray candidates() As Variant) As Boolean\n \n Dim allAreNull As Boolean\n allAreNull = True\n \n Dim candidate As Variant\n For Each candidate In candidates\n If Not candidate = vbNullString Then\n allAreNull = False\n End If\n Next candidate\n \n AllVbNullString = allAreNull\n\n End Function\n\n Private Sub InitializeListlap(ByRef listlap As Worksheet, listlastrow As Long)\n\n With listlap\n .Activate\n .Columns("AG").Insert Shift:=xlToRight\n .Range("AG1").Value = "Eü. fogl."\n .Columns("AK").Insert Shift:=xlToRight\n .Range("AK1").Value = "Import orsz."\n .Columns("AO").Insert Shift:=xlToRight\n .Range("AO1").Value = "Járvány neve"\n .Range("AT:AT").Copy Range("A:A")\n .Columns("A:A").NumberFormat = "0"\n .Range("A1").Value = "TAJ"\n .Columns("AS:AS").NumberFormat = "yyyy/mm/dd"\n \n Dim x As Long\n For x = 2 To listlastrow\n If .Range("A" & x).Value = vbNullString Then\n .Range("A" & x).Value = "nincs"\n End If\n Next x\n End With\n\n End Sub\n\n Private Sub FormatP(ByRef listlap As Worksheet, ByVal kitolt As Long, ByRef kCell As ImportantCells, _\n ByVal eval4Result As Boolean, ByRef kData As ImportantRowData, ByRef alap As Long)\n \n alap = 1\n If kCell.p = vbNullString And _\n eval4Result And _\n alap = 1 And _\n kData.otthon = True Then\n \n SetValueAndColor listlap.Range("P" & kitolt), 1\n End If\n alap = 0\n \n End Sub\n\n Private Sub FormatY(ByRef listlap As Worksheet, ByVal kitolt As Long, ByRef kCell As ImportantCells, _\n ByVal eval4Result As Boolean, ByRef kData As ImportantRowData)\n \n With listlap\n If kCell.y = vbNullString And _\n eval4Result And _\n .Range("J" & kitolt) < 64 And _\n Date - .Range("N" & kitolt) > 13 And _\n kCell.p = 1 And _\n kData.gyogyult = True Then\n \n SetValueAndColor .Range("Y" & kitolt), 1\n End If\n End With\n \n End Sub\n\n Private Function Evaluation2(a As String) As Boolean\n Evaluation2 = a <> vbNullString And a <> "0" And a <> "nincs"\n End Function\n\n Private Function Evaluation3(toCompare As String, countFound As Long, target As String) As Boolean\n Evaluation3 = ((toCompare = target And countFound <> 1) Or _\n (toCompare = vbNullString And countFound = 1 And toCompare = target) Or _\n (toCompare = target And countFound = 1 And toCompare = target))\n End Function\n\n Private Sub CopyWorkbooks(ByRef listlap As Worksheet, gyogylapAttributes As WorksheetAttributes, egyedilapAttributes As WorksheetAttributes)\n \n Dim closedBook As Workbook\n \n Application.DisplayAlerts = False\n On Error GoTo ErrorExit\n listlap.Range("I:K").Delete\n\n Set closedBook = Workbooks.Open("C:\\Users\\tulaj\\Documents\\makróhozalap másolata\\lista_okt-26.xlsx")\n closedBook.Sheets(1).Range("A:AM").Copy listlap.Range("I:AU")\n closedBook.Close SaveChanges:=False\n Set closedBook = Workbooks.Open("C:\\Users\\tulaj\\Documents\\makróhozalap másolata\\BE_gyogy.xlsx")\n closedBook.Sheets(1).Range("A:DD").Copy gyogylapAttributes.wksht.Range("B:DF")\n closedBook.Close SaveChanges:=False\n Set closedBook = Workbooks.Open("C:\\Users\\tulaj\\Documents\\makróhozalap másolata\\egyedi.xlsx")\n closedBook.Sheets(1).Range("A:DY").Copy egyedilapAttributes.wksht.Range("B:DZ")\n closedBook.Close SaveChanges:=False\n \n ErrorExit:\n Application.DisplayAlerts = True\n\n End Sub\n</code></pre>\n<p>The above code compiles, but only serves as an example of how the program data organization and functions <em>could</em> be done. The code would likely fail if ran against 'real' data as I have no way of replicating your actual data environment to test it. Hope you found this helpful and useful.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-02T04:07:25.040",
"Id": "498518",
"Score": "0",
"body": "A `With` clause can contribute to (minor) performance improvements because the properties of the object are only \"read\" once. As an example, using `Sheets(1).Range(\"A1\") = \"xx\"; Sheets(1).Range(\"A2\") = \"yy\"` forces VBA to re-read the `Sheets(1)` object twice. Refactoring to use `With Sheets(1); .Range(\"A1\") = \"xx\"; .Range(\"A2\") = \"yy\"; End With` will only access the `Sheets(1)` object once. See [this reference (#5)](https://techcommunity.microsoft.com/t5/excel/9-quick-tips-to-improve-your-vba-macro-performance/m-p/173687) for more information."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T23:14:18.683",
"Id": "252683",
"ParentId": "252647",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T11:13:44.680",
"Id": "252647",
"Score": "2",
"Tags": [
"performance",
"vba",
"excel"
],
"Title": "Different worksheets data comparison VBA is it possible without Application.WorksheetFunction.Vlookup?"
}
|
252647
|
<p>It should return <code>true</code>, if there is no element that follow or the following elements are greater than their predecessors.</p>
<pre><code>public class Element {
private int value;
private Element next;
public boolean isSorted(){
if (this.next == null)
return true;
else return (this.value < this.next.value && this.next.isSorted());
}
}
</code></pre>
<p>What do you guys think of it?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T15:37:44.583",
"Id": "497903",
"Score": "1",
"body": "It's hard to review without seeing the rest of the class. For instance, we can't see the declaration of `this.next` and `this.value` with what you've shown. It's hard to see why you're explicitly writing `this.` when accessing members, too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T15:39:42.663",
"Id": "497905",
"Score": "1",
"body": "Why not simply `public boolean isSorted() { return next == null || value < next.value && next.isSorted(); }`? That said, you may be better with iterative, rather than recursive, code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T16:22:58.427",
"Id": "497918",
"Score": "0",
"body": "public class Element {\n private int value;\n private Element next;} the class also includes the isSorted function"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T17:18:13.243",
"Id": "497922",
"Score": "1",
"body": "Welcome to Code Review! When adding additional information you should [edit] your question instead of adding a comment. I have added that information to your post. Learn more about comments including when to comment and when not to in [the Help Center page about Comments](https://codereview.stackexchange.com/help/privileges/comment)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T17:19:51.513",
"Id": "497923",
"Score": "0",
"body": "for anyone in the close vote queue: this post is on-topic now"
}
] |
[
{
"body": "<p>I would like to add few improvements for better readability.</p>\n<ol>\n<li><p>You don't need an <code>else</code> statement; rather you should directly return it.</p>\n</li>\n<li><p>For every <code>if</code> and <code>else</code> statement, even if it is a single line and Java allows it without braces, it's not preferable because of possible code bugs which may arise in future due to missing braces.</p>\n</li>\n<li><p>Better to put <code>(this.value < this.next.value)</code> in brackets for better readability.</p>\n</li>\n</ol>\n<p>So the updated code should look like:</p>\n<pre><code>public boolean isSorted() {\n if (this.next == null) {\n return true;\n }\n \n return (this.value < this.next.value) && this.next.isSorted();\n} \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T14:32:45.913",
"Id": "497897",
"Score": "1",
"body": "thank you for your improvements :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T13:24:44.897",
"Id": "252652",
"ParentId": "252650",
"Score": "7"
}
},
{
"body": "<p>There is no need for <code>else</code>.\nFor better code readability single point of <code>return</code> should be used.</p>\n<pre><code>return (this.next == null) || ((this.value < this.next.value) && this.next.isSorted());\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T18:52:24.157",
"Id": "252668",
"ParentId": "252650",
"Score": "2"
}
},
{
"body": "<p>With this implementation it is impossible for a list with duplicate elements to be sorted. However, that possibility is easy enough to support:</p>\n<pre><code>return (next == null)\n || ((value <= next.value) && next.isSorted());\n</code></pre>\n<p>Now, empty lists are explicitly sorted by the first clause. Lists with an element strictly greater than a previous element are not sorted by the second. And the third says that if the first two values are sorted and the rest of the list is sorted, the list as a whole is sorted.</p>\n<p>This works because this uses short circuit Boolean operators. So when <code>next</code> is null, it doesn't bother to check the rest of the statement (<code>true ||</code> is always true). And when the current value is greater than the next, it doesn't need to continue (<code>false &&</code> is always false). Finally, if it makes it to the last clause, it can simply return the result of it. Because it knows that the first clause was false and the second was true; otherwise, it would never have reached the third.</p>\n<p>Alternately, you could change the name from <code>isSorted</code> to <code>isIncreasing</code> which would better describe what you are actually doing. If that is what you actually wanted to do.</p>\n<p>Moving from a recursive solution on <code>Element</code> to an iterative solution on the linked list would also make sense.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T23:15:30.053",
"Id": "252684",
"ParentId": "252650",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "252684",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T12:52:22.553",
"Id": "252650",
"Score": "1",
"Tags": [
"java",
"recursion"
],
"Title": "Java recursive sort verification function for a linked list"
}
|
252650
|
<p>I have been trying to code something simple where I call a class with different functions to different paths,</p>
<p>if I call etc:</p>
<pre><code>from lib.utils import GetAllPaths
path = GetAllPaths()
path.test()
</code></pre>
<p>with following code:</p>
<pre><code>class GetAllPaths:
"""
Return file and paths directions
"""
if platform == "win32":
def test(self):
return "C:\\Users\\test.py"
def test2(self):
return "C:\\Users\\test2.py"
def test_flag(self):
# new_manual_url.flag
return "C:\\Users\\*test.flag"
def kill_flag(self):
# kill_*.txt
return "C:\\Users\\*kill_*.flag"
def restart(self):
# start_*.txt
return "C:\\Users\\*start_*.flag"
elif platform == "linux" or platform == "linux2":
def test(self):
return "/home/test.py"
def test2(self):
return "/home/test2.py"
def test_flag(self):
return "/home/*test.flag"
def kill_flag(self):
return "/home/*kill_*.flag"
def restart(self):
return "/home/*start_*.flag"
</code></pre>
<p>My problem here is that I run sometimes my code through Linux and sometimes through Windows, so I have created a if else statement if the script is ran through Linux or Windows,</p>
<p>however I do see huge potential to short this code by alot but I don't know how to apply it where I can choose etc if its linux then use the correct path of "test" for linux or if its windows then use the correct path of "test" for windows</p>
|
[] |
[
{
"body": "<p>I think you can lean on a class-variable to create your base paths, and then define the functions to use that variable:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import os\nfrom sys import platform\n\nclass GetAllPaths:\n """\n Return file and paths directions\n """\n\n if platform == "win32":\n root = 'C:\\\\Users'\n elif platform == 'linux':\n root = '/home'\n else:\n # Probably raise an exception here\n raise Exception(f"Platform {platform} not supported")\n\n def test(self):\n return os.path.join(self.root, "test.py")\n\n def test2(self):\n return os.path.join(self.root, "test2.py")\n\n def test_flag(self):\n # new_manual_url.flag\n return os.path.join(self.root, "*test.flag")\n\n def kill_flag(self):\n # kill_*.txt\n return os.path.join(self.root, "*kill_*.flag")\n\n def restart(self):\n # start_*.txt\n return os.path.join(self.root, "*start_*.flag")\n</code></pre>\n<p>Furthermore, you'll notice that I'm using <code>os.path.join</code>, this way you don't have to worry about hard-coding the path separators.</p>\n<p>Even more DRY would be to use a decorator on each of these functions which cuts down on repeated code:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import os\nfrom functools import wraps\nfrom sys import platform\n\n\nclass GetAllPaths:\n if platform == "win32":\n root = 'C:\\\\Users'\n elif platform == 'linux':\n root = '/home'\n else:\n # Probably raise an exception here\n raise Exception(f"Platform {platform} not supported")\n\n def _add_platform(f):\n @wraps(f)\n def wrapper(self):\n path = f(self)\n return os.path.join(self.root, path)\n return wrapper\n\n \n @_add_platform\n def test(self):\n return "test.py"\n\n \n @_add_platform\n def test2(self):\n return "test2.py"\n\n\n @_add_platform\n def test_flag(self):\n # new_manual_url.flag\n return "*test.flag"\n\n\n @_add_platform\n def kill_flag(self):\n # kill_*.txt\n return "*kill_*.flag"\n\n\n @_add_platform\n def restart(self):\n # start_*.txt\n return "*start_*.flag"\n</code></pre>\n<h2>Ditch the <code>class</code></h2>\n<p>Realistically, you don't <em>need</em> the class here. You can identify this by looking at how your functions are utilized. There's not any class or instance specific information being passed to your functions (decorator notwithstanding). This means that your class and a module are fairly indistinguishable. To see this without a class, you might put all of this code into a new file, say <code>get_all_paths.py</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code># get_all_paths.py\nimport os\nfrom functools import wraps\nfrom sys import platform\n\n\nif platform == "win32":\n root = 'C:\\\\Users'\nelif platform == 'linux':\n root = '/home'\nelse:\n # Probably raise an exception here\n raise Exception(f"Platform {platform} not supported")\n\n\ndef add_platform(f):\n @wraps(f)\n def wrapper(*args, **kwargs):\n path = f(*args, **kwargs)\n return os.path.join(root, path)\n return wrapper\n\n\n@add_platform\ndef test():\n return "test.py"\n\n\n@add_platform\ndef test2():\n return "test2.py"\n\n\n@add_platform\ndef test_flag():\n # new_manual_url.flag\n return "*test.flag"\n\n\n@add_platform\ndef kill_flag():\n # kill_*.txt\n return "*kill_*.flag"\n\n\n@add_platform\ndef restart():\n # start_*.txt\n return "*start_*.flag"\n\n</code></pre>\n<p>Where now, you can use your functions through a global import:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import get_all_paths as g\n\ng.test()\n'/home/test.py'\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T15:53:42.863",
"Id": "497909",
"Score": "0",
"body": "Oh wow! This also seem pretty nice way to do it I would say! Really like the concept but do you think that it is still necessary to use Class for this problem I do have? I mean I do not need to use Classes but I couldn't figure out another way than this as well. But for sure this already cuts my code by half!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T15:55:28.210",
"Id": "497911",
"Score": "0",
"body": "The way this is set up, no, you don't need the class. It would slightly change how the functions and decorator look, but the concept is the same. `root` could be module-level"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T15:57:31.563",
"Id": "497912",
"Score": "0",
"body": "Would you mind how it would look like if we don't use the class? Im curious how it would look like when we still need to look for the if-else statement for the Linux & Windows? If not then I still do appreciate this since it did give me a good inspiration! :D"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T15:49:22.543",
"Id": "252662",
"ParentId": "252651",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "252662",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T13:10:34.300",
"Id": "252651",
"Score": "6",
"Tags": [
"python"
],
"Title": "Return correct path if windows or linux"
}
|
252651
|
<p>I created an app which counts days, hours, minutes and seconds until some event.</p>
<p>I learned a lot while creating it and as always I would love some feedback from you guys to improve my code by learning from mistakes and maybe implement a better solution. In particular, I am not very proud of the way my <code>startTimer()</code> works.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>'use strict';
// #####################################################################
// start - event name and calculating difference between the event and today
const startBtn = document.querySelector('.start-btn');
const resetBtn = document.querySelector('.reset-btn');
const eventName = document.querySelector('#event-name');
const eventDate = document.querySelector('#event-date');
const eventTime = document.querySelector('#event-time');
const untilParagraph = document.querySelector('.until');
let isStartClicked = false;
startBtn.addEventListener('click', () => {
const today = new Date();
let eventDay = new Date(eventDate.value);
if (isValid('time')) {
const splitedTime = eventTime.value.split(':');
eventDay.setHours(splitedTime[0]);
eventDay.setMinutes(splitedTime[1]);
}
//date in the past
if (eventDay.getTime() < today.getTime()) {
const message = document.querySelector('.message');
message.classList.remove('hidden');
const messageClose = document.querySelector('.message__close');
messageClose.addEventListener('click', () => {
message.classList.add('hidden');
});
return;
}
if (isValid('name') && isValid() && !isStartClicked) {
untilParagraph.innerHTML = `<span class='until--until'>until</span> ${eventName.value}`;
let difference = eventDay - today; //in ms
const daysLeft = Math.floor(difference / (1000 * 3600 * 24));
difference -= daysLeft * 1000 * 3600 * 24;
let hoursLeft, minutesLeft, secondsLeft;
hoursLeft = Math.floor(difference / (1000 * 3600));
difference -= hoursLeft * 1000 * 3600;
minutesLeft = Math.floor(difference / (1000 * 60));
difference -= minutesLeft * 1000 * 60;
secondsLeft = Math.floor(difference / 1000);
difference -= secondsLeft * 1000;
startTimer({ daysLeft, hoursLeft, minutesLeft, secondsLeft });
isStartClicked = true;
}
});
// #####################################################################
// reset
resetBtn.addEventListener('click', () => {
stopTimer();
insertTime({ daysLeft: 0, hoursLeft: 0, minutesLeft: 0, secondsLeft: 0 });
isStartClicked = false;
});
// #####################################################################
// Validation
const isValid = (type) => {
if (type === 'name') {
if (eventName.value) return true;
return false;
} else if (type === 'time') {
const timePattern = /^([0-1][0-9]|[2][0-3]):([0-5][0-9])$/;
if (!timePattern.test(eventTime.value)) return false;
else return true;
} else {
// date
const datePattern = /^(((0[13-9]|1[012])[-/]?(0[1-9]|[12][0-9]|30)|(0[13578]|1[02])[-/]?31|02[-/]?(0[1-9]|1[0-9]|2[0-8]))[-/]?[0-9]{4}|02[-/]?29[-/]?([0-9]{2}(([2468][048]|[02468][48])|[13579][26])|([13579][26]|[02468][048]|0[0-9]|1[0-6])00))$/;
if (!datePattern.test(eventDate.value)) return false;
else return true;
}
};
eventName.addEventListener('blur', () => {
if (!isValid('name'))
document.querySelector('#name-invalid').classList.remove('hidden');
else document.querySelector('#name-invalid').classList.add('hidden');
});
eventDate.addEventListener('blur', () => {
if (!isValid('date'))
document.querySelector('#date-invalid').classList.remove('hidden');
else document.querySelector('#date-invalid').classList.add('hidden');
});
eventTime.addEventListener('blur', () => {
if (!isValid('time'))
document.querySelector('#time-invalid').classList.remove('hidden');
else document.querySelector('#time-invalid').classList.add('hidden');
});
// #####################################################################
// Timer
let interval;
const startTimer = (time) => {
interval = setInterval(() => {
if (
time.daysLeft != 0 ||
time.hoursLeft != 0 ||
time.minutesLeft != 0 ||
time.secondsLeft != 0
) {
if (time.secondsLeft > 0) {
time.secondsLeft -= 1;
} else {
time.secondsLeft = 59;
if (time.minutesLeft > 0) time.minutesLeft -= 1;
else {
time.minutesLeft = 59;
if (time.hoursLeft > 0) time.hoursLeft -= 1;
else {
time.hoursLeft = 23;
if (time.daysLeft > 0) time.daysLeft -= 1;
}
}
}
}
insertTime(time);
}, 1000);
};
const stopTimer = () => {
clearInterval(interval);
};
const insertTime = (time) => {
document.querySelector('.days').textContent =
time.daysLeft < 10 ? `0${time.daysLeft}` : time.daysLeft;
document.querySelector('.hours').textContent =
time.hoursLeft < 10 ? `0${time.hoursLeft}` : time.hoursLeft;
document.querySelector('.minutes').textContent =
time.minutesLeft < 10 ? `0${time.minutesLeft}` : time.minutesLeft;
document.querySelector('.seconds').textContent =
time.secondsLeft < 10 ? `0${time.secondsLeft}` : time.secondsLeft;
};
// TODO:
// ? Improve algorythmic notation of timer</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url("https://fonts.googleapis.com/css2?family=Ubuntu:wght@300;400;500;700&display=swap");
*,
*::after,
*::before {
padding: 0;
margin: 0;
-webkit-box-sizing: border-box;
box-sizing: border-box;
font-family: 'Ubuntu', sans-serif;
}
body {
background-color: #111010;
height: 100vh;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
main .menu {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
padding: 5rem 15rem;
border: 2px solid #fffbfc;
border-radius: 3px;
}
main .menu div {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-direction: column;
flex-direction: column;
color: #fffbfc;
position: relative;
}
main .menu div:not(:first-child) {
margin-left: 3rem;
}
main .menu div label {
font-size: 0.8rem;
font-weight: 400;
}
main .menu div label span {
font-size: 0.7rem;
color: #c2c2c2;
font-weight: 300;
}
main .menu div input {
padding: 1rem 0.7rem;
margin-top: 1rem;
background-color: #292727;
border: none;
border-radius: 5px;
color: #fffbfc;
}
main .menu div input::-webkit-input-placeholder {
color: #c2c2c2;
}
main .menu div input:-ms-input-placeholder {
color: #c2c2c2;
}
main .menu div input::-ms-input-placeholder {
color: #c2c2c2;
}
main .menu div input::placeholder {
color: #c2c2c2;
}
main .menu div .valid-info {
color: #e94949;
margin-top: 0.5rem;
font-size: 0.8rem;
font-weight: bold;
position: absolute;
top: 100%;
}
main .menu .btn {
height: 45px;
width: 80px;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-ms-flex-item-align: end;
align-self: flex-end;
border: 2px solid #fffbfc;
color: #fffbfc;
text-decoration: none;
padding: 0.8rem 1.3rem;
-webkit-transition: all 0.3s;
transition: all 0.3s;
border-radius: 5px;
background: none;
cursor: pointer;
}
main .menu .btn:hover {
background-color: #fffbfc;
color: black;
}
main .menu .btn--margin-small {
margin-left: 1rem;
}
main .menu .btn--margin-big {
margin-left: 3rem;
}
main .event {
padding: 10rem 15rem;
}
main .event .timer-box {
color: white;
font-size: 8rem;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
font-weight: 500;
}
main .event .timer-box p {
font-size: 5rem;
}
main .event .timer-box .days,
main .event .timer-box .hours,
main .event .timer-box .minutes,
main .event .timer-box .seconds {
position: relative;
}
main .event .timer-box .days::before,
main .event .timer-box .hours::before,
main .event .timer-box .minutes::before,
main .event .timer-box .seconds::before {
font-size: 1rem;
position: absolute;
bottom: 100%;
left: 50%;
-webkit-transform: translateX(-50%);
transform: translateX(-50%);
color: #c2c2c2;
font-weight: 300;
}
main .event .timer-box .days::before {
content: 'days';
}
main .event .timer-box .hours::before {
content: 'hours';
}
main .event .timer-box .minutes::before {
content: 'minutes';
}
main .event .timer-box .seconds::before {
content: 'seconds';
}
main .event .until {
font-size: 1rem;
font-weight: bold;
color: #c2c2c2;
margin-top: 2rem;
text-align: center;
-ms-flex-item-align: end;
align-self: flex-end;
}
main .event .until--until {
font-size: 0.8rem;
color: #aaaaaa;
font-weight: 300;
}
.message {
color: black;
font-weight: 500;
border-radius: 5px;
text-align: center;
background-color: white;
position: absolute;
top: 10rem;
left: 50%;
padding: 2rem 4rem;
-webkit-transform: translateX(-50%);
transform: translateX(-50%);
}
.message__close {
color: black;
text-decoration: none;
font-weight: bold;
font-size: 1.2em;
padding: 0.5rem;
position: absolute;
top: 0;
right: 0;
-webkit-transition: scale 0.3s;
transition: scale 0.3s;
}
.message__close:hover {
-webkit-transform: scale(1.5);
transform: scale(1.5);
}
.hidden {
visibility: hidden;
}
/*# sourceMappingURL=main.css.map */</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style/main.css">
<title>Countdown</title>
</head>
<body>
<main>
<form action="#" class="menu">
<div>
<label for="event-name">Event name</label>
<input type="text" id='event-name' placeholder="New Year Party" required>
<p class='valid-info hidden' id="name-invalid">Invalid name</p>
</div>
<div>
<label for="event-date">Date</label>
<input type="text" id='event-date' placeholder="12/31/2020" required>
<p class='valid-info hidden' id="date-invalid">Invalid date</p>
</div>
<div>
<label for="event-time">Time <span>(optional)</span></label>
<input type="text" id='event-time' placeholder="20:00">
<p class='valid-info hidden' id="time-invalid">Invalid time</p>
</div>
<button class='btn btn--margin-big start-btn'>Start</button>
<a href="#" class='btn btn--margin-small reset-btn'>Reset</a>
</form>
<div class="event">
<div class="timer-box">
<div class="days">00</div>
<p>:</p>
<div class="hours">00</div>
<p>:</p>
<div class="minutes">00</div>
<p>:</p>
<div class="seconds">00</div>
</div>
<div class="until"> <span class='until--until'>until</span> New Year Party</div>
</div>
<p class="message hidden">Your event has already happend
<a href="#" class="message__close">x</a>
</p>
</main>
<script src="script.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>It does not look bad :)</p>\n<p>Thing I'd improve:</p>\n<ul>\n<li><p>Avoid styling using the HTML tags. Use classes instead</p>\n</li>\n<li><p>color: #c2c2c2; is repeated a lot. Use one CSS selector that applies this style to multiple elements instead of repeating it</p>\n</li>\n<li><p>: in your timer should not be a paragraph. I'd pick a span instead</p>\n</li>\n<li><p>I'd add a test or at least a comment for the regExp. Or maybe a variable with a descriptive name ?</p>\n</li>\n<li>\n<pre><code>if (\n time.daysLeft != 0 ||\n time.hoursLeft != 0 ||\n time.minutesLeft != 0 ||\n time.secondsLeft != 0\n</code></pre>\n<p>.... should be replaced by a JS <code>.some()</code> method that would repurn true if one of the elements meets the condition</p>\n</li>\n<li><p>Add curly braces on if/else statements</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-28T09:40:23.023",
"Id": "252781",
"ParentId": "252655",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "252781",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T14:04:41.023",
"Id": "252655",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "Timer app in vanilla JS"
}
|
252655
|
<p>What is your opinion on my solution for <strong>Rock Paper Scissors</strong> game logic in Java?</p>
<h3>Round outcome <code>enum</code> class</h3>
<pre><code>public enum Winer
{
DRAW,
PLAYER,
COMPUTER;
}
</code></pre>
<h3>Played moves <code>enum</code> class</h3>
<pre><code>public enum PlayedMove
{
ROCK,
PAPER,
SCISSORS;
}
</code></pre>
<h3>Game logic class</h3>
<pre><code>public class GameLogic
{
public static Winer getWiner(PlayedMove player, PlayedMove computer)
{
if (player == computer)
{
return Winer.DRAW;
}
else if (isPlayerWiner(player, computer))
{
return Winer.PLAYER;
}
else
{
return Winer.COMPUTER;
}
}
private static boolean isPlayerWiner(PlayedMove player, PlayedMove computer)
{
return ((player == PlayedMove.ROCK && computer == PlayedMove.SCISSORS)
|| (player == PlayedMove.SCISSORS && computer == PlayedMove.PAPER)
|| (player == PlayedMove.PAPER && computer == PlayedMove.ROCK));
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T15:11:07.970",
"Id": "497900",
"Score": "2",
"body": "I think your solution depends on the need for the \"problem\". That is why you should include a statement that details the use case (s) of the game itself. For example, what happens if you win 3 times in a row.\nIn this way we can know how well your solution fits the problem itself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T09:50:51.087",
"Id": "498146",
"Score": "0",
"body": "I suggest that you expand the game to Rock Paper Scissors Spock Lizard, see http://www.samkass.com/theories/RPSSL.html. That way you have the same logic, but have more cases to cover. If the code gets messy when doing this you probably should look into other ways to solve the problem."
}
] |
[
{
"body": "<p>The code looks fine, few suggestions:</p>\n<ul>\n<li><strong>Typo</strong>: <code>winer</code> should be <code>winner</code>.</li>\n<li><strong>Naming</strong>: since the variable <code>player</code> is of type <code>PlayedMove</code>, it's better to name it <code>playerMove</code>. Same for the variable <code>computer</code>. Reading <code>playerMove == PlayedMove.ROCK</code> is betten than <code>player == PlayedMove.ROCK</code>. The class name <code>GameLogic</code> seems too generic, consider a more specific name, for example <code>RockPaperScissors</code>.</li>\n<li><strong>Ternary operator</strong>: the method <code>getWiner</code> can use the ternary operator for deciding the winner between <code>Winner.COMPUTER</code> and <code>Winner.PLAYER</code>.</li>\n<li><strong>Redundant parentheses</strong>: in the last <code>return</code> the outer parentheses can be removed.</li>\n<li><strong>Code format</strong>: personally, I prefer the curly braces on the same line and IntelliJ Idea auto-formatting agrees with this rule.</li>\n<li><strong>OOP missing</strong>: as others have mentioned, it's hard to say that this implementation is object-oriented since there are only static methods. To make it more object-oriented, there should be at least one object that stores some data as its own state and provides methods to manipulate such state.</li>\n<li><strong>Minor readability improvement (optional)</strong>: adding methods like <code>isRock</code>, <code>isPaper</code> and <code>isRock</code> to <code>PlayedMove</code>, makes the code more compact and a little bit easier to read. Alternatively, <code>PlayedMove</code> can be imported statically but I prefer the former.</li>\n</ul>\n<h2>Revised code:</h2>\n<pre><code>public static Winner getWinner(PlayedMove playerMove, PlayedMove computerMove) {\n if (playerMove == computerMove) {\n return Winner.DRAW;\n } \n return isPlayerWinner(playerMove, computerMove) ? Winner.PLAYER : Winner.COMPUTER;\n}\n\nprivate static boolean isPlayerWinner(PlayedMove playerMove, PlayedMove computerMove) {\n return (playerMove.isRock() && computerMove.isScissors())\n || (playerMove.isScissors() && computerMove.isPaper())\n || (playerMove.isPaper() && computerMove.isRock());\n}\n</code></pre>\n<p><code>PlayedMove</code>:</p>\n<pre><code>enum PlayedMove {\n PAPER(0),\n ROCK(1),\n SCISSORS(2);\n\n private final int value;\n\n PlayedMove(int value) {\n this.value = value;\n }\n\n public boolean isPaper() {\n return this.value == PAPER.value;\n }\n\n // isRock and isScissors methods..\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T19:30:54.120",
"Id": "497935",
"Score": "1",
"body": "Thanks for the advice, I appreciate it. Regarding code formatting, that is not part of Java conventions. There are many generally accepted code styles. In Eclipse IDE, and probably in many other IDEs, you can define your own code auto format."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T02:15:53.907",
"Id": "497992",
"Score": "12",
"body": "The java convention has always been that curly braces go on the same line. https://www.oracle.com/technetwork/java/codeconventions-150003.pdf"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T03:13:40.283",
"Id": "497993",
"Score": "1",
"body": "Oracle's convention document published in 1997 is not evidence of \"always\", for several reasons: Java existed before that; styles have changed since then; not everybody agrees with Oracle anyway. Braces on the same line is a popular style today, but by no means the only style used. now or in the past."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T08:57:35.167",
"Id": "498027",
"Score": "9",
"body": "@amalloy braces on the same line is used in every single open source Java library / framework I know of. Its pretty much the de-facto standard of the ecosystem, even if there are some exceptions. That is notably different in C#, where the prevalent style is braces on new lines, which is done by MS and widely adopted in the C# ecosystem. \"When in rome, do as the romans do\" is always a good advice to follow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T09:02:18.757",
"Id": "498028",
"Score": "0",
"body": "People tend to use the oracle/sun conventions, and java has the conventions specified. Its not the only style in use by any means, but its not something that I would have brought up. I feel its more comment worthy than a point I'd bring up in a code review of an independant library.\n\nBut java style is the one mentioned here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T03:35:20.697",
"Id": "498124",
"Score": "0",
"body": "@ZoranJankov I am glad I could help ;). FYI, I added a note about OOP and a minor style suggestion."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T16:31:33.443",
"Id": "252664",
"ParentId": "252657",
"Score": "10"
}
},
{
"body": "<p>I don't see anything object-oriented in it. A program without a single non-static method can hardly be called OO.</p>\n<p>The main task of this piece of code is to compare <code>PlayedMove</code> instances, so to follow OO style, you should make that comparison a method of <code>PlayedMove</code>. This will make the enum a bit more complex (beyond beginner level), so you might want to switch away from <code>PlayedMove</code> being an enum (or, use it as an exercise on complex enums).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T19:24:19.933",
"Id": "497934",
"Score": "0",
"body": "Yes, I now see that I could transfer the code of the `GameLogic` class in the `Winner` enum."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T10:09:08.337",
"Id": "498037",
"Score": "1",
"body": "@ZoranJankov `Winner` is useful for many contexts; I would put the logic to see which `Move` wins against which inside the `Move` enum"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T01:54:01.413",
"Id": "498264",
"Score": "2",
"body": "@tucuxi I would handle the logic neither in the Winner nor in the Move enums. Having a separate function/method is totally fine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T12:34:49.743",
"Id": "498292",
"Score": "1",
"body": "@RolandIllig in OOP, placing that function/method inside a well-chosen class is also fine :-)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T18:03:49.817",
"Id": "252667",
"ParentId": "252657",
"Score": "14"
}
},
{
"body": "<p>In my opinion, the logic contained in the <code>GameLogic#isPlayerWinner</code> method can be exploded into a <code>switch</code> to declutter the logic; this will remove the need to compare the player's move with the computer's move.</p>\n<p><strong>Enhanced switch statement - Java 14</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>private static boolean isPlayerWinner(PlayedMove player, PlayedMove computer) {\n return switch (player) {\n case ROCK -> computer == PlayedMove.SCISSORS;\n case PAPER -> computer == PlayedMove.ROCK;\n case SCISSORS -> computer == PlayedMove.PAPER;\n default -> throw new IllegalArgumentException();\n };\n}\n</code></pre>\n<p><strong>Java under 14</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>private static boolean isPlayerWinner(PlayedMove player, PlayedMove computer) {\n switch (player) {\n case ROCK:\n return computer == PlayedMove.SCISSORS;\n case PAPER:\n return computer == PlayedMove.ROCK;\n case SCISSORS:\n return computer == PlayedMove.PAPER;\n default:\n throw new IllegalArgumentException();\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T21:41:17.560",
"Id": "252679",
"ParentId": "252657",
"Score": "4"
}
},
{
"body": "<p>One important point I would like to add (along with what is suggested earlier). Your class is having only static methods. If class is having only static methods, then:</p>\n<ol>\n<li><p>This class should be marked final to prevent inheritance.</p>\n</li>\n<li><p>Class constructor should be private to prevent class initialization.</p>\n</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T05:27:14.603",
"Id": "252693",
"ParentId": "252657",
"Score": "1"
}
},
{
"body": "<p>This is not OOP, because all your methods are static.</p>\n<p>To make it into an OOP program, you could re-model it like this: A game has two players. For the game, it is not important, if the player is human or computer. Now, a human can only play against a computer, but what if you want to implement a multi-player mode?</p>\n<p>First we create an interface for the player:</p>\n<pre><code>public interface Player\n{\n PlayedMove chooseMove();\n}\n</code></pre>\n<p>There should be two classes implementing the interface, one for a human and one for a computer:</p>\n<pre><code>public class HumanPlayer implements Player\n{\n public PlayedMove chooseMove()\n {\n // read from keyboard or wait for button clicked\n }\n}\n\npublic class ComputerPlayer implements Player\n{\n public PlayedMove chooseMove()\n {\n // choose randomly\n }\n}\n</code></pre>\n<p>Then you have a game class, which holds two players. If you call the <code>play()</code> method, it will every player chose who their move and then return the winning player, or null if it was a draw.</p>\n<pre><code>public class Game\n{\n private Player player1;\n private Player player2;\n\n public Game(Player player1, Player player2)\n {\n this.player1 = player1;\n this.player2 = player2;\n }\n\n public Player play()\n {\n PlayedMove player1Move = player1.chooseMove();\n PlayedMove player2Move = player2.chooseMove();\n if(player1Move == PlayedMove.ROCK && player2Move == PlayedMove.SCISSORS ||\n player1Move == PlayedMove.PAPER && player2Move == PlayedMove.ROCK ||\n player1Move == PlayedMove.SCISSORS && player2Move == PlayedMove.PAPER)\n {\n return player1;\n }\n else if(player2Move == PlayedMove.ROCK && player1Move == PlayedMove.SCISSORS ||\n player2Move == PlayedMove.PAPER && player1Move == PlayedMove.ROCK ||\n player2Move == PlayedMove.SCISSORS && player1Move == PlayedMove.PAPER)\n {\n return player2;\n }\n else\n {\n return null;\n }\n } \n}\n</code></pre>\n<p>Note: I am mostly a C# programmer, hence this code might not contain the most fancy Java features.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T09:54:53.047",
"Id": "498035",
"Score": "0",
"body": "You could offload move-outcome computation int the move, and make your `Game` class ignore details of `PlayerMove`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T14:44:45.393",
"Id": "498166",
"Score": "0",
"body": "I also think that the comparison part of this answer is not the best. For this, I recommend the other answers. With this answer, I wanted to show how one could make OP's code more object-oriented by introducing classes and an interface for the players."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T07:45:46.377",
"Id": "252698",
"ParentId": "252657",
"Score": "5"
}
},
{
"body": "<p>The code is readable, and beyond the <code>Winer</code> typo, and the use of brackes-on-different-lines (which I realize is not universal; but that Java code tends to adhere to), it certainly passes muster.</p>\n<p>However, I suggest making heavier use of <code>enum</code> (which I find are generally under-utilized) as follows:</p>\n<pre><code>enum Move {\n ROCK, \n SCISSORS,\n PAPER; \n \n private Move winsAgainst;\n static {\n ROCK.winsAgainst = SCISSORS;\n SCISSORS.winsAgainst = PAPER;\n PAPER.winsAgainst = ROCK;\n }\n\n public Result against(Move other) {\n if (this == other) return Result.DRAW;\n\n return (winsAgainst == other) ? Result.WIN : Result.LOSS;\n }\n}\n</code></pre>\n<p>A simpler variant using constructors unfortunately does not work due to forward references -- see <a href=\"https://stackoverflow.com/questions/5678309/illegal-forward-reference-and-enums\">this question on SO</a>.</p>\n<p>I would also rename <code>PlayedMove</code> to <code>Move</code> (it will probably be an inner class, so that the outer class will provide enough context, as in <code>RockPaperScissors.Move</code>), and <code>Winner</code> to <code>Result</code>, so that you can build different games that do not necessarily have a human and a computer competing -- this allows <code>Move</code> to be used unchanged in more contexts.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T10:35:26.983",
"Id": "498039",
"Score": "0",
"body": "The game logic should not be programmed into a class that describes the action as that prevents one from extending the game logic. The action should only know about itself. Game logic should be placed in a class whose responsibility is to handle game logic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T11:10:49.863",
"Id": "498040",
"Score": "5",
"body": "@TorbenPutkonen we disagree. The fact that rock wins vs scissors is very coupled to those values, and placing it in a different class adds little clarity. Mixing logic with data when closely coupled is a common OO practice. If other games need to be implemented, different `OtherGame.Move` enums, possibly with a common interface, would be my choice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T11:32:15.070",
"Id": "498043",
"Score": "1",
"body": "You can use object equality rather than .equals() methods...\nOtherwise, the code is exemplary, in my view, as it's more data-driven than procedural."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T07:33:50.567",
"Id": "498133",
"Score": "0",
"body": "@tucuxi I have a real grudge against placing logic inside enums. My view is that it always violates single responsibility principle. It extends the enum contract in non-standard ways and always surprises the maintainer. This particular example is a highly specialized use case but with a more generic enum it makes the code unreusable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T07:38:54.713",
"Id": "498134",
"Score": "0",
"body": "@tucuxi Where would you go looking for gameplay rules if you were handed a completely unfamiliar piece of code? I would look for a class with a name such as GameLogic. No matter how convenient it seems in a short term, loading enums with logic is always the less maintainable approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T10:12:37.297",
"Id": "498151",
"Score": "1",
"body": "@TorbenPutkonen, I vehemently disagree. It doesn't violate SRP, since any logic should be tightly coupled to the values. Uncle bob himself uses and recommends this in Clean Code. As to maintainability, placing logic elsewhere is *way* worse: I added a new value, now where are all the places I need to change that should handle this new value? Also, the same unfamiliar code example (as strained as it is) can be used the other way as well: I have a move, what can I do with it? Ctrl+F PlayerMoveUtils?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T11:22:36.923",
"Id": "498155",
"Score": "0",
"body": "@MarkBluemel fixed equals - you are right, readability is improved."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T14:50:20.433",
"Id": "498168",
"Score": "0",
"body": "I also agree with putting the logic with the enum, why ? Because if you want to add a 4th move and the logic that goes with it, you will need to actually add a new value in the enum, hence modifying it. Now you might want a game where you actually change the rules (or different rules \"mods\"), but that's probably beyond the scope of what OP intended and can be classified as YAGNI for the moment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-28T08:11:28.860",
"Id": "498208",
"Score": "0",
"body": "If the logic is tightly coupled with the values, then the values need to be put into the component that implements the logic (enum in class as a public member). Now you have logic split between the game engine and the enumeration. Putting logic in enumeration is always a case of doing things because they're possible instead of thinking whether they should be made."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T19:40:33.580",
"Id": "498319",
"Score": "0",
"body": "Having an enum with non-final fields is bad style. Sure, the `static` initializer does its job, but everyone else uses a constructor for this purpose."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T20:26:06.933",
"Id": "498325",
"Score": "0",
"body": "@RolandIllig read the link regarding constructors and forward references. Yes, I tried with final+constructor. No, it did not work."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T09:51:54.233",
"Id": "252702",
"ParentId": "252657",
"Score": "4"
}
},
{
"body": "<p>The main point of OO is to provide structures that allow you to easily extend and modify your application without having to alter existing source code. Having everything in static methods prevent this completely.</p>\n<p>How would you extend your code to handle "rock, paper, scissors, lizard, spock"? First the moves have to be taken out of the enum, because the enum prevents extensions, and replace it with an interface: <code>Move</code>.</p>\n<p>The game logic is essentially comparing the moves. A <code>Comparator<T extends Move></code> comes to min but it doesn't cut it because the relations are cyclical and that breaks Comparator's contract. You need to name it <code>MoveEvaluator<T extends Move></code>.</p>\n<p>Players need to know which moves the game supports. A <code>MoveFactory<T extends Move></code> is used to list the moves.</p>\n<p>You probably want to have games decided on best of three or more rounds, because after all, this is a game of skill. So the moves played by the two players are are stored in a <code>Round<T extends Move></code>. The fate of earth is decided in RPS game against aliens so better not call the players humans or computers, just use player1 and player2.</p>\n<p>A <code>Game<T extends Move></code> holds the number of rounds needed to win the game and the rounds that have been played.</p>\n<p>And so on...</p>\n<p>I don't blame you if you now want to go code in Python and make memes about Java coders writing endless factories.</p>\n<p>Now that you got this far, RPS only works for choosing a winner from two participants. You also have to think about how you would write your code so that it can be extended to allow three or more people?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T11:18:58.600",
"Id": "498042",
"Score": "4",
"body": "Building an over-general application is a case of premature optimization. What about multi-player? Player ELO calculation? Scalability and network failure? Instead of over-designing from the start, I advocate writing readable code that is easy to refactor if and when requirements change. OPs' program is, in that regard, better than what you propose."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T07:40:24.913",
"Id": "498135",
"Score": "0",
"body": "@tucuxi You're absolutely correct in that. But for the sake of the requested OOP aspects, I stand by my answer. :) I mean, we're striving to making better code in general, not just the best possible throwaway hack."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T10:55:18.600",
"Id": "252705",
"ParentId": "252657",
"Score": "2"
}
},
{
"body": "<p>I was taken with tucuxi's version, but wanted to get more data-driven, with tables to represent combinations of plays, and their outcomes.\nTo take it a stage further, I included the Lizard and Spock ;-)</p>\n<p>From the point of view of reviewing the original code, I dislike complex multi-part "if" statements, and will look for clearer ways to represent the logic. In this case, the set of rules can be encapsulated as data (thanks to Roland for suggesting the rule() method), and, for me, that is a preferable approach. Expressing Rock,Paper,Scissors,Lizard,Spock in the original's style would be very ugly...</p>\n<pre><code>package com.acme.rps;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * OOP approach to Rock, Paper, Scissors, Lizard, Spock\n */\npublic class RockPaperScissors {\n\n private static enum Outcome {\n WIN, LOSE, DRAW;\n }\n\n private static class Result {\n\n private Outcome outcome;\n private String winDescription;\n\n Result(Outcome outcome, String winDescription) {\n this.outcome = outcome;\n this.winDescription = winDescription;\n }\n\n Outcome getOutcome() {\n return outcome;\n }\n\n String getWinDescription() {\n return winDescription;\n }\n }\n\n private static enum Play {\n\n /* The five "Plays" */\n ROCK, PAPER, SCISSORS, LIZARD, SPOCK;\n\n /*\n * For the current play,\n * the plays we can defeat and how we defeat them\n */\n Map<Play /*defeatablePlay*/, String /*how*/> winDescriptions = new HashMap<>();\n\n Result resultAgainst(Play opponentsPlay) {\n if (opponentsPlay == this) { // enums can be compared with object equality\n return new Result(Outcome.DRAW, null);\n }\n\n // Can we defeat them?\n String winDescription = winDescriptions.get(opponentsPlay);\n if (winDescription != null) {\n return new Result(Outcome.WIN, winDescription);\n }\n\n // If not, then they must be able to defeat us\n winDescription = opponentsPlay.winDescriptions.get(this);\n return new Result(Outcome.LOSE, winDescription);\n }\n\n /**\n * A nice way to express one of the rules\n * @param winningPlay\n * @param winDescription\n * @param losingPlay\n */\n static void rule(Play winningPlay, String winDescription, Play losingPlay) {\n winningPlay.winDescriptions.put(losingPlay, winDescription);\n }\n\n static {\n rule(ROCK, "crushes", SCISSORS);\n rule(ROCK, "crushes", LIZARD);\n\n rule(PAPER, "covers", ROCK);\n rule(PAPER, "disproves", SPOCK);\n\n rule(SCISSORS, "cuts", PAPER);\n rule(SCISSORS, "decapitates", LIZARD);\n\n rule(LIZARD, "eats", PAPER);\n rule(LIZARD, "poisons", SPOCK);\n\n rule(SPOCK, "smashes", SCISSORS);\n rule(SPOCK, "vaporizes", ROCK);\n }\n }\n\n /**\n * Show all possible plays and their results\n * @param args ignored\n */\n public static void main(String[] args) {\n for (Play yourPlay : Play.values()) {\n for (Play opponentPlay : Play.values()) {\n System.out.format("You play %s, opponent plays %s, you ", yourPlay.name(), opponentPlay.name());\n Result result = yourPlay.resultAgainst(opponentPlay);\n switch (result.getOutcome()) {\n case DRAW :\n System.out.format("DRAW%n");\n break;\n case LOSE :\n System.out.format("LOSE (%s %s %s)%n", opponentPlay.name(), result.getWinDescription(), yourPlay.name());\n break;\n case WIN :\n System.out.format("WIN (%s %s %s)%n", yourPlay.name(), result.getWinDescription(), opponentPlay.name());\n break;\n default :\n break;\n }\n }\n System.out.println();\n }\n\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T20:30:32.543",
"Id": "498327",
"Score": "0",
"body": "Could you perhaps add a little icing on the cake, in that the rules read `rule(ROCK, \"crushes\", LIZARD)`? This would make them even easier to read and verify."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-30T12:05:11.783",
"Id": "498366",
"Score": "1",
"body": "Thanks @RolandIllig - I've incorporated your rule() method suggestion, which I think is a nice touch."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T12:32:19.223",
"Id": "252708",
"ParentId": "252657",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "252664",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T14:29:43.077",
"Id": "252657",
"Score": "11",
"Tags": [
"java",
"object-oriented",
"game",
"rock-paper-scissors"
],
"Title": "OOP implementation of Rock Paper Scissors game logic in Java"
}
|
252657
|
<p>I've created a <code>.py</code> utility file, which specifies the learning rate policy for the neural network in <strong>PyTorch</strong>. The program in prior reads a <code>json</code> and creates a <code>dict</code>, called here is <code>cfg</code>.</p>
<p>So far, I have implemented 3 kinds of learning policies - <code>steps, exp, cos</code>, and for each of them I've created a separate class with the <code>__call__</code> method. I've done this to have this parameters set in the <code>LambdaLR</code> without further refering to <code>cfg</code> during the training.</p>
<p>In order to avoid branch of <code>if's</code> I've created a dict, which chooses one of the options, and in the function <code>create_scheduler</code> the instance of one of these classes is created, passed to the initializer of <code>LambdaLR</code> scheduler, and this scheduler is then returned.</p>
<pre><code>class LR_Steps:
def __init__(self, cfg):
self.lr_base = cfg["OPTIM"]["BASE_LR"]
self.lr_mult = cfg["OPTIM"]["LR_MULT"]
self.steps = cfg["OPTIM"]["STEPS"]
# the current index in the steps
self.ind = 0
def __call__(self, epoch):
if epoch > self.steps[self.ind]:
self.ind += 1
return self.lr_base * (self.lr_mult ** self.ind)
class LR_Exp:
def __init__(self, cfg):
self.lr_base = cfg["OPTIM"]["BASE_LR"]
self.lr_mult = cfg["OPTIM"]["LR_MULT"]
def __call__(self, epoch):
return self.lr_base * (self.lr_mult ** epoch)
class LR_Cos:
def __init__(self, cfg):
self.lr_base = cfg["OPTIM"]["BASE_LR"]
self.max_epoch = cfg["OPTIM"]["MAX_EPOCH"]
def __call__(self, epoch):
return 0.5 * self.lr_base * (1.0 + np.cos(np.pi * epoch / self.max_epoch))
lr_policy_dict = {
"cos" : LR_Cos,
"exp" : LR_Exp,
"steps" : LR_Steps
}
def create_scheduler(optimizer, cfg):
return optim.lr_scheduler.LambdaLR(optimizer, lr_policy_dict[cfg["OPTIM"]["LR_POLICY"]](cfg))
</code></pre>
<p>My question is - if there a shorter or safer way to do this? I would also appreciate criticism, concerning the structure of code and functionality.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T15:28:20.650",
"Id": "497902",
"Score": "1",
"body": "If each class takes one set of input and exposes one method I'd change them to functions. You don't need a class to map one input to output with any state. In this case it might make sense to create one class that accepts `config` and then wraps what you already have, exposing each of those as a method. You'd only need to set `self.lr_base` once then and each method would have access to it"
}
] |
[
{
"body": "<p>Overall I rather like this. It's a nice way to think about "configurable functions". Minor stuff:</p>\n<ul>\n<li>Due to order of operations, the parens around <code>self.lr_base * (self.lr_mult ** epoch)</code> are not needed</li>\n<li>It's worth splitting out a temporary variable for <code>cfg['OPTIM']</code></li>\n<li>Consider annotating your member variables and method signatures with PEP484 type hints</li>\n<li>Decimals in <code>1.0</code> are not necessary due to float promotion</li>\n<li>Spaces before colons - <code>"cos" :</code> - are not PEP8-standard</li>\n<li>You've not shown unit tests. If you don't have them, write them.</li>\n</ul>\n<p>If you're interested, a different (not necessarily better) way of thinking about these functions is that they can start as normal, non-class functions, where the first parameter(s) are the configuration needed; then call <code>partial()</code> to get a callable reference that you can then use as if it has only <code>epoch</code> as a parameter from the perspective of <code>LambdaLR</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T15:24:09.040",
"Id": "252661",
"ParentId": "252658",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T14:30:22.563",
"Id": "252658",
"Score": "7",
"Tags": [
"python",
"neural-network",
"pytorch"
],
"Title": "A .py utility file for neural network learing rate policies"
}
|
252658
|
<p>I've been quite annoyed lately by the fact that the <code>CopyMemory</code> API (<code>RtlMoveMemory</code> on Windows and <code>MemMove</code> on Mac) is running much slower than it used to, on certain computers. For example on one of my machines (x64 Windows and x32 Office) the <code>CopyMemory</code> API is running about 600 times slower than a month ago. I did do a Windows Update lately and maybe that is why. In this <a href="https://stackoverflow.com/questions/57885185/windows-defender-extremly-slowing-down-macro-only-on-windows-10">SO question</a> is seems that Windows Defender is the cause of slowness. Regardless of why the API is much slower, it is unusable if the operations involving the API need to run many times (e.g. millions of times).</p>
<p>Even without the issue mentioned above, <code>CopyMemory</code> API is slower than other alternatives. Since I did not want to use references to <em>msvbvm60.dll</em> which is not available on most of my machines, I decided to create something similar with the <code>GetMemX</code> and <code>PutMemX</code> methods available in the mentioned dll. So, I created a couple of properties (Get/Let) called <code>MemByte</code>, <code>MemInt</code>, <code>MemLong</code> and <code>MemLongPtr</code> using the same <code>ByRef</code> technique that I've used in the <a href="https://github.com/cristianbuse/VBA-WeakReference" rel="nofollow noreferrer"><code>WeakReference</code></a> repository. In short, I am using 2 Variants that have the <code>VT_BYREF</code> flag set inside the 2 Bytes holding the <code>VarType</code>. These 2 Variants allow remote read/write of memory.</p>
<p><strong>Code</strong></p>
<p>The full module with more explanations and also demos are available on GitHub at <a href="https://github.com/cristianbuse/VBA-MemoryTools" rel="nofollow noreferrer">VBA-MemoryTools</a>.</p>
<p><em>LibMemory</em> standard module:</p>
<pre><code>Option Explicit
Option Private Module
'Used for raising errors
Private Const MODULE_NAME As String = "LibMemory"
#If Mac Then
#If VBA7 Then
Public Declare PtrSafe Function CopyMemory Lib "/usr/lib/libc.dylib" Alias "memmove" (Destination As Any, source As Any, ByVal Length As LongPtr) As LongPtr
#Else
Public Declare Function CopyMemory Lib "/usr/lib/libc.dylib" Alias "memmove" (Destination As Any, source As Any, ByVal Length As Long) As Long
#End If
#Else 'Windows
'https://msdn.microsoft.com/en-us/library/mt723419(v=vs.85).aspx
#If VBA7 Then
Public Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, source As Any, ByVal Length As LongPtr)
#Else
Public Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, source As Any, ByVal Length As Long)
#End If
#End If
#If VBA7 Then
Public Declare PtrSafe Function VarPtrArray Lib "VBE7.dll" Alias "VarPtr" (ByRef ptr() As Any) As LongPtr
#Else
Public Declare Function VarPtrArray Lib "msvbvm60.dll" Alias "VarPtr" (ByRef ptr() As Any) As Long
#End If
'The size in bytes of a memory address
#If Win64 Then
Public Const PTR_SIZE As Long = 8
#Else
Public Const PTR_SIZE As Long = 4
#End If
#If Win64 Then
#If Mac Then
Public Const vbLongLong As Long = 20 'Apparently missing for x64 on Mac
#End If
Public Const vbLongPtr As Long = vbLongLong
#Else
Public Const vbLongPtr As Long = vbLong
#End If
Private Type REMOTE_MEMORY
memValue As Variant
remoteVT As Variant
isInitialized As Boolean 'In case state is lost
End Type
'https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-oaut/3fe7db9f-5803-4dc4-9d14-5425d3f5461f
'https://docs.microsoft.com/en-us/windows/win32/api/oaidl/ns-oaidl-variant?redirectedfrom=MSDN
'Flag used to simulate ByRef Variants
Public Const VT_BYREF As Long = &H4000
Private m_remoteMemory As REMOTE_MEMORY
'*******************************************************************************
'Read/Write a Byte from/to memory
'*******************************************************************************
#If VBA7 Then
Public Property Get MemByte(ByVal memAddress As LongPtr) As Byte
#Else
Public Property Get MemByte(ByVal memAddress As Long) As Byte
#End If
DeRefMem m_remoteMemory, memAddress, vbByte
MemByte = m_remoteMemory.memValue
End Property
#If VBA7 Then
Public Property Let MemByte(ByVal memAddress As LongPtr, ByVal newValue As Byte)
#Else
Public Property Let MemByte(ByVal memAddress As Long, ByVal newValue As Byte)
#End If
DeRefMem m_remoteMemory, memAddress, vbByte
LetByRef(m_remoteMemory.memValue) = newValue
End Property
'*******************************************************************************
'Read/Write 2 Bytes (Integer) from/to memory
'*******************************************************************************
#If VBA7 Then
Public Property Get MemInt(ByVal memAddress As LongPtr) As Integer
#Else
Public Property Get MemInt(ByVal memAddress As Long) As Integer
#End If
DeRefMem m_remoteMemory, memAddress, vbInteger
MemInt = m_remoteMemory.memValue
End Property
#If VBA7 Then
Public Property Let MemInt(ByVal memAddress As LongPtr, ByVal newValue As Integer)
#Else
Public Property Let MemInt(ByVal memAddress As Long, ByVal newValue As Integer)
#End If
DeRefMem m_remoteMemory, memAddress, vbInteger
LetByRef(m_remoteMemory.memValue) = newValue
End Property
'*******************************************************************************
'Read/Write 4 Bytes (Long) from/to memory
'*******************************************************************************
#If VBA7 Then
Public Property Get MemLong(ByVal memAddress As LongPtr) As Long
#Else
Public Property Get MemLong(ByVal memAddress As Long) As Long
#End If
DeRefMem m_remoteMemory, memAddress, vbLong
MemLong = m_remoteMemory.memValue
End Property
#If VBA7 Then
Public Property Let MemLong(ByVal memAddress As LongPtr, ByVal newValue As Long)
#Else
Public Property Let MemLong(ByVal memAddress As Long, ByVal newValue As Long)
#End If
DeRefMem m_remoteMemory, memAddress, vbLong
LetByRef(m_remoteMemory.memValue) = newValue
End Property
'*******************************************************************************
'Read/Write 8 Bytes (LongLong) from/to memory
'*******************************************************************************
#If VBA7 Then
Public Property Get MemLongPtr(ByVal memAddress As LongPtr) As LongPtr
#Else
Public Property Get MemLongPtr(ByVal memAddress As Long) As Long
#End If
DeRefMem m_remoteMemory, memAddress, vbLongPtr
MemLongPtr = m_remoteMemory.memValue
End Property
#If VBA7 Then
Public Property Let MemLongPtr(ByVal memAddress As LongPtr, ByVal newValue As LongPtr)
#Else
Public Property Let MemLongPtr(ByVal memAddress As Long, ByVal newValue As Long)
#End If
#If Win64 Then
'Cannot set Variant/LongLong ByRef so we use a Currency instead
Const currDivider As Currency = 10000
DeRefMem m_remoteMemory, memAddress, vbCurrency
LetByRef(m_remoteMemory.memValue) = CCur(newValue / currDivider)
#Else
MemLong(memAddress) = newValue
#End If
End Property
'*******************************************************************************
'Redirects the rm.memValue Variant to the new memory address so that the value
' can be read ByRef
'*******************************************************************************
Private Sub DeRefMem(ByRef rm As REMOTE_MEMORY, ByRef memAddress As LongPtr, ByRef vt As VbVarType)
With rm
If Not .isInitialized Then
'Link .remoteVt to the first 2 bytes of the .memValue Variant
.remoteVT = VarPtr(.memValue)
CopyMemory .remoteVT, vbInteger + VT_BYREF, 2
'
.isInitialized = True
End If
'Link .memValue to the desired address
.memValue = memAddress
LetByRef(.remoteVT) = vt + VT_BYREF 'Faster than: CopyMemory .memValue, vt + VT_BYREF, 2
End With
End Sub
'*******************************************************************************
'Utility for updating remote values that have the VT_BYREF flag set
'*******************************************************************************
Private Property Let LetByRef(ByRef v As Variant, ByRef newValue As Variant)
v = newValue
End Property
#If VBA7 Then
Public Function UnsignedAddition(ByVal val1 As LongPtr, ByVal val2 As LongPtr) As LongPtr
#Else
Public Function UnsignedAddition(ByVal val1 As Long, ByVal val2 As Long) As Long
#End If
'The minimum negative integer value of a Long Integer in VBA
#If Win64 Then
Const minNegative As LongLong = &H8000000000000000^ '-9,223,372,036,854,775,808 (dec)
#Else
Const minNegative As Long = &H80000000 '-2,147,483,648 (dec)
#End If
'
If val1 > 0 Then
If val2 > 0 Then
'Overflow could occur
If (val1 + minNegative + val2) < 0 Then
'The sum will not overflow
UnsignedAddition = val1 + val2
Else
'Example for Long data type (x32):
' &H7FFFFFFD + &H0000000C = &H80000009
' 2147483645 + 12 = -2147483639
UnsignedAddition = val1 + minNegative + val2 + minNegative
End If
Else 'Val2 <= 0
'Sum cannot overflow
UnsignedAddition = val1 + val2
End If
Else 'Val1 <= 0
If val2 > 0 Then
'Sum cannot overflow
UnsignedAddition = val1 + val2
Else 'Val2 <= 0
'Overflow could occur
On Error GoTo ErrorHandler
UnsignedAddition = val1 + val2
End If
End If
Exit Function
ErrorHandler:
Err.Raise 6, MODULE_NAME & ".UnsignedAddition", "Overflow"
End Function
</code></pre>
<p><strong>Demo</strong></p>
<p>For demos that are testing speed go to the <a href="https://github.com/cristianbuse/VBA-MemoryTools/blob/master/Code%20Modules/Demo%20Modules/DemoLibMemory.bas" rel="nofollow noreferrer">Demo module</a> in the above mentioned repository.</p>
<pre><code>Sub DemoMem()
#If VBA7 Then
Dim ptr As LongPtr
#Else
Dim ptr As Long
#End If
Dim i As Long
Dim arr() As Variant
ptr = ObjPtr(Application)
'
'Read Memory using MemByte
ReDim arr(0 To PTR_SIZE - 1)
For i = LBound(arr) To UBound(arr)
arr(i) = MemByte(UnsignedAddition(ptr, i))
Next i
Debug.Print Join(arr, " ")
'
'Read Memory using MemInt
ReDim arr(0 To PTR_SIZE / 2 - 1)
For i = LBound(arr) To UBound(arr)
arr(i) = MemInt(UnsignedAddition(ptr, i * 2))
Next i
Debug.Print Join(arr, " ")
'
'Read Memory using MemLong
ReDim arr(0 To PTR_SIZE / 4 - 1)
For i = LBound(arr) To UBound(arr)
arr(i) = MemLong(UnsignedAddition(ptr, i * 4))
Next i
Debug.Print Join(arr, " ")
'
'Read Memory using MemLongPtr
Debug.Print MemLongPtr(ptr)
'
'Write Memory using MemByte
ptr = 0
MemByte(VarPtr(ptr)) = 24
Debug.Assert ptr = 24
MemByte(UnsignedAddition(VarPtr(ptr), 2)) = 24
Debug.Assert ptr = 1572888
'
'Write Memory using MemInt
ptr = 0
MemInt(UnsignedAddition(VarPtr(ptr), 2)) = 300
Debug.Assert ptr = 19660800
'
'Write Memory using MemLong
ptr = 0
MemLong(VarPtr(ptr)) = 77777
Debug.Assert ptr = 77777
'
'Write Memory using MemLongPtr
MemLongPtr(VarPtr(ptr)) = ObjPtr(Application)
Debug.Assert ptr = ObjPtr(Application)
End Sub
</code></pre>
<p><strong>Decisions</strong></p>
<p>For those that are not aware, a LongLong integer cannot be modified ByRef if it is passed inside a Variant. Example:</p>
<pre><code>#If Win64 Then
Private Sub DemoByRefLongLong()
Dim ll As LongLong
EditByRefLLVar ll, 1^
End Sub
Private Sub EditByRefLLVar(ByRef ll As Variant, ByRef newValue As LongLong)
ll = newValue 'Error 458 - Variable uses an Automation type not supported...
End Sub
#End If
</code></pre>
<p>Since I couldn't use the same approach I've used for Byte, Integer and Long I've finally decided to go for the Currency approach because it was the cleanest and fastest. A Currency variable is stored using 8 Bytes in an integer format, scaled by 10,000 resulting in a fixed point number. So, it was quite easy to use currency instead of <code>LongLong</code> (see the <code>MemLongPtr</code> Let property).</p>
<p>Another approach is to use a Double but looks absolutely horrendous (and is slower) and needs a second <code>REMOTE_MEMORY</code> variable:</p>
<pre><code>#If VBA7 Then
Public Property Let MemLongPtr(ByVal memAddress As LongPtr, ByVal newValue As LongPtr)
#Else
Public Property Let MemLongPtr(ByVal memAddress As Long, ByVal newValue As Long)
#End If
#If Win64 Then
Static rm As REMOTE_MEMORY
With rm
If Not .isInitialized Then
'Link .remoteVt to the first 2 bytes of the .memValue Variant
.remoteVT = VarPtr(.memValue)
CopyMemory .remoteVT, vbInteger + VT_BYREF, 2
'
.isInitialized = True
End If
.memValue = newValue
LetByRef(.remoteVT) = vbDouble
End With
DeRefMem m_remoteMemory, memAddress, vbDouble
LetByRef(m_remoteMemory.memValue) = rm.memValue
#Else
MemLong(memAddress) = newValue
#End If
End Property
</code></pre>
<p>Another approach is to write two Longs:</p>
<pre><code>#If VBA7 Then
Public Property Let MemLongPtr(ByVal memAddress As LongPtr, ByVal newValue As LongPtr)
#Else
Public Property Let MemLongPtr(ByVal memAddress As Long, ByVal newValue As Long)
#End If
#If Win64 Then
MemLong(memAddress) = LoLong(newValue)
MemLong(UnsignedAddition(memAddress, 4)) = HiLong(newValue)
#Else
MemLong(memAddress) = newValue
#End If
End Property
#If Win64 Then
Private Function HiLong(ByVal ll As LongLong) As Long
HiLong = VBA.Int(ll / &H100000000^)
End Function
Private Function LoLong(ByVal ll As LongLong) As Long
If ll And &H80000000^ Then
LoLong = CLng(ll And &H7FFFFFFF^) Or &H80000000
Else
LoLong = CLng(ll And &H7FFFFFFF^)
End If
End Function
#End If
</code></pre>
<p>This approach looks dangerous because it might change half of a pointer first and by the time the second half is changed, some other code uses that pointer to do something that will likely result in a crash or data corruption.</p>
<p>Another decision was to leave the <code>DeRefMem</code> method as a Sub. Consider the current code (excluding the VBA7 declarations):</p>
<pre><code>Public Property Get MemByte(ByVal memAddress As LongPtr) As Byte
DeRefMem m_remoteMemory, memAddress, vbByte
MemByte = m_remoteMemory.memValue
End Property
Public Property Let MemByte(ByVal memAddress As LongPtr, ByVal newValue As Byte)
DeRefMem m_remoteMemory, memAddress, vbByte
LetByRef(m_remoteMemory.memValue) = newValue
End Property
Private Sub DeRefMem(ByRef rm As REMOTE_MEMORY, ByRef memAddress As LongPtr, ByRef vt As VbVarType)
With rm
If Not .isInitialized Then
.isInitialized = True
'Link .remoteVt to the first 2 bytes of the .memValue Variant
.remoteVT = VarPtr(.memValue)
CopyMemory .remoteVT, vbInteger + VT_BYREF, 2
End If
.memValue = memAddress
LetByRef(.remoteVT) = vt + VT_BYREF
End With
End Sub
</code></pre>
<p>and now the Function equivalent:</p>
<pre><code>Public Property Get MemByte(ByVal memAddress As LongPtr) As Byte
MemByte = DeRefMem(memAddress, vbByte).memValue
End Property
Public Property Let MemByte(ByVal memAddress As LongPtr, ByVal newValue As Byte)
LetByRef(DeRefMem(memAddress, vbByte).memValue) = newValue
End Property
Private Function DeRefMem(ByRef memAddress As LongPtr, ByRef vt As VbVarType) As REMOTE_MEMORY
Static rm As REMOTE_MEMORY
With rm
If Not .isInitialized Then
.isInitialized = True
'Link .remoteVt to the first 2 bytes of the .memValue Variant
.remoteVT = VarPtr(.memValue)
CopyMemory .remoteVT, vbInteger + VT_BYREF, 2
End If
.memValue = memAddress
LetByRef(.remoteVT) = vt + VT_BYREF
End With
DeRefMem = rm
End Function
</code></pre>
<p>The <em>Function</em> approach looks definitely more readable. The problem is that it is 2-3 times slower than the <em>Sub</em> equivalent. Since this code will act as a library, I went with the faster approach.</p>
<hr />
<p>I would be very grateful for suggestions that could improve the code.<br />
Have I missed anything obvious? Are there any other useful methods that should be part of such a 'Memory' library (e.g. like I've added <code>VarPtrArray</code> and <code>UnsignedAddition</code>)?</p>
<p>I should also mention that although I wrote the necessary conditional compilations to make the code work for VB6, I cannot test it on VB6 because I don't have VB6 available.</p>
<p><strong>Edit #1</strong></p>
<p>The above has been extensively updated at the mentioned repository on GitHub at <a href="https://github.com/cristianbuse/VBA-MemoryTools" rel="nofollow noreferrer">VBA-MemoryTools</a>.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-01T12:26:50.260",
"Id": "498463",
"Score": "0",
"body": "Why is the Function slower than the Sub?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-01T14:28:07.173",
"Id": "498472",
"Score": "1",
"body": "@Greedo Mainly because of the return value. If the return is just a Variant it seems to be 1.5x slower but that doesn't work for ByRef Variants so the return must be the whole UDT which is at least 2x slower. I've tested with multiples of 10 starting from 1000 to 10 milions (iterations) and it seems to be consistently slower. Quite unfortunate as it was definitely more elegant to have a Function instead. I assume the extra stack space and copy result operation are the reason"
}
] |
[
{
"body": "<p>I have a very curious result of running the demo.</p>\n<p>-------------------- Host info --------------------<br />\nOS: Microsoft Windows NT 10.0.17763.0, x64</p>\n<p><strong>VBA7-x64</strong><br />\nHost Product: Microsoft Office 2016 x64<br />\nHost Version: 16.0.4266.1001<br />\nHost Executable: EXCEL.EXE</p>\n<p><strong>VBA6-x32</strong><br />\nHost Product: Microsoft Office XP x86<br />\nHost Version: 10.0.6501<br />\nHost Executable: EXCEL.EXE</p>\n<hr />\n<p>Immediate output after running the demo routine.</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Operation</th>\n<th style=\"text-align: center;\">Method</th>\n<th style=\"text-align: center;\">Times</th>\n<th style=\"text-align: center;\">time, s / VBA6-x32</th>\n<th style=\"text-align: center;\">time, s / VBA7-x64</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Copy <Byte></td>\n<td style=\"text-align: center;\">By Ref</td>\n<td style=\"text-align: center;\">10<sup>6</sup></td>\n<td style=\"text-align: center;\">0.383</td>\n<td style=\"text-align: center;\">0.414</td>\n</tr>\n<tr>\n<td>Copy <Byte></td>\n<td style=\"text-align: center;\">By API</td>\n<td style=\"text-align: center;\">10<sup>6</sup></td>\n<td style=\"text-align: center;\">0.023</td>\n<td style=\"text-align: center;\">2.062</td>\n</tr>\n<tr>\n<td>Copy <Integer></td>\n<td style=\"text-align: center;\">By Ref</td>\n<td style=\"text-align: center;\">10<sup>6</sup></td>\n<td style=\"text-align: center;\">0.352</td>\n<td style=\"text-align: center;\">0.375</td>\n</tr>\n<tr>\n<td>Copy <Integer></td>\n<td style=\"text-align: center;\">By API</td>\n<td style=\"text-align: center;\">10<sup>6</sup></td>\n<td style=\"text-align: center;\">0.031</td>\n<td style=\"text-align: center;\">2.047</td>\n</tr>\n<tr>\n<td>Copy <Long></td>\n<td style=\"text-align: center;\">By Ref</td>\n<td style=\"text-align: center;\">10<sup>6</sup></td>\n<td style=\"text-align: center;\">0.781</td>\n<td style=\"text-align: center;\">0.375</td>\n</tr>\n<tr>\n<td>Copy <Long></td>\n<td style=\"text-align: center;\">By API</td>\n<td style=\"text-align: center;\">10<sup>6</sup></td>\n<td style=\"text-align: center;\">0.062</td>\n<td style=\"text-align: center;\">2.047</td>\n</tr>\n<tr>\n<td>Copy <LongLong></td>\n<td style=\"text-align: center;\">By Ref</td>\n<td style=\"text-align: center;\">10<sup>6</sup></td>\n<td style=\"text-align: center;\">0.508</td>\n<td style=\"text-align: center;\">0.484</td>\n</tr>\n<tr>\n<td>Copy <LongLong></td>\n<td style=\"text-align: center;\">By API</td>\n<td style=\"text-align: center;\">10<sup>6</sup></td>\n<td style=\"text-align: center;\">0.031</td>\n<td style=\"text-align: center;\">2.055</td>\n</tr>\n<tr>\n<td>Dereferenced an Object</td>\n<td style=\"text-align: center;\">-</td>\n<td style=\"text-align: center;\">10<sup>6</sup></td>\n<td style=\"text-align: center;\">0.156</td>\n<td style=\"text-align: center;\">0.188</td>\n</tr>\n</tbody>\n</table>\n</div><hr />\n<p>There is a minor bug in the demo code. You have:</p>\n<pre class=\"lang-vb prettyprint-override\"><code>t = Timer\nFor i = 1 To LOOPS\n CopyMemory x1, x2, 1\nNext i\n</code></pre>\n<p>should be</p>\n<pre class=\"lang-vb prettyprint-override\"><code>Dim ByteCount As Long\nByteCount = Len(x1)\nt = Timer\nFor i = 1 To LOOPS\n CopyMemory x1, x2, ByteCount\nNext i\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-14T08:41:28.403",
"Id": "533100",
"Score": "1",
"body": "Interesting. I didn't have VBA6 to test with. It seems that the API is super fast. However on VBA7 x32 I get the worst results using the API. SO, I guess for VBA7 is simply faster to use the ByRef approach instead of the API. BTW, I am due to push a faster version to GitHub next week."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-14T12:26:18.893",
"Id": "533108",
"Score": "0",
"body": "@CristianBuse, see updated comment regarding a minor bug in the demo."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-14T13:54:40.947",
"Id": "533123",
"Score": "0",
"body": "Thanks! I will review next week."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-22T12:13:44.860",
"Id": "533673",
"Score": "0",
"body": "[Here](https://i.stack.imgur.com/7mM4R.png) are the results I get when running the demo. As you can see on my x32 VBA7 the API is completely unusable"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-22T14:45:26.850",
"Id": "533700",
"Score": "1",
"body": "BTW, thanks for looking into this. +1 Helpful to see that VBA6 is not affected."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-13T20:13:59.960",
"Id": "270053",
"ParentId": "252659",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T14:48:41.087",
"Id": "252659",
"Score": "6",
"Tags": [
"vba",
"memory-management"
],
"Title": "Fast Native Memory Manipulation in VBA"
}
|
252659
|
<p>I am using following script to plot cluster populations using two lists contained x and y data</p>
<pre><code># calculate clusters using encore method
cluster = encore.cluster(u, select="all", superposition=False, method=encore.DBSCAN(eps=1))
# make list of population of each cluster;
cluster_sizes= [len(c) for c in cluster.clusters]
# make list of the cluster number;
cluster_numbers=[x+1 for x in range(0,len(cluster_sizes))]
# plot data
plt.bar(cluster_numbers, cluster_sizes)
plt.title('Cluster Populations')
plt.grid(True)
#plt.style.use('ggplot')
plt.savefig(f'clusters.png')
plt.close()
</code></pre>
<p>The problem that sometimes on the resulted bar plot the values are ranged by 0.5 along both X and Y (see the enclosed picture as the example). How I could plot only integers along the both axes? In my example graph the X should be scalled from 0 to 20 (avoiding 0.5 spacings) and the Y from 0 to 18 (thus <a href="https://i.stack.imgur.com/bdhvF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bdhvF.png" alt="enter image description here" /></a>avoiding these unused 0.5 spacings)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T13:14:13.073",
"Id": "498051",
"Score": "3",
"body": "Welcome to the Code Review Community where we review code that is working as expected that you have written. This question is off-topic because the code is not working as expected. As indicated on your [previous question](https://codereview.stackexchange.com/questions/252654/python-stacking-images) please read the [Code Review Guidelines for Asking](https://codereview.stackexchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<p>Use <code>plt.xticks</code> - <a href=\"https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.xticks.html\" rel=\"nofollow noreferrer\">https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.xticks.html</a>.</p>\n<p>One may to <code>xticks</code> <code>np.arange(len(cluster.clusters))</code> as an argument</p>\n<p>And for <code>yticks</code> it works in a same fashion -if you pass <code>np.arange(int(max(cluster_sizes)))</code>, there will be integer ticks along the <code>y</code>-axis</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T09:32:11.660",
"Id": "498031",
"Score": "0",
"body": "Thank you very much for this info! Generally it may work very good for a particular graph, but could not be applied in the script producing many different bar plots (with broad range of values on X and Y). For example, in the case of many bars on the same plot, the values of X tend to overlap. By contrast, if there is only one bar (1 cluster) it looks like a big square, then an individual bar :-) I tried to add step argument for both xticks and yticks to customize values along both axes but it also could not be applied for many different graphs ... are there other possibilities?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T12:18:13.263",
"Id": "498047",
"Score": "0",
"body": "@MaîtreRenard I am not aware of any adaptive ways for formatting, the more flexible thing is `major formatter` https://matplotlib.org/3.1.1/gallery/ticks_and_spines/custom_ticker1.html#sphx-glr-gallery-ticks-and-spines-custom-ticker1-py"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T13:16:10.463",
"Id": "498053",
"Score": "1",
"body": "Decent answer for Stack Overflow, we don't answer `how to` questions on Code Review, the code has to be working as expected."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T16:16:08.860",
"Id": "252663",
"ParentId": "252660",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T15:00:24.647",
"Id": "252660",
"Score": "0",
"Tags": [
"python",
"matplotlib"
],
"Title": "Matplot lib : scalling of the axes on bar plot"
}
|
252660
|
<p>I have a list of <code>N</code> integers and I iteratively take two integers at random, which are not at the same position in the list and uniformly recombine their binary representation, e.g. in <code>intList = [1,4,1,5]</code> <code>(N=4)</code> the number on the second and third position is chosen, aka <code>4 & 1</code>, and their binary represenations <code>4=100</code> & <code>1=001</code> is uniformly recombined. Uniformly recombined means that I chose either the <code>1 or the 0</code> of the first position, one of the two <code>0's</code> of the second position and either the <code>0 or 1</code> of the third position. This could result in 000 or 101 or 100 or 001. The result is saved as integer in the list. In each iteration I do this recombination for all <code>N</code> integers. This happens in a function with a numba decorator. My code is:</p>
<pre><code>@nb.njit()
def comb():
iterations = 100000
N = 1000
intList = list(range(N)) # this is just an example of possible integer lists
l = 10 # length of the largest binary representation.
intList_temp = [0]*N
for _ in range(iterations):
for x3 in range(N):
intList_temp[x3] = intList[x3]
for x3 in range(N):
randint1 = random.randint(0, N - 1)
randint2 = random.randint(0, N - 1)
while randint1 == randint2:
randint1 = random.randint(0, N - 1)
randint2 = random.randint(0, N - 1)
a = intList[randint1]
b = intList[randint2]
c = a ^ ((a ^ b) & random.randint(0, (1 << l) - 1))
intList_temp[x3] = c
for x3 in range(N):
intList[x3] = intList_temp[x3]
return intList
print(timeit(lambda: comb(), number=1))
>>>2.59s
</code></pre>
<p>My question is, can this be improved?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T17:10:24.257",
"Id": "497921",
"Score": "2",
"body": "Are you sure the code works? `(1 << l)` throws `l is undefined`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T18:00:09.287",
"Id": "497927",
"Score": "0",
"body": "my mistake, `l` should be the length of the binary representation of the largest integer. If you choose `l` to be 10 in my example code it should work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T18:05:40.430",
"Id": "497929",
"Score": "0",
"body": "The numbers in intList are chosen, such that they are equal or smaller than `l` but I think that is not important."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T15:53:10.980",
"Id": "498071",
"Score": "0",
"body": "asked this on the answer I took down, is the output supposed to be a list of the same number repeated 1000 times?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T16:00:40.210",
"Id": "498074",
"Score": "0",
"body": "In each iteration, we choose for each entry two random variables, which are recombined as described above. The update process is sequential and that is the reason why I create intList_temp. Did I make myself more clear? Sorry for the misunderstanding."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T16:05:50.167",
"Id": "498075",
"Score": "0",
"body": "Actually sequential might be the wrong word for that but I hope it is still clear. Let me know otherwise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T16:07:51.313",
"Id": "498076",
"Score": "0",
"body": "I'm asking if the expected output of that process is supposed to a list repeating a single number. For example I just copy-pasted it into a fresh file and when I run `comb()` it returns `1013` repeated 1000 times"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T16:12:11.247",
"Id": "498077",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/116690/discussion-between-coupcoup-and-highwayjohn)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T16:18:32.690",
"Id": "498078",
"Score": "0",
"body": "Okay I understand. The only reason you get a single number 1000 times is, that the process was repeated 100000 times and by chance all other numbers got lost. In my code other things are also happening in each iteration and then the result is not like this."
}
] |
[
{
"body": "<p>One obvious improvement is the repeated calculations of <code>N-1</code> and <code>1<<l - 1</code> -- those can be calculated once outside the loop and put in variables.</p>\n<p>Another wasted effort is the triple initialization of <code>intList_temp</code>. There is no reason to set it to 0, set it to <code>intList</code>, then set it to the actually calculated values.</p>\n<p>Also that <code>while</code> loop to ensure the values are distinct is unnecessary. There's plenty of code out there to generate two distinct random numbers with just two random calls. (Hint: if the first random number is chosen arbitrarily, how many valid choices are there for the second random number?)</p>\n<p>But I don't think either of these will make much of a difference in speed.</p>\n<p>Have you profiled this?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T09:25:21.117",
"Id": "498030",
"Score": "0",
"body": "Predefining N-1 and 1<<l - 1 makes no measurable difference. In Numba I think there is no faster way to copy a list. Also the possibilites to generate two random numbers is limited."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T13:11:43.930",
"Id": "498050",
"Score": "0",
"body": "How does profiling works?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T01:28:36.267",
"Id": "498121",
"Score": "0",
"body": "https://en.wikipedia.org/wiki/Profiling_(computer_programming) https://toucantoco.com/en/tech-blog/tech/python-performance-optimization https://stackoverflow.com/questions/55213687/python-how-to-profile-code-written-with-numba-njit-decorators"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T19:34:47.160",
"Id": "252670",
"ParentId": "252665",
"Score": "3"
}
},
{
"body": "<pre><code>for x3 in range(N):\n intList_temp[x3] = intList[x3]\n</code></pre>\n<p>and</p>\n<pre><code>for x3 in range(N):\n intList[x3] = intList_temp[x3]\n</code></pre>\n<p>look pretty messy, I'm not proficient in python, but there should be an implementation of copying a vector much faster.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T22:34:42.403",
"Id": "497968",
"Score": "1",
"body": "Which one is faster in numba?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T09:23:19.560",
"Id": "498029",
"Score": "0",
"body": "`intList_temp = intList[:]` also does the job but seems to be a tiny bit slower"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T20:29:55.150",
"Id": "252673",
"ParentId": "252665",
"Score": "2"
}
},
{
"body": "<p>No significant performance improvement but cleaner code.</p>\n<p>Because <code>temp_list</code> is overwritten element-wise you can create it once and then leave it. At the end of each iteration you can then copy the entire list into <code>int_list</code> for the next iteration.</p>\n<p>Similarly you can simplify creating the random ints <code>a</code> and <code>b</code> a bit. There are a lot of ways that get close to this in numpy but nothing I can find that beats the naive sampling directly works with numba and numba beats any overall solution I can think of without it.</p>\n<p>Unfortunately (or maybe fortunately depending on your view), the numba compiler is compiling it down to the best solution I can think of for both your original version and this. Only difference is readabilitiy:</p>\n<pre><code>@nb.njit()\ndef comb(int_list, l, iterations):\n n = len(int_list)\n\n temp_list = int_list\n\n for _ in range(iterations):\n for i in range(n):\n a, b = 0, 0\n while a == b:\n a = random.randint(0, n - 1)\n b = random.randint(0, n - 1)\n\n temp_list[i] = a ^ ((a ^ b) & random.randint(0, l))\n\n int_list = temp_list\n\n return int_list\n\nprint(timeit(lambda: comb(list(range(1000)), (1 << 10) - 1, 100000), number=10))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T22:29:55.847",
"Id": "497967",
"Score": "0",
"body": "Thanks for the help! The numba decorator is kinda necessary, since other stuff is also happening in the function which would be difficult to optimize without numba. Unfortunately Random.sample does not work with numba. Do you know an efficient workaround for that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T22:38:16.757",
"Id": "497969",
"Score": "0",
"body": "Do you mean the function that calls `comb` needs numba to work? I can get it working with numba or multiprocessing, another speedup approach, but both were slower than the solution I provided when I tested them. If it's faster not to use numba do you still need it for this particular function? A 6x speed up seems worth dropping it if possible"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T22:43:22.190",
"Id": "497970",
"Score": "0",
"body": "Yes, unfortunately at the current state of my code I need comb to work with numba. Could you maybe add a version for that? Maybe I can make use of the non numba code later. Generally speaking, for me it is strange that it is slower with the numba decorator."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T22:47:56.410",
"Id": "497971",
"Score": "0",
"body": "Yeah, overall my results with numba seem to be hit or miss. Simple code tends to beat optimized complex code in my experience. I can add in the numba version for you see. It's possible your overall code would benefit from dropping numba and reducing complexity but it'd be up to you to decide if refactoring is worth it or not, especially without a guarantee of improved performance. I will say your native solution without numba was super slow though, 466 seconds vs .4"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T22:54:28.287",
"Id": "497973",
"Score": "1",
"body": "I probably really have to think about it then. It’s always interesting to see the possible performance jumps in python. For now it would be really helpful for me if you would add a numba version."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T23:36:24.117",
"Id": "497977",
"Score": "0",
"body": "just added the numba version. Cleaner but no faster than your original"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T07:58:51.417",
"Id": "498018",
"Score": "0",
"body": "Thanks a lot!! I use numba 0.51 and on my machine your numba version (0.43s) and your non-numba version (0.38s) are both much faster and comparable in time with each other!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T08:45:40.077",
"Id": "498024",
"Score": "0",
"body": "One more question: In your code, it seems to me, that in each iteration only two numbers are chosen to recombine. Is that correct? In my code, in each iteration, for all N numbers we choose two random numbers which are recombined."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T15:21:13.397",
"Id": "498067",
"Score": "0",
"body": "In that case your code would actually be much slower :/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T15:31:35.990",
"Id": "498070",
"Score": "0",
"body": "Yeah, I'm i've been messing with it a bit this morning. The two in my code are equivalent and show numba doesn't always beet a native solution but I'm I'll pull the answer down until it beats your benchmark. BTW is your code suppose to return a list of the same number repeated 1000 times? I was looking at the len of the output"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T20:34:55.097",
"Id": "252674",
"ParentId": "252665",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "252674",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T16:44:22.767",
"Id": "252665",
"Score": "2",
"Tags": [
"python",
"performance",
"numba"
],
"Title": "Iterative uniform recombination of integer lists in python with numba"
}
|
252665
|
<p>I have a function that gets a string and prints it as a message. Then, it reads the text from <code>stdin</code>, saves it in a pointer and sends it back:</p>
<pre><code>char *getString(char *queryText){
char buffer[BUFFERSIZE];
char *temp;
printf("%s", queryText);
fgets(buffer, BUFFERSIZE, stdin);
//clears \n at the end of the line
if ((strlen(buffer) > 0) && (buffer[strlen(buffer) - 1] == '\n'))
buffer[strlen(buffer) - 1] = '\0';
temp = (char*)malloc(strlen(buffer));
//if(temp == NULL)? , checked each time in the calling function
strcpy(temp, buffer);
return temp;}
</code></pre>
<p>I use it every time I need to get an input from the user that needs to be saved dynamically. For example, in this function that adds a name to the <code>char* contacts</code> (that's just a part of it):</p>
<pre><code>int add(char *contacts[], int *nextAvailableP){
if (*nextAvailableP > N-3){
printf("Unable to add a contact, not enough memory\n");
return FALSE;
}
int numberOfMails = 0;
//receives the name, and saves it at the right cell
contacts[*nextAvailableP] = getString("Enter the contact name\n");
if(contacts[*nextAvailableP] == NULL){
printf("Malloc failed\n");
return FALSE;
}
(*nextAvailableP)++;
</code></pre>
<p>My questions are:</p>
<ol>
<li>Is this really doing what i think it does?</li>
<li>Do I need to check if <code>malloc</code> succeeded in <code>char *getString(char *queryText)</code> or the way it is right now?</li>
<li>I'm just changing the pointer to the memory I've allocated, right? So I don't have to free it until I'm deleting the name from the array.</li>
<li>Is it a good habit at all?</li>
</ol>
<h2>Whole Program</h2>
<p>For reference, here is the whole program.</p>
<p>My assigment was to write a program that maintains a list of contacts and their mail addresses. I had to use <code>char *contacts[N];</code> and a variable that saves the index of the next available cell in the array.</p>
<p>For each contact the cell at index:</p>
<ul>
<li><code>i</code> will save his name</li>
<li><code>i+1</code> will save the number of mails (not known in advance)</li>
<li><code>i+2</code> and beyond the mail addresses (not any format required)</li>
</ul>
<p>I also had to</p>
<pre><code>#define TRUE 1
#define FALSE 0
</code></pre>
<p>The program will present the user the following menu:</p>
<pre><code>Choose an option:
1. Enter new contact (Had to check that there is enough room for the minimal contact)
2. Search contact
3. Delete mail from contact (only if he has more than 1 email adress)
4. Delete Contact (Delete everythings about him, and rearrange the array)
5. Print
6. Exit
</code></pre>
<p>We can assume that the maximum length of a name or a mail will be 50, and that the inputs are valid.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
const int N = 100;
const int BUFFERSIZE = 50;
void printMenu();
int add(char* contacts[], int* nextAvailableP);
char *getString(char *queryText);
void deleteMailAddress(char* contacts[], int* nextAvailableP);
int existReturnIndex(char* contacts[], int* nextAvailableP);
void deleteContact(char* contacts[], int* nextAvailableP);
void printArray(char* contacts[], int* nextAvailable);
void freeMemory(char* contacts[], int* nextAvailable);
int main()
{
char *contacts[N];
int nextAvailable = 0;
int quit = FALSE;
int option;
printMenu();
while(quit == FALSE){
scanf(" %d", &option);
getchar();
switch(option){
case 1:
add(contacts, &nextAvailable);
break;
case 2:
find(contacts, &nextAvailable);
break;
case 3:
deleteMailAddress(contacts, &nextAvailable);
break;
case 4:
deleteContact(contacts, &nextAvailable);
break;
case 5:
printArray(contacts, &nextAvailable);
break;
case 6:
freeMemory(contacts, &nextAvailable);
quit = TRUE;
break;
default:
printf("Enter a valid number between 1 to 6\n");
}
printMenu();
}
}
//Prints the menu
void printMenu(){
printf("Choose an option \n1. Enter new contact.\n2. Search contact.\n3. Delete mail from contact.\n4. Delete Contact.\n5. Print.\n6. Exit.\n\n");
}
void freeMemory(char *contacts[], int* nextAvailableP){
int i;
for(i=0; i<*nextAvailableP; i++){
free(contacts[i]);
}
*nextAvailableP = 0;
}
void printArray(char *contacts[], int* nextAvailableP){
int i;
for(i=0; i<*nextAvailableP;){
printf("%s:\n", contacts[i++]);
int tempNumOfMails = atoi(contacts[i]);
printXmailsNumberd(contacts, tempNumOfMails, ++i);
i+=tempNumOfMails;
}
}
//Gets a contact name and deletes it from the list if he exists, rearranging the array afterwards
void deleteContact(char *contacts[], int *nextAvailableP){
int i = existReturnIndex(contacts, nextAvailableP);
if(i != -1){
int numberOfMails = atoi(contacts[i+1]);
for(i; i<*nextAvailableP-(numberOfMails+2); i++){
strcpy(contacts[i], contacts[i+numberOfMails+2]);
}
(*nextAvailableP)--;
while(*nextAvailableP>=i){
free(contacts[*nextAvailableP]);
(*nextAvailableP)--;
}
}
else{
printf("Not on the list\n");
}
}
//Gets the array, the number of mails to print and their first index and prints them numberd
void printXmailsNumberd(char* contacts[], int X, int beginIndex){
int j;
for(j=0; j<X; j++,beginIndex++){
printf("%d. %s\n",j+1, contacts[beginIndex]);
}
printf("\n");
}
//Deletes a single mail address from a given user, if he exists, and rearrange the array afterwards
void deleteMailAddress(char* contacts[], int* nextAvailableP){
int i = existReturnIndex(contacts, nextAvailableP);
if(i != -1){
i++;
int numberOfMails = atoi(contacts[i]);
int firstMailIndex = ++i;
if(numberOfMails > 1){
printXmailsNumberd(contacts, numberOfMails, i);
printf("Choose the number of one of the above\n");
int mailToDelete;
scanf(" %d", &mailToDelete);
for(i=mailToDelete+firstMailIndex-1; i<*nextAvailableP-1; i++){
strcpy(contacts[i], contacts[i+1]);
}
itoa((numberOfMails-1),contacts[(firstMailIndex-1)], 10);
(*nextAvailableP)--;
free(contacts[*nextAvailableP]);
}
else{
printf("Only one address available, you're not allowed to delete it\n");
}
}
else{
printf("Not on the list\n");
}
}
//Checks if a name exits in the array and return his index
int existReturnIndex(char* contacts[], int* nextAvailableP){
char *name = getString("Enter the contact name\n");
if(name == NULL){
printf("Malloc failed\n");
return FALSE;
}
int i;
for(i=0; i<*nextAvailableP; i++){
if(strcmp(contacts[i],name) == 0){
return i;
}
}
free(name);
return -1;
}
//prints the name of the person the user was looking for, and his mails, if he is on the list
void find(char *contacts[], int *nextAvailableP){
int numberOfMails;
int i = existReturnIndex(contacts, nextAvailableP);
if(i != -1){
i++;
numberOfMails = atoi(contacts[i++]);
printf("\n%s:\n", contacts[i-2]);
printXmailsNumberd(contacts, numberOfMails, i);
}
else{
printf("Not on the list\n");
}
}
//Adds a contact to the list
int add(char *contacts[], int *nextAvailableP){
if (*nextAvailableP > N-3){
printf("Unable to add a contact, not enough memory\n");
return FALSE;
}
int numberOfMails = 0;
//receives the name, and saves it at the right cell
contacts[*nextAvailableP] = getString("Enter the contact name\n");
if(contacts[*nextAvailableP] == NULL){
printf("Malloc failed\n");
return FALSE;
}
(*nextAvailableP)++;
//allocates the memory needed for the number of email addresses
int numberOfMailsIndex = (*nextAvailableP);
contacts[numberOfMailsIndex] = (char*)malloc(5);
itoa(numberOfMails, contacts[numberOfMailsIndex], 10);
(*nextAvailableP)++;
//receives the name, and saves it at the right cell
printf("Enter the mail/s, use enter to enter a mail and '-1' to signal you finished\n");
while(1){
if (*nextAvailableP > N-1){
printf("Unable to add another mail, not enough memory\n");
return FALSE;
}
char *tempMail = getString("Enter mail or '-1' to stop\n");
if(tempMail == NULL){
printf("Malloc failed\n");
return FALSE;
}
if(strcmp(tempMail,"-1") == 0){
break;
}
contacts[*nextAvailableP] = tempMail;
printf("\nAdded!\n");
(*nextAvailableP)++;
numberOfMails++;
itoa(numberOfMails, contacts[numberOfMailsIndex], 10);
}
}
//Gets a string and prints it as a message.
//Then, read the text from stdin, saves it in a pointer and sends it back
char *getString(char *queryText){
char buffer[BUFFERSIZE];
char *temp;
printf("%s", queryText);
fgets(buffer, BUFFERSIZE, stdin);
//clears \n at the end of the line
if ((strlen(buffer) > 0) && (buffer[strlen(buffer) - 1] == '\n'))
buffer[strlen(buffer) - 1] = '\0';
temp = (char*)malloc(strlen(buffer));
//if(temp == NULL)? , checked each time in the calling function
strcpy(temp, buffer);
return temp;}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T20:15:02.100",
"Id": "497939",
"Score": "0",
"body": "@Reinderien I'll be happy to, but it's quite (realtivly). Do I just post it here the same way or it's better to uplaod it to somewhere else?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T20:44:18.847",
"Id": "497942",
"Score": "2",
"body": "Please do not edit the question, especially the code after an answer has been posted. Everyone needs to be able to see what the reviewer was referring to. [What to do after the question has been answered](https://codereview.stackexchange.com/help/someone-answers)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T20:44:41.447",
"Id": "497943",
"Score": "0",
"body": "CC @Reinderien ^^"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T20:51:40.837",
"Id": "497945",
"Score": "0",
"body": "@Mast ho sorry I just did, but I left the old part of code too.\nI'll upload a new question, can you edit the question back to the original?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T21:02:13.423",
"Id": "497953",
"Score": "2",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<p>Your code is not correct. It can crash.</p>\n<p>First, look at the line</p>\n<pre><code>fgets(buffer, BUFFERSIZE, stdin);\n</code></pre>\n<p>If an error occurs while reading, the state of <code>buffer</code> is indeterminate. You should not continue processing it in that case. You need to detect this by the appropriate means and signal a failure.</p>\n<p>Second, if the <code>malloc()</code> fails, what will be the effect of the next line which is</p>\n<pre><code>strcpy(temp, buffer);\n</code></pre>\n<p>hint: it's not good</p>\n<p>To answer your specific questions:</p>\n<ol>\n<li>Mostly</li>\n<li>Yes</li>\n<li>Your wording is imprecise. You're not changing the pointer, you're changing the memory pointed to by the pointer.</li>\n<li>It is somewhat frowned upon to have a function allocate memory and then return a pointer to, because the caller may not know how the memory was allocated and how it needs to be deallocated (is it static? is it on the <code>malloc</code> heap? is it in a private buffer? is it in an OS-specific heap?). For a simple example what you have is probably okay but Best practice is for the caller to allocate it and then pass it in.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T20:11:51.530",
"Id": "497938",
"Score": "0",
"body": "About the `fgets(buffer, BUFFERSIZE, stdin);` - I can assume at this point that the \ninput is correct.\n\nAbout the `malloc()` - understood, (I edited the post). So do I have to check it again \nafterwards?\n\nAbout 3, That's probably my english - but just to make sure again - in terms of freeing the memory I'm ok, right?\n\nThank you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T20:55:57.677",
"Id": "497947",
"Score": "0",
"body": "Why can you assume that \"the input is correct\" but can't assume \"there's enough memory so that `malloc()` will succeed\"? What is the source of those assumptions? If you're developing in a situation where `malloc()` could fail, how can you possibly assume that `fgets()` will have enough memory available to do what it needs to do?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T20:58:26.323",
"Id": "497949",
"Score": "0",
"body": "I'm a student, that's my first assigment about pointers and malloc.\nThe source is my proffesor"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T20:59:11.363",
"Id": "497950",
"Score": "2",
"body": "What do you mean by \"check it again\"? What \"it\" are you talking about? The rule of `malloc()` is, you have to check that its return value is not `NULL`. Once you have determined that it is `NULL`, you cannot proceed as intended, you have to abort and/or signal an error. How you signal that error is up to you. Whoever calls your function then needs to detect that error and respond appropriately. So if you signal your error by returning `NULL`, then... (finish the thought yourself)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T21:00:04.757",
"Id": "497951",
"Score": "1",
"body": "Then you need to check with your professor exactly what you can and cannot assume, and make sure you include all assumptions when you ask about the code."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T19:49:25.927",
"Id": "252672",
"ParentId": "252669",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T19:24:56.470",
"Id": "252669",
"Score": "3",
"Tags": [
"c",
"memory-management",
"pointers"
],
"Title": "Maintain a list of contacts in C"
}
|
252669
|
<p>I have two integer values and would like to obtain their quotient which should be a fractional number, in this example <code>37/2=18.5</code>. I usually do this:</p>
<pre><code>uint16_t dividend=37;
uint16_t divisor=2;
auto quotient=dividend/double(divisor);
</code></pre>
<p>In python3 there are division <code>/</code> and truncation division <code>//</code> which result in respective quotients of <code>18.5</code> and <code>18</code>. As far as I know there is only <code>/</code> in C++ which on integers works like truncation division.</p>
<p>Is there a standard way of getting a <code>quotient==18.5</code> in C++?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T20:46:37.513",
"Id": "497944",
"Score": "4",
"body": "Code Review requires concrete code from a project, with enough code and / or context for reviewers to understand how that code is used. Pseudocode, **stub code, hypothetical code**, obfuscated code, **and generic best practices** are outside the scope of this site. Please take a look at the [help/on-topic]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T20:53:12.997",
"Id": "497946",
"Score": "0",
"body": "When you post again, post the actual section of code that is dividing two integers and obtaining their quotient, making it clear where the two integers come from, why they are integers, and why the quotient needs to be not truncated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T21:31:56.263",
"Id": "497958",
"Score": "0",
"body": "To get a `double` result, you need to convert (at least) one of the operands to `double` before doing the division (so your `auto quotient=dividend/double(divisor);` should be correct)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T08:35:58.410",
"Id": "498023",
"Score": "1",
"body": "@Snowbody It would still break this rule: \"We require that the poster know why the code is written the way it is.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T22:37:39.927",
"Id": "498198",
"Score": "0",
"body": "Thanks for the discussion and pointing out that the way I posed my question was inappropriate. I'll write a better question next time."
}
] |
[
{
"body": "<p>Don't use the C cast in C++.<br />\nWe have a specific cast for this in C++</p>\n<pre><code>auto quotient = dividend / static_cast<double>(divisor);\n</code></pre>\n<p>Alternatively you can simply multiply one value by 1.0</p>\n<pre><code>auto quotient = 1.0 * dividend / divisor;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T23:02:30.210",
"Id": "252682",
"ParentId": "252671",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "252682",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T19:45:03.963",
"Id": "252671",
"Score": "-1",
"Tags": [
"c++"
],
"Title": "best practice to divide uint16_t to get double"
}
|
252671
|
<p>Initially, I posted <a href="https://stackoverflow.com/questions/64986989/python-library-for-hierarchical-sets">this question</a> on StackOverflow. I wanted to know if there's an existing library that implements the concept I have in mind, which is the following.</p>
<p>I want to define a hierarchy/tree, e.g.:</p>
<pre><code> Commit
/ | \
Feature Fix Refactoring
/ \
CodeFix DocFix
</code></pre>
<p>and then be able to define sets where the elements are the nodes of the tree, e.g. <code>X = {Feature, Fix}</code>, <code>Y = {DocFix, Refactoring}</code>. When performing operations, in contrast to the standard python sets, I would like to consider that the elements in the set that are a child and a parent in the tree have the SUBSET-OF relationship (like <code>DocFix</code> and <code>Fix</code>). I would like, therefore, <code>X.union(Y)</code> to yield <code>{DocFix}</code> rather than <code>{}</code>. Please see more examples in the doc-test I provided.</p>
<p>My biggest concern is not to "reinvent the wheel", and I would be grateful to pointers to existing data structures in the standard python library or custom libraries that can be used to fully/partially replace my code. Of course, other comments regarding the code are greatly appreciated.</p>
<p>Cheers, Hlib.</p>
<h3>hset.py</h3>
<pre><code>from typing import List
from hset.tree import _Tree
class HSet:
"""
>>> commit = HSet.create_root_element("Commit")
>>> feature, fix, refactoring = commit.add_children("Feature", "Fix", "Refactoring")
>>> code_fix, doc_fix = fix.add_children("CodeFix", "DocFix")
# Commit
# / | \
# Feature Fix Refactoring
# / \
# CodeFix DocFix
>>> str(code_fix | doc_fix)
'{Fix}'
>>> str(code_fix | refactoring)
'{CodeFix|Refactoring}'
>>> str(feature | fix | refactoring)
'{Commit}'
>>> str(~ code_fix)
'{Feature|DocFix|Refactoring}'
>>> str(~ commit)
'{}'
>>> str(~ (feature | refactoring))
'{Fix}'
"""
def __init__(self, subtrees: List[_Tree], domain: _Tree):
self.subtrees = domain.collapse_subtrees(subtrees)
self.domain = domain
@classmethod
def create_root_element(cls, label: str) -> 'HSet':
tree = _Tree(label, None, [])
return cls([tree], tree)
def add_children(self, *labels: str) -> List['HSet']:
if len(self.subtrees) != 1:
raise ValueError(f"Cannot add children to this HSet since it has multiple root elements: {self}")
if self.subtrees[0].children:
raise ValueError(f"This HSet already has children.")
trees = self.subtrees[0].add_children(*labels)
return list(map(lambda t: self._create([t]), trees))
def _create(self, subtrees: List[_Tree]) -> 'HSet':
return HSet(subtrees, self.domain)
def __str__(self):
return '{' + "|".join(map(lambda x: x.label, self.subtrees)) + '}'
def __invert__(self) -> 'HSet':
return self._create(self.domain.complement(self.subtrees))
def __or__(self, other: 'HSet') -> 'HSet':
if self.domain != other.domain:
raise ValueError("Cannot perform operations on HSets with different domains")
return self._create(self.domain.collapse_subtrees(self.subtrees + other.subtrees))
</code></pre>
<h3>tree.py</h3>
<pre><code>from dataclasses import dataclass
from typing import Optional, List
@dataclass
class _Tree:
label: str
parent: Optional['_Tree']
children: List['_Tree']
def add_children(self, *labels: str) -> List['_Tree']:
children = [_Tree(label, self, []) for label in labels]
self.children = children
return children
def collapse_subtrees(self, subtrees: List['_Tree']) -> List['_Tree']:
if self in subtrees:
return [self]
elif not self.children:
return []
fully_covered = True
res = []
for child in self.children:
collapsed_child = child.collapse_subtrees(subtrees)
fully_covered &= (collapsed_child == [child])
res.extend(collapsed_child)
return [self] if fully_covered else res
def complement(self, subtrees: List['_Tree']) -> List['_Tree']:
if self in subtrees:
return []
elif not self.children:
return [self]
return [elem for lst in map(lambda x: x.complement(subtrees), self.children) for elem in lst]
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T20:44:19.400",
"Id": "252677",
"Score": "1",
"Tags": [
"python",
"tree",
"set"
],
"Title": "Set operations on a tree / Hierarchical set class"
}
|
252677
|
<p>I'm a beginner to python and as part of my course I'm instructed to create a simple tic tac toe game.</p>
<p>I'd be very appreciative and interested of any insight, criticism, instructions, best practices or code readability and tips.</p>
<p>Are my comments descriptive, repetitive and useful enough?</p>
<p>Any inputs and tips would be greatly appreciated.</p>
<h3>Here's my code</h3>
<pre><code>import random
#gives the apearance of rewriting the board on the screen
clear = lambda: print('\n' * 20)
#will be used as the game board; to hold the x's and o's and determine a win etc.
test_board = ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']# the '#' is at index 0 so that players can input 1 to use first position instead of 0
# prints testboard with lines so that it appears like a real board
def display_board(board):
print(board[1] + '|' + board[2] + '|' + board[3])
print('-|-|-')
print(board[4] + '|' + board[5] + '|' + board[6])
print('-|-|-')
print(board[7] + '|' + board[8] + '|' + board[9])
# assigns x to player1 and o to player2
def player_input():
marker = ''
while not (marker == 'x' or marker == 'o'): #this loop goes over and over untill the playerinput is an x or o.
marker = input('player1 please choose a marker. "x" or "o"')
if marker == 'x':
return ('x', 'o') # to assign x to player1 and o to player2 with tuple unpacking
else:
return ('o', 'x') # to assign o to player1 and x to player2 with tuple unpacking
# converts a players integer input to and assings either x or o to the testboard's index of the input
def place_marker(board, marker, position):
board[position] = marker
# checks to board for a win
def win_check(board, mark):
return ((board[1] == mark and board[2] == mark and board[3] == mark) or # across top
(board[4] == mark and board[5] == mark and board[6] == mark) or # across middle
(board[7] == mark and board[8] == mark and board[9] == mark) or # across bottom
(board[1] == mark and board[4] == mark and board[7] == mark) or # down left
(board[2] == mark and board[5] == mark and board[8] == mark) or # down middle
(board[3] == mark and board[6] == mark and board[9] == mark) or # down right
(board[1] == mark and board[5] == mark and board[9] == mark) or # diagonal upper right to lower left
(board[3] == mark and board[5] == mark and board[7] == mark) # diagonal upper left to lower right
)
#chooses a player to go first
def choose_first():
random_int = random.randint(1, 10)
if random_int % 2 == 0:
print('player1 may go first')
return True
else:
print('player2 may go first')
return False
# when player gives index position, checks if index position is not already taken
def space_check(board, position):
return board[position] == ' '
# checks if the board is full
def full_board_check(board):
for x in range(1, 10):
if space_check(board, x):
return False #the index position of the player's input is ' ' based on space_check so its False. i.e. empty
return True #the index position of the player's input is not ' ' based on space_check so its True. i.e. full
# accepts the players position for where he wants to go
def player_choice(board):
while True:
a = input('please input an integer 1-9')#will be the index position of test_board
try:
a = int(a)#must convert to int to be used in test_board indexing
except ValueError:#ensures that the players input is an integer
clear()
print('\n please type a number')
print('_____________________')
display_board(board)
continue
if a >= 1 and a <= 9:#since there are only nine positions in test_board, the players input must be between 1 and 9
if space_check(board, a):
return a #return a(player's input) to be used in test_board
elif a < 1 or a > 9:
print('please input an integer from 1-9')
else:
clear()
print('\n that space isn\'t available')
print('____________________________')
display_board(board)
continue
# when game is over, replay the game
def replay():
replay = input('press any key to play again. type "q" to quit')
while True:
if 'q' in replay:
return False
break
else:
return True
break
while True:
#set the game up
test_board = ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '] #at the begining of the game empty's the board.
#randomly select a player to go first
if choose_first():
player1,player2=player_input()
else:
player2,player1=player_input()
game_on=True
#players take turns
while game_on:
#player1's turn
display_board(test_board)
print('%s may go'% player1)
place_marker(test_board,player1,player_choice(test_board))#assings the players input to test_board
if win_check(test_board,player1):
display_board(test_board)
print('%s has won! \n game over'% player1)
break #breaks out of local loop and jumps to next loop (if not replay())
elif full_board_check(test_board):
display_board(test_board)
print('board is full')
break
#player2's turn
print('%s may go' % player2)
display_board(test_board)
place_marker(test_board,player2,player_choice(test_board))
if win_check(test_board,player2):
display_board(test_board)
print('%s has won! \n game over'% player2)
elif full_board_check(test_board):
display_board(test_board)
print('board is full')
break
if not replay():
break
</code></pre>
|
[] |
[
{
"body": "<h2>use platform-independent clear function</h2>\n<pre><code>from os import system, name\ndef clear():\n if name == 'nt':\n system('cls')\n else:\n system('clear')\n\n</code></pre>\n<p>This new function <code>clear</code> is platform-independent and slightly more elegant than the approach you used.</p>\n<h2>Notes on Comments</h2>\n<p>Comments are good but a necessary evil, since you highlighted that you are doing a course, it might be a requirement to include "descriptive comments", but you won't be doing that course all your life. Comments should be avoided as much as possible. Use comment to explain intent(why something was done) not how it was done. If a thought to include a comment crosses your mind, ask yourself, "How would I express myself in code?"</p>\n<h2>Consider using a 2D to represent a board</h2>\n<p>Your internal representation of a board is a 1D list. This is fine, but I would advise you to mirror a real-life application, a tic-tac-toe game is mostly 2D or 3D, a 2D representation would be</p>\n<pre><code>board = [ [ ' ' for _ in range(3)] for _ in range(3) ]\n</code></pre>\n<p>Accessing this is also easy with just an index</p>\n<pre><code>index = 5 # an example\nrow = index // len(board)\ncol = index % len(board)\n\nboard[row][col] = marker\n\n</code></pre>\n<h2>Improvement on names and structure</h2>\n<p>Right now, your code is messy and hard to read, <code>win_check</code> is a little confusing, a nice and better structure might be something like this</p>\n<pre><code>def check_victory():\n if row_victory():\n return True\n if column_victory():\n return True\n if diagonal_victory():\n return True\n\n return False\n\n</code></pre>\n<p>From the look of this, it is quite easy to follow what is going on here. <code>row_victory</code>, <code>column_victory</code>, <code>diagonal_victory</code> might be implemented as follows</p>\n<pre><code>def row_victory():\n for i in range(len(board)):\n if (board[i][0] != ' ' and\n board[i][0] == board[i][1] == board[i][2]):\n return True\n\n return False\n\ndef column_victory():\n for i in range(len(board)):\n if (board[0][i] != ' ' and\n board[0][i] == board[1][i] == board_array[2][i]):\n return True\n\n return False\n\ndef diagonal_victory():\n if (board[0][0] != ' ' and\n board[0][0] == board[1][1] == board[2][2]):\n return True\n if (board[0][2] != ' ' and\n board[0][2] == board[1][1] == board[2][0]):\n return True\n\n return False\n\n</code></pre>\n<p>This would mean you need to keep a <code>current_player</code> variable, this should seem easy for you. When any of the above function returns true, the current player is the winner. Consider renaming <code>full_board_check</code> to <code>stalemate</code>.</p>\n<p>Names like <code>a</code> should be avoided, a better alternative is <code>user_input</code></p>\n<h2>Consider using a class</h2>\n<p>Using a class would really improve the structure and readability of your code</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T17:56:59.230",
"Id": "498089",
"Score": "0",
"body": "This is a very nice review, But I don't agree with the 2-dimensional board thing, You will always need two subscripts to access as square, always keep two variables to represent a position, and will always have to convert the user input to your way of representing the board. A lot of extra lines of code, for what?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T18:10:08.363",
"Id": "498091",
"Score": "1",
"body": "Also, from your `check_victory()` function. `return row_victory() or col_victory() or diag_victory()` :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T19:30:33.633",
"Id": "498103",
"Score": "0",
"body": "@Aryan Parekh, A 2d board mirrors tic-tac-toe real life implementation, the overhead of having two variables to represent a position is negligible"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T19:31:34.537",
"Id": "498104",
"Score": "0",
"body": "Real-life implementation? How so, in my head I see 1-9, that's why you ask the user to enter a number from 1-9."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T19:34:33.663",
"Id": "498105",
"Score": "0",
"body": "I mean't the board is represented on a 2d plane with x and y co-ordinates."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T17:28:48.160",
"Id": "252720",
"ParentId": "252681",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "252720",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T22:32:28.517",
"Id": "252681",
"Score": "4",
"Tags": [
"python",
"beginner",
"game",
"tic-tac-toe"
],
"Title": "Tic Tac Toe game in Python - Beginner"
}
|
252681
|
<p>I'd like to get a review for the function that cd into the git tree root or does nothing if we are outside of the repository.</p>
<h2>reviewed version:</h2>
<pre class="lang-bsh prettyprint-override"><code># cd to the root of the current git directory
# If $PWD is submodule, will cd to the root of the top ancestor
# It requires to stay in the current directory, if the root is . or unknown,
# and use cd only once, to have a way to do `cd -`
function cg {
git_root() {
local super_root
local top
top="$(git rev-parse --show-cdup)"
top="${top:-./}"
super_root="$(git rev-parse --show-superproject-working-tree)"
if [[ "$super_root" ]]; then
printf '%s' "$top../"
( cd "$top../" && git_root || return )
fi
printf '%s' "$top"
}
local git_root
git_root="$(git_root)"
[ "x${git_root}" != "x./" ] && cd "$(git_root)" && return || return 0
}
</code></pre>
<h2>updated version:</h2>
<pre><code>#!/bin/bash
# cd to the root of the current git directory
# If $PWD is submodule, will cd to the root of the top ancestor
# It requires to stay in the current directory, if the root is . or unknown,
# and use cd only once, to have a way to do `cd -`
function cg {
function git_root {
local top; top="$(git rev-parse --show-cdup)"
top="${top:-./}"
local super_root; super_root="$(git rev-parse --show-superproject-working-tree)"
if [[ "$super_root" ]]; then
printf '%s' "$top../"
( cd "$top../" && git_root || return )
fi
printf '%s' "$top"
}
local tree_root
tree_root="$(git_root)"
[[ "x${tree_root}" != "x./" ]] && cd "${tree_root}" && return || return 0
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T13:01:20.840",
"Id": "498048",
"Score": "0",
"body": "just a suggestion, the single line `cd \"$(git rev-parse --show-toplevel || echo .)\"` does the exact thing :) Taken from oh-my-zsh plugin: https://github.com/ohmyzsh/ohmyzsh/blob/master/plugins/git/git.plugin.zsh#L238"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T13:21:32.150",
"Id": "498054",
"Score": "2",
"body": "Please do not edit the question after it has been answered. See [what should I not do](https://codereview.stackexchange.com/help/someone-answers)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T13:29:39.410",
"Id": "498058",
"Score": "1",
"body": "@hjpotter92 no, sorry, it doesn't because it knows nothing about: a) symlinks; b) submodules. These two points forced me to invest time in the function above."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-30T09:45:58.910",
"Id": "498364",
"Score": "0",
"body": "Thank you pacmaninbw, here's the updated version https://codereview.stackexchange.com/questions/252838/updated-bash-zsh-function-that-cd-to-the-root-of-git-tree"
}
] |
[
{
"body": "<h1>Great</h1>\n<ul>\n<li>100% pass on <a href=\"https://www.shellcheck.net/\" rel=\"nofollow noreferrer\">shellcheck</a> which means you're doing great with quoting everything that could be potentially problematic.</li>\n<li>scoping variables</li>\n<li>using <code>[[</code> conditional for the <code>if</code></li>\n<li>nice explanation of what it is doing and why</li>\n</ul>\n<h1>Could be better</h1>\n<ul>\n<li>a sh-bang line at the top is a good idea for scripts, even if this would usually just be sourced during your login scripts.</li>\n<li>Your inner function is defined with different syntax than your outer function.</li>\n<li>You can scope and define a variable in one line. For example: <code>local super_root="$(git rev-parse --show-superproject-working-tree)"</code>. This makes sure you don't fail to define a local variable or fail to scope a new variable. And it cuts out a line of code in each case.</li>\n<li>Reusing <code>git_root</code> for a variable name and the function name is confusing. I initially wondered why you were trying to scope the function after you had just defined it.</li>\n<li>use <code>[[</code> conditional for conditional in the last line.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T11:18:27.943",
"Id": "498041",
"Score": "0",
"body": "I know it's tagged [tag:bash], but I'd go the other way on your last comment, and turn the existing `[[` into a `[` test, so this function can more easily be adapted for other shells (I think that just leaves `local` as the only Bash feature used)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T12:04:58.153",
"Id": "498045",
"Score": "0",
"body": "Thank you for your review!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T12:16:53.437",
"Id": "498046",
"Score": "0",
"body": "1) sure, makes sense; 2) true, I've missread the `name() ( code )` and `name() { code }` notations; 3) actually making one line `local top=...` cause complaints by shellcheck `SC2155: Declare and assign separately to avoid masking return values`. That's why I've decided to leave it this way; 4) yes, a little bit messy; 5) I see the point to make it POSIX-complaint, but this looks to me like a function for interactive shell, so I'll use `[[` in the latest line too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T14:12:33.280",
"Id": "498062",
"Score": "0",
"body": "Thanks for reviewing the review! I like `[[` for safety, but I'm not worried about portability like Toby. SC2155 applies because all your assignments involve subcommands, but you're already masking return values in a few places."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T17:18:34.393",
"Id": "498087",
"Score": "0",
"body": "I like the cleaned up version, but to get a new review you're supposed to post a new question each time."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T03:12:59.607",
"Id": "252690",
"ParentId": "252685",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "252690",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T23:26:12.507",
"Id": "252685",
"Score": "4",
"Tags": [
"bash",
"git"
],
"Title": "Bash/zsh function that cd to the root of git tree"
}
|
252685
|
<p>I was extremely annoyed by the lengthy, edge-case-galore explanation of integer version of C++ standard library mindpoint implementation <a href="https://www.youtube.com/watch?v=sBtAGxBh-XI" rel="nofollow noreferrer">here</a>, so I made my own simple 2's complement version. I present it for your judgement.</p>
<p>The general idea is to carry out <code>a + (b-a)/2</code> in a wider signed integer that won't ever overflow.
Say a and b are N bit integers. Consider them as imaginary signed (2's complement) N+1 bit integers. The obvious magic of 2's complement is that we can carry out addition/subtraction as usual, so first we obtain the lower N bits of the hypothetical N+1 bit difference,</p>
<pre><code>Unsigned diff = Unsigned(b) - Unsigned(a);
</code></pre>
<p>working with unsigned type to avoid signed overflow UB. We don't really have the +1 bit, so just imagine sign extension also happens. We only care about lower N bits anyway since we know the final half difference has to fit there. Problem is - we can't do division in this straightforward way, so we have to branch, based on the sign of the final result.</p>
<ul>
<li><p>If N+1 bit difference was negative (highest/sign bit set), we jump through hoops:<br />Negate/abs (2's complement approved as subtraction 0-diff).<br /><code>Unsigned negative_2x = -diff; </code><br />Divide (it works cause sign bit is now guaranteed 0).<br /><code>negative_2x /= 2;</code><br />
Now we can fit this halved difference back into our original N bit signed int, so we convert it back and negate to restore the original sign.<br /><code>Integer negative = -Integer(negative_2x);</code> <br />
Converting first is important to avoid signed overflow UB again. If original Integer was unsigned this still works, since the wrapping behavior is consistent with 2's complement.</p>
</li>
<li><p>Otherwise if difference was positive, it fully fit in N bits unsigned, and half of it should fit in signed, no hoops:<br /><code>Integer positive = diff / 2;</code></p>
</li>
</ul>
<p>The actual branch looks like this to encourage conditional move, not that compilers care...</p>
<pre><code>return a + (b < a ? negative : positive);
</code></pre>
<p>The code by itself with a primitive/stand-in function signature, for the purposes of copying into an IDE and compiling:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <type_traits>
template<typename Integer, typename Unsigned = std::make_unsigned_t<Integer>>
Integer midpoint(Integer a, Integer b)
{
Unsigned diff = Unsigned(b) - Unsigned(a);
Unsigned negative_2x = -diff;
negative_2x /= 2;
Integer negative = -Integer(negative_2x);
Integer positive = diff / 2;
return a + (b < a ? negative : positive);
}
</code></pre>
<p>Also available <a href="https://git.sr.ht/%7Enamark/libsimple_support/tree/68b0f2380c358059b39ef0891d33243a0b3e347e/source/simple/support/algorithm.hpp#L344" rel="nofollow noreferrer">here</a>, passes all the libstdc++ and libc++ unit tests for integers.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T00:25:28.713",
"Id": "497982",
"Score": "1",
"body": "Welcome to the Code Review Community. We can only review code that is included in the question. While we can use repositories for reference, there just isn't enough code in the question to review and that makes the question off-topic. Please read [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask) in the [help center](https://codereview.stackexchange.com/help/asking). Please note that if the code isn't working as expected that also makes the question off-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T01:49:39.217",
"Id": "497991",
"Score": "0",
"body": "That's exactly what he does for integers in the video. Just written slightly different but the point is the same. You also need to make that no branches were generated in compilation like he did."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T07:21:33.203",
"Id": "498015",
"Score": "0",
"body": "@ALX23z Obviously the point would be the same, it's an implementation of the same function, but it is in no way exactly the same, it's the difference between \"but what if, but what if, but what if\" type of code, and an elegant solution. It generates shorter branch-less assemebly than the current standard implementation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T07:25:13.420",
"Id": "498016",
"Score": "0",
"body": "No idea why this was closed, I wrote the code, and it is present in its entirety in the question. I just added more elaborate comments on it.\nThe context of the code is c++ standard library midpoint, the integer part. That should tell you everything you want to know, if not - you should watch that video I linked."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T18:43:20.690",
"Id": "498097",
"Score": "0",
"body": "@pacmaninbw There are 7 lines, and I didn't know there is a limit. I expect the usual criticisms on readability - variables could be named differently, expression written down differently, or could be that entirely different set of primitives could be chosen to express the same thing (for instance the neg-div-neg sequence is actually `a - (a-b)/2`, where `a=0, b=diff`, and I have a function that does that called `halfwayback`, but I wasn't able to utilize it). Also c++ specific stuff, standard compliance, portability, weird edge cases perhaps, codegen etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T20:21:25.233",
"Id": "498109",
"Score": "3",
"body": "see, those 7 lines in that post don't look like the 7 lines in your IDE of choice. We really don't want you to sprinkle the code under review in between an extensive explanation of what the code does. Instead we want to see the code and an explanation for it. Taking a look at other questions on the site (that have not been closed) hopefully gives you an idea how this community prefers questions. I'd also avoid \"wrong\" in the question title, if only because people could easily get the wrong idea about what you're actually asking for..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T21:04:42.910",
"Id": "498111",
"Score": "0",
"body": "@Vogel612 I don't understand the implication. If you understand what I've presented tell me how to improve it. Are you saying I should just copy those 7 lines and paste them at the end, after the explanations? I wouldn't recommend copying it into an IDE from here, if you want to run it or experiment with it I provided you a link to my code repository, you can check it out, open the file, jump to the line, `make test` if you will, or just copy from there. Here I didn't want to draw attention towards the function signature or the static assertions, as they are a bit out of context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T05:28:44.223",
"Id": "498129",
"Score": "2",
"body": "Yes, we want to see the full code, we want function signatures, we want context. If you think each line needs a separate explanation, put it in a code comment. And definitely don't put \"what's wrong\" in the title of your question. And links can carry additional information that is not necessary but we cannot consider them a legitimate part of your question. We cannot know if the link is dead or provides different information by tomorrow..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T09:54:39.470",
"Id": "498147",
"Score": "0",
"body": "@slepic You misunderstand, the link to code I provided is not the context, it's just for convenience. The context is c++ standard library midpoint. I edited to clarify. Again I don't want you reviewing the signature, it is not the same as standard's for my own purposes, that are out of context.\nI put the explanations in as code comments initially but it looked horrible, so I thought why not make them formatted? what's the difference?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-28T06:49:16.797",
"Id": "498207",
"Score": "2",
"body": "Somebody here does not understand, that's for sure. Look, you can keep your own truth and get rejected by the community or you accept the community truth and post it the way the community wants it. Easy as that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-28T11:14:49.607",
"Id": "498224",
"Score": "0",
"body": "@slepic If you ask me, understanding is between people, not within a person, one person can't not understand, two people might understand or not understand each other, so I did not mean to insult you, or question your beliefs, by telling you that you misunderstood the context. I, myself, don't understand what you want from me, and your are not answering my questions directly. I met all of the criteria, the code is there in its entirety, the context is clarified. If you want, I can copy and paste the full standard implementation, or maybe just the signature from it, but that's just noise IMHO."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-28T13:55:25.990",
"Id": "498231",
"Score": "2",
"body": "\"the code is there in its entirety\" that's disputable. If I cut a picture into pieces and toss those pieces into a cup of tea, then I give you the tea and say \"nice picture, huh?\" even if you were an arts expert, you wouldn't be very confident answering that one, would you? We want a specification and its implementation - the code, possibly decorated with some explanatory comments. Rather than an essay with fragments of code in it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-28T15:08:25.647",
"Id": "498233",
"Score": "0",
"body": "@slepic Comparing code to a picture is curious. I, for one, do not appreciate monolithic code that is impossible to subdivide into meaningful pieces. I wanted to clearly explain the logic behind it, because I think it is important. I expect I would have to do it in the comments, if I didn't do it in the question. The specification is c++ standard library midpoint, the integer part. Implementation is presented in its entirety. Interface is defined by the standard and can be put in code in various ways. Wheat exactly do you want changed? Just a copy of the code after the explanations?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-28T15:51:24.163",
"Id": "498236",
"Score": "1",
"body": "Probably. Yes. Including any asserts, called functions, used namespaces and included headers. Some edge test cases won't hurt either. If we can just copy and compile the thing, you're much more likely to get feedback."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-28T19:05:28.357",
"Id": "498245",
"Score": "0",
"body": "@slepic I was referring to the exact code presented, nothing extra, and issue is not that I'm not getting enough feedback, it is that the question was closed for no specific reason. In c++ the function signature can be just as complex as the implementation, that's why I deliberately avoided it, my focus is on the implementation. Nevertheless I've added some compilable code, bracing for signature criticism. I haven't written any tests myself, I used existing ones, and to include those would be against the rules. Also the whole point of my approach is to leave no edge cases to conciser."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-28T19:17:59.840",
"Id": "498247",
"Score": "1",
"body": "Seems good enough now. I'm voting to reopen."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-28T21:10:35.413",
"Id": "498255",
"Score": "0",
"body": "@slepic Thank you for your comments, the question has been reopened."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T18:41:08.313",
"Id": "498310",
"Score": "0",
"body": "Since the question is good now, might as well remove the downvotes!"
}
] |
[
{
"body": "<h1>Naming things</h1>\n<p>The variable names are not very clear. I assume the <code>_2x</code> stands for "2's complement" instead for "times 2", but for someone who doesn't know the context, it will be hard to follow. I'm not sure what the best way to name them is though, but as shown below you can avoid the issue altogether.</p>\n<h1>Don't use a template parameter for a derived type</h1>\n<p>If you make <code>Unsigned</code> a template parameter, it means someone can override it to something nonsensical. If you want to have a named type that is a derivative of another type, use <code>using</code> inside the function body:</p>\n<pre><code>template<typename Integer>\nInteger midpoint(Integer a, Integer b)\n{\n using Unsigned = std::make_unsigned_t<Integer>;\n ...\n}\n</code></pre>\n<h1>Simplifying the code</h1>\n<p>Most of the temporary variables can be removed. I would keep the variable <code>diff</code>, as it is the most important one where the casts are essential, and since it is used twice:</p>\n<pre><code>template<typename Integer>\nInteger midpoint(Integer a, Integer b)\n{\n using Unsigned = std::make_unsigned_t<Integer>;\n Unsigned diff = Unsigned(b) - Unsigned(a);\n return a + (b < a ? -Integer(Unsigned(-diff) / 2) : Integer(diff / 2));\n}\n</code></pre>\n<p>The return expression is still reasonably short, and I don't think any information was lost. Adding some comments explaining why the casts are necessary would be helpful though.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T14:50:44.367",
"Id": "498296",
"Score": "0",
"body": "Hm now I wonder now if it should be `-Integer(-diff / 2)` or not, as you mentioned that this might be UB otherwise, but would it still be UB with C++20's mandatory two's complement signed integers?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T16:38:37.123",
"Id": "498299",
"Score": "0",
"body": "I have Unsigned as template parameter to use the function for types other than the fundamental integers, without specializing std::make_unsigned_t, but that is out of context here, I wanted to discuss the implementation only, I was \"forced\" to include the signature. In context of standard spec of midpoint, I can criticize your signature as well to no end."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T16:43:05.593",
"Id": "498300",
"Score": "0",
"body": "The `_2x` does indeed mean 2 times, indicating that we are dealing with a number that is twice the range of our original (+1 bit), and only after properly halfing it can we assign it back to the original type. One should be familiar with 2's compliment to understand this code yes, but I think that's better than consider numerous edge cases. You might have not concidered char or short, and promotion rules, since you code is failing some test cases. You can check out the repo I linked, modify the midpoint there and run `make test` see the details."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T16:47:09.540",
"Id": "498301",
"Score": "0",
"body": "It is possible that a single cast can be eliminated thanks to C++20's two's complement, but there are a lot more casts happening there, mainly to combat pesky promotion. I wonder what things might look like with something like safe_numerics library employed here, and what the codegen would be."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T18:14:10.547",
"Id": "498307",
"Score": "0",
"body": "I can only review the code you show here, so in that context the `Unsigned` template parameter is avoidable. If you need it in your code, then of course you should keep using it. If you want to be safe on platforms that do not have two's complement arithmetic, then still I would avoid the temporary variables, and write: `return a + (b < a ? -Integer(-diff / 2) : Integer(diff / 2))`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T20:26:52.553",
"Id": "498326",
"Score": "0",
"body": "The issue is not just signed overflow, it is promotion, which applies to all arithmetic, including unary minus, and prevents the modulo arithmetic that this method relies on. Your code still doesn't pass the tests, you probably need one or two more casts in your one-liner. Even if correct I think the code is less readable that way. That said nobody would even recognize what I wrote as code so who am I to judge."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T22:23:27.747",
"Id": "498332",
"Score": "0",
"body": "It's interesting that it doesn't pass the tests. What compiler and CPU architecture are you using? Clang and GCC produce the same assembly for your version as for mine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T22:44:20.340",
"Id": "498336",
"Score": "1",
"body": "I tried with gcc on x86_64, are you sure the assembly is the same for short and char? For example one of the failing cases looks like this `midpoint(limits::max(), limits::min()) == T( 0)` where `T` is singed char/short and `limits` is `std::numeric_limits<T>`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-30T15:52:46.587",
"Id": "498373",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/116816/discussion-between-g-sliepen-and-namark)."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T11:15:57.390",
"Id": "252816",
"ParentId": "252686",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "18",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T23:29:04.430",
"Id": "252686",
"Score": "3",
"Tags": [
"c++",
"integer"
],
"Title": "Integer version of c++ standard library midpoint"
}
|
252686
|
<p>I'm new to both Python and socket programming and figured setting up a simple chat server would be good practice. In addition to general critiques of the code, I have specific questions:</p>
<ul>
<li><p>What are the best practices for network programming in Python? Is the object-oriented style I went with advisable or should I structure it differently?</p>
</li>
<li><p>How can I write effective unit tests for a client-server program when both client and server seem to depend on each other for execution? I've heard of mocking, but I have no firsthand experience with it and don't know whether mocking would be applicable in this case.</p>
</li>
<li><p>Normally I would have assumed that a server with multiple clients would be multithreaded, but the Python networking tutorials I could find all used select. In socket programming should I prefer to use select over threads?</p>
</li>
</ul>
<p>server.py</p>
<pre><code>import socket
import select
import sys
class Server:
def __init__(self, host, port, max_clients):
self.host = host
self.port = port
self.max_clients = max_clients
self.clients = {}
def run(self):
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.bind((self.host, self.port))
self.server.listen(self.max_clients)
print 'Listening on %s' % ('%s:%s' % self.server.getsockname())
self.clients[self.server] = 'server'
while True:
read_sockets, write_sockets, error_sockets = select.select(self.clients.keys(), [], [])
for connection in read_sockets:
if connection == self.server:
client_connection, addr = self.server.accept()
self.setup_user(client_connection)
else:
try:
message = connection.recv(4096)
if message != '':
self.broadcast(connection, '\n<' + self.clients[connection] + '>' + message)
except:
self.broadcast(connection, '\n[%s has left the chat]' % self.clients[connection])
connection.close()
del self.clients[connection]
continue
self.server.close()
def setup_user(self, connection):
try:
name = connection.recv(1024).strip()
except socket.error:
return
if name in self.clients.keys():
connection.send('Username is already taken\n')
else:
self.clients[connection] = name
self.broadcast(connection, '\n[%s has enterred the chat]' % name)
def broadcast(self, sender, message):
print message,
for connection, name in self.clients.items():
if connection != sender:
try:
connection.send(message)
except socket.error:
pass
if __name__ == '__main__':
if (len(sys.argv) < 3):
print 'Format requires: python server.py hostname portno'
sys.exit()
server = Server(sys.argv[1], int(sys.argv[2]), 10)
server.run()
</code></pre>
<p>client.py</p>
<pre><code>import socket
import select
import sys
class Client:
def __init__(self, username):
self.username = username
def prompt(self):
sys.stdout.write('<You> ')
sys.stdout.flush()
def connect_to(self, hostname, portno):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.settimeout(2)
try:
server_socket.connect((hostname, portno))
except:
print 'Connection error'
sys.exit()
server_socket.send(self.username)
print 'Connected to host'
self.prompt()
while True:
socket_list = [sys.stdin, server_socket]
read_sockets, write_sockets, error_sockets = select.select(socket_list, [], [])
for chosen_socket in read_sockets:
if chosen_socket == server_socket:
message = chosen_socket.recv(4096)
if not message:
print 'Connection error: no data'
sys.exit()
else:
sys.stdout.write(message)
self.prompt()
else:
message = sys.stdin.readline()
server_socket.send(message)
self.prompt()
if __name__ == '__main__':
if (len(sys.argv) < 4):
print 'Format requires: python client.py username hostname portno'
sys.exit()
client = Client(sys.argv[1])
client.connect_to(sys.argv[2], int(sys.argv[3]))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T21:23:09.350",
"Id": "498112",
"Score": "9",
"body": "First suggestion is to stop using Python 2.x because it's end of life."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T05:17:42.777",
"Id": "252692",
"Score": "4",
"Tags": [
"python",
"python-2.x",
"networking",
"socket"
],
"Title": "Simple chat server in Python"
}
|
252692
|
<p>The program is meant to collect from the user:</p>
<ol>
<li>The function under which to calculate the area</li>
<li>The left and right boundaries of the region</li>
<li>The amount and position of rectangles to use to approximate the area</li>
</ol>
<p>Then run the calculation. Finally, the user is given the option to do another calculation.</p>
<pre><code>import re
print('This is a calculator that determines the Riemann Sum\n\tfor a finite number of rectangles.\n\nYou can quit the program at any time by entering "end".\n')
# Function to escape the program
def escape():
print('Thanks for using the Riemann Sum Calculator! Goodbye!')
quit()
# Calculations for the area under the curve
def right_riemann_sum():
total_area = 0
for k in range(rectangles):
x = left_bound + (k + 1) * delta_x
total_area += delta_x * eval(function.replace("x", str(x)))
print('The area under the curve is %s' % total_area)
def left_riemann_sum():
total_area = 0
for k in range(rectangles):
x = left_bound + k * delta_x
total_area += delta_x * eval(function.replace("x", str(x)))
print('The area under the curve is %s' % total_area)
def midpoint_riemann_sum():
total_area = 0
for k in range(rectangles):
x = left_bound + ((k + 1) - (delta_x / 2))
total_area += delta_x * eval(function.replace("x", str(x)))
print('The area under the curve is %s' % total_area)
while True:
total_area = 0
function = input("What is the function? (must be entered in python math syntax for now... sorry! \n\nf(x) = " )
if function.upper() == "END":
escape()
left_bound = input("What is the left bound? ")
if left_bound.upper() == "END":
escape()
#Regex number check
while re.match(r'(\A\-?\d*\.?\d+$)', left_bound) == None:
if left_bound.upper() == "END":
escape()
print("Please enter only numbers.")
left_bound = input("What is the left bound? ")
left_bound = float(left_bound)
right_bound = input("What is the right bound? ")
if right_bound.upper() == "END":
escape()
while re.match(r'(\A\-?\d*\.?\d+$)', right_bound) == None:
if right_bound.upper() == "END":
escape()
print("Please enter only numbers.")
right_bound = input("What is the right bound? ")
right_bound = float(right_bound)
rectangles = input("How many rectangles do you need? ")
if rectangles.upper() == "END":
escape()
while rectangles == "0":
if rectangles.upper() == "END":
escape()
print('The number of rectangles cannot be 0.')
rectangles = input("How many rectangles do you need? ")
while re.match(r'(\A\d+$)', rectangles) == None:
if rectangles.upper() == "END":
escape()
print("Please enter only whole numbers.")
rectangles = input("How many rectangles do you need? ")
rectangles = int(rectangles)
delta_x = (right_bound - left_bound) / rectangles
# Loop if user wants to use same function
while 1 == 1:
total_area = 0
sum_type = input("Do you need the right, left, or midpoint Riemann sum? ")
# Forcing user to use desired inputs
while re.match(r'(LEFT|RIGHT|MIDPOINT|END)', sum_type.upper()) == None:
print("Just use one of the words, man.")
sum_type = input("Left, right, or midpoint? ")
sum_type = sum_type.upper()
if sum_type == "END":
escape()
if sum_type == "RIGHT":
right_riemann_sum()
if sum_type == "LEFT":
left_riemann_sum()
if sum_type == "MIDPOINT":
midpoint_riemann_sum()
another = input("Should we do another? ")
if another.upper() == "END":
escape()
while re.match(r'(YES|NO)', another.upper()) == None:
if another.upper() == "END":
escape()
print('Please enter only "yes" or "no"')
another = input("Should we do another? ")
# If user doesn't want to do another, the program closes
if 'YES'.find(another.upper()) == -1:
escape()
same = input("Is it the same function? ")
if same.upper() == "END":
escape()
while re.match(r'(YES|NO)', same.upper()) == None:
if same.upper() == "END":
escape()
print('Please enter only "yes" or "no"')
same = input("Is it the same function? ")
if 'YES'.find(same.upper()) == -1:
break # Breaks loop on line 79, loops to line 33
</code></pre>
<p>This is my first program that runs continuously until the user tells it to stop. I'm a beginner to Python and programming in general, so mostly I would love any advice on general style.</p>
<p>I'm sure there are more efficient ways to accomplish the goal, too. For example, I wanted the user to be able to exit the program at any time. However, since I'm using different variables for all of the inputs, the only solution that I could come up with was to put the <code>escape()</code> function under each input. Is there a simpler way to do this?</p>
<p>As for more advanced topics, I want to be able to check that the f(x) function is valid, but there are so many valid options. I <em>just</em> learned about regular expressions today, so I thought I'd start figuring out how to use them to check the function. I would also love to allow the user to enter more standard math inputs ("^" for exponents, 2x for multiplying "2" and "x", etc). Would regular expressions be the way to accomplish that, or is there a better option?</p>
<p>Thank you so much in advance for your critique! I'm proud of what I've made so far but I know it can be much better!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T07:00:55.337",
"Id": "498011",
"Score": "0",
"body": "Welcome to Code review, please [edit] your title so that it only states the task accomplished by your code, anything else belongs to the body of the question"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T19:36:50.570",
"Id": "498107",
"Score": "1",
"body": "A few suggestions for practice since you seem to be on the right track: Could you pull all the input checking into a separate function called once per loop? Could you map each input to a function using dict? How about add the choice to select between either a riemann sum or monte carlo and then implement a Monte Carlo simulation? None of those should be particularly hard and all would give you good practice"
}
] |
[
{
"body": "<p>There are a couple of bad patterns in here, for what is an otherwise not bad looking code for a beginner.</p>\n<p>The most important of them is to <strong>not</strong> do the following (this is an example):</p>\n<pre><code>def do_something():\n something = another_variable_defined_below * 2\n\n# bunch of code\n\nsomething=3\n</code></pre>\n<p>So, looking at :</p>\n<pre><code>def right_riemann_sum():\n total_area = 0\n for k in range(rectangles):\n x = left_bound + (k + 1) * delta_x\n total_area += delta_x * eval(function.replace("x", str(x)))\n print('The area under the curve is %s' % total_area)\n</code></pre>\n<p>I'm wondering where do <code>rectangles, left_bound, delta_x, function</code> are coming from? In general, unless you're using some constants that are defined at the beginning of your code or you're inside a class, if a function needs to use some variables, they should be parameters to the method :</p>\n<pre><code>def right_riemann_sum(rectangles, left_bound, delta_x, function):\n</code></pre>\n<p>Because otherwise it gets confusing, what are the value of these parameters, how do I know if they're modified elsewhere or if they can be <code>None</code>.</p>\n<p>Next, you'll want to have a better name for the variable <code>rectangles</code> (the other ones are looking good from what I saw). For example, <code>rectangles</code> is misleading. <code>rectangles</code> would be a good name for a list of rectangles. But in the case of the Riemann's sum, that variable contains a number of rectangles, so <code>number_of_rectangles</code> or <code>num_rectangles</code> would be more appropriate.</p>\n<p>Try not to repeat yourself when possible. There is obvious duplicated code when asking for left and right bound, so why not create a function?</p>\n<pre><code>def ask_for_bound(bound_name):\n question = "What is the {0} bound? ".format(bound_name)\n bound = input(question)\n\n if bound.upper() == "END":\n escape()\n\n #Regex number check\n while re.match(r'(\\A\\-?\\d*\\.?\\d+$)', bound) == None:\n if bound.upper() == "END":\n escape()\n\n print("Please enter only numbers.")\n bound = input(question)\n\n return float(left_bound)\n</code></pre>\n<p>Your usage of regex aren't bad, but the thing about regex is that they're hard to read : <code>(\\A\\-?\\d*\\.?\\d+$)</code> checks for a floating point number. I would either :</p>\n<ul>\n<li>compile the regex into a variable <code>is_float_number = re.compile(r"(\\A\\-?\\d*\\.?\\d+$)")</code></li>\n<li>ditch the regex.</li>\n</ul>\n<p>The regex works, that's good. But instead of working with the whole match/capture routine, you could consider that the user won't mess up and do this :</p>\n<pre><code>bound = 0\nwhile True:\n try:\n bound = float(input(question))\n break\n except ValueError:\n pass\n</code></pre>\n<p>This way, you don't check if the string matches a floating point number, you just try to parse it and deal with the potential problem that the input isn't good.</p>\n<p>There's another thing you should consider. Say you're filling a form on Google Forms and midway through you want to quit. Are you going to expect that there's a "quit" button near every entry of the form? You'll probably just close your browser tab and go do something else.</p>\n<p>I'd think of it the same way with your program. Because right now you have soooo many <code>if some_input == "END" : escape()</code>. It clutters the code a lot. If you really want to leave the option for the user to quit at any moment, consider wrapping the <code>input</code> function this way :</p>\n<pre><code>def input_with_escape(question):\n response = input(question)\n\n if response.upper() == "END": \n escape()\n\n return response\n</code></pre>\n<p>This way you won't have to check for <code>END</code> every time (Also, if you never specify to your user they can quit using END, they'll never use it).</p>\n<p>Finally, replace <code>while 1 == 1</code> by <code>while True</code></p>\n<p>Basically, try to keep your code that interacts with your user away from the code that has logic into it. Having <code>print</code> at the end of functions instead of <code>return</code> is usually not a good sign.</p>\n<p>You've done a good job and you use most tools properly, there're just a couple of points you need to look after regarding clean code :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T19:24:50.300",
"Id": "252724",
"ParentId": "252695",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "252724",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T06:38:37.900",
"Id": "252695",
"Score": "4",
"Tags": [
"python",
"beginner",
"regex",
"calculator",
"iteration"
],
"Title": "Calculator that finds the area under a curve"
}
|
252695
|
<p>I was asked to write chess simulation of pieces as a take home interview question and was given <a href="https://pastebin.com/VbgWA5SK" rel="nofollow noreferrer">this spec</a>.</p>
<p>This is what I came up with:</p>
<h3>ChessGenerator.java</h3>
<pre><code>import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
public class ChessGenerator {
private static final int n = 8;
private static final int m = 8;
private static final int[][] board = new int[8][8];
public static void main(String[] args) {
String piece = args[0];
String position = args[1];
Point point = PositionTransformer.translateToPoint(position);
run(piece, position, point);
}
public static List<Point> run(String piece, String position, Point point) {
List<Point> result = null;
if(piece.equals("Horse")) {
result = new Horse().findAllPossibleMoves(board, point.getX(), point.getY());
System.out.println(result.toString());
}
return result;
}
// TODO Remove
public String letterPosition(String position) {
return position.replaceAll("[0-9]","");
}
// TODO Remove
public String numericPosition(String position) {
return position.replaceAll("[^A-Za-z]","");
}
}
</code></pre>
<h3>Horse.java</h3>
<pre><code>import java.util.ArrayList;
import java.util.List;
public class Horse extends Piece {
public List<Point> findAllPossibleMoves(int mat[][], int p, int q) {
List<Point> result = new ArrayList<Point>();
int X[] = {2, 1, -1, -2, -2, -1, 1, 2};
int Y[] = {1, 2, 2, 1, -1, -2, -2, -1};
for (int i = 0; i < 8; i++) {
int x = p + X[i];
int y = q + Y[i];
if (x >= 0 && y >= 0 && x < n && y < m
&& mat[x][y] == 0)
result.add(new Point(x, y));
}
return result;
}
}
</code></pre>
<h3>Piece.java</h3>
<pre><code>import java.util.List;
public abstract class Piece {
public static final int n = 8;
public static final int m = 8;
public abstract List<Point> findAllPossibleMoves(int board[][], int m, int n);
}
</code></pre>
<h3>Point.java</h3>
<pre><code>public class Point {
private int x;
private int y;
public int getY() {
return y;
}
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
@Override
public String toString() {
return "Point{" +
"x=" + x +
", y=" + y +
'}';
}
}
</code></pre>
<h3>PositionTransformer.java</h3>
<pre><code>import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class PositionTransformer {
private static final Map<String, Point> transformer = new HashMap<String, Point>() {{
put("A1", new Point(7,0));
put("A2", new Point(6,0));
put("A3", new Point(5,0));
put("A4", new Point(4,0));
put("A5", new Point(3,0));
put("A6", new Point(2,0));
put("A7", new Point(1,0));
put("A8", new Point(0,0));
put("B1", new Point(7,1));
put("B2", new Point(6,1));
put("B3", new Point(5,1));
put("B4", new Point(4,1));
put("B5", new Point(3,1));
put("B6", new Point(2,1));
put("B7", new Point(1,1));
put("B8", new Point(0,1));
put("C1", new Point(7,2));
put("C2", new Point(6,2));
put("C3", new Point(5,2));
put("C4", new Point(4,2));
put("C5", new Point(3,2));
put("C6", new Point(2,2));
put("C7", new Point(1,2));
put("C8", new Point(0,2));
put("D1", new Point(7,3));
put("D2", new Point(6,3));
put("D3", new Point(5,3));
put("D4", new Point(4,3));
put("D5", new Point(3,3));
put("D6", new Point(2,3));
put("D7", new Point(1,3));
put("D8", new Point(0,3));
put("E1", new Point(7,4));
put("E2", new Point(6,4));
put("E3", new Point(5,4));
put("E4", new Point(4,4));
put("E5", new Point(3,4));
put("E6", new Point(2,4));
put("E7", new Point(1,4));
put("E8", new Point(0,4));
put("F1", new Point(7,5));
put("F2", new Point(6,5));
put("F3", new Point(5,5));
put("F4", new Point(4,5));
put("F5", new Point(3,5));
put("F6", new Point(2,5));
put("F7", new Point(1,5));
put("F8", new Point(0, 5));
put("G1", new Point(7,6));
put("G2", new Point(6,6));
put("G3", new Point(5,6));
put("G4", new Point(4,6));
put("G5", new Point(3,6));
put("G6", new Point(2,6));
put("G7", new Point(1,6));
put("G8", new Point(0, 6));
put("H1", new Point(7,7));
put("H2", new Point(6,7));
put("H3", new Point(5,7));
put("H4", new Point(4,7));
put("H5", new Point(3,7));
put("H6", new Point(2,7));
put("H7", new Point(1,7));
put("H8", new Point(0, 7));
}};
public static Point translateToPoint(String position) {
return transformer.get(position);
}
public static Map<String, Point> unmodifiableMap() {
return Collections.unmodifiableMap(transformer);
}
}
</code></pre>
<h3>This is the feedback I received</h3>
<p>Variables names must be self-explanatory.
Unused variables.
Hardcoded PositionTransformer. Could have written a logic for that.
Implemented only 1 piece i.e. Horse.</p>
<p>I agree with unused variables and due to time constraint only implemented horse piece. Not sure what is meant by <code>PositionTransformer</code> review comment. How else could the code be improved?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T08:35:28.127",
"Id": "498022",
"Score": "1",
"body": "You should adjust the page title to \"chess knight move generator\" since you only implemented that. As a general chess move generator, your code is off-topic since it doesn't fully implement the spec."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T13:29:52.930",
"Id": "498059",
"Score": "1",
"body": "I think you should add the specs in this post :) Imagine the pastebin was to be deleted, we'd lose context on your problem."
}
] |
[
{
"body": "<p>I would implement <code>Piece</code> as an <code>enum</code>, with an element for each piece.</p>\n<p>A <code>ChessBoard</code> would have <code>rows</code> and <code>cols</code> instead of <code>n</code> and <code>m</code>, where each cell would be a <code>Piece</code>.</p>\n<pre><code>ChessBoard b = new ChessBoard();\nb.setPieceAt(0, 0, Piece.ROOK);\nb.getPieceAt(0, 0); // Piece.ROOK\n</code></pre>\n<p>The <code>ChessBoard</code> could, for example, return <code>Piece.NONE</code> for empty spaces and <code>null</code> for out-of-bounds access. This would save you a lot of bounds-checking during move generation. An implementation trick would be to reserve extra rows and columns in the backing <code>Piece[][]</code> array, so that there are 2 empty rows and columns to either side of valid in-the-board positions; this would remove bounds-checking from the <code>ChessBoard</code> code too.</p>\n<p>A <code>Position</code> would be an immutable row-col combination, as in "e4", and would be usable on a board to set and get pieces (but I would still keep check-by-coordinates as seen above for quicker move generation). Positions would know how to parse and write themselves.</p>\n<p>Within the <code>Piece</code> enum, you could implement parsing and printing (so that, say, a <code>PAWN</code> can print itself as a <code>"Pawn"</code>). Move generation could use, without exposing them, several helper methods::</p>\n<pre><code>public List<Position> generateMoves(Position p, ChessBoard b) {\n List<Position> moves = new ArrayList<>();\n switch (this) {\n case PAWN:\n generatePawnMoves(p, b, moves); // private method\n break;\n case QUEEN:\n generateDiagonalMoves(p, b, moves);\n generateHorizontalMoves(p, b, moves);\n break; \n // ... \n }\n return moves;\n}\n</code></pre>\n<p>Since the statement does not require you to implement black and white pieces, I would ignore all those aspects. They can all be added later, and the exercise explicitly requests not over-complicating the answer.</p>\n<p>If you look further into move generation, your <code>Knight</code> code contains 2 arrays, one of <code>dx</code> and another of <code>dy</code> displacements. Very similar code could generate <code>KING</code> moves (as 8 "jumps", one to each adjacent position), and placing that in a loop that keeps on "jumping" until it hits something would generate Bishop and Rook (and thus Queen) moves. Code reuse is good, because it makes testing your code easier, and gives you shorter code to look at.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T11:55:32.967",
"Id": "252706",
"ParentId": "252697",
"Score": "3"
}
},
{
"body": "<p>Regarding your <code>PositionTransformer</code> comment :</p>\n<p>We have an 8x8 board where columns are represented by letters and rows by numbers (it might be the opposite I don't really play chess). <em>But that doesn't matter to your code.</em> What the code is working with is a 8x8 grid.</p>\n<p>However, your user interacts with the board with letters and numbers. What this means is, instead of using a map of strings that maps to points, I believe your code should only be a grid and you should parse what the user gives you in a format you can use with the grid. For example :</p>\n<p>Note that I haven't coded in Java in awhile, so I'll be writing Java-like pseudo-code that won't compile, but you'll get my idea.</p>\n<pre><code>//Create the board\nint[][] board = new int[8][8];\n\nprivate Point getPositionFromUserInput(String cellId) {\n //You expect a format of [A-H][1-8], so let's first check if this makes sense\n if (!Pattern.matches("[A-H][1-8]", cellId)) {\n throw exception regarding bad argument\n }\n\n //Letters are mapped A=0,..., H=7\n int column = cellId[0] - 'A';\n\n //Numbers are mapped 1=7,...,8=0\n int row = '1' - cell[1] + 7;\n\n return new Point(row, column);\n}\n\n//Return a Point(0,3)\nPoint p = getPositionFromUserInput("A5");\n</code></pre>\n<p>But <strong>frankly</strong>, I think this is a useless abstraction. Your interviewer didn't agree with my it seems, but a chess board is by definition pretty much hardcoded, so there's no need to take time to write specific logic to deal with changing the chess position to a point, as this would lead to potential bugs that could've been avoided. Anyways, I also think that in an interview question, if you can write <strong>why</strong> you did some things, interviewers might agree with you.</p>\n<p>Now, "Variables names must be self-explanatory. Unused variables" is pretty bad. In an interview question, you should give it your all to give a solution that's as close as possible to what you'd do when you work and unused variables is a pretty red flag regarding code quality, as are poor variable names. Even though sometimes poor variable names are inevitable.</p>\n<p>Now, there's one other red flag I see in the code that'd make me question myself as an interviewer : Why is there only a setter for the <code>x</code> variable of <code>Point</code> and not for <code>y</code>? I believe you added it and forgot to remove it, but I may be wrong. Anyways, a <code>Point</code> should be an immutable structure, it's just easier to manage. Why should a point change location? It's a pretty static thing.</p>\n<p>Finally, you use an abstract class to define <code>Piece</code>, which I think isn't a bad idea in itself, but in both the <code>Piece</code> and <code>Knight</code> class you don't use any instance variables/functions, so abstraction seems like a bad idea. Try to answer this question : Why would you use an abstract method <code>findAllPossibleMoves</code> when it could be <code>static</code> and it wouldn't change a thing?</p>\n<p>Maybe what you want isn't a <code>Knight</code> class, but a <code>KnightMoveGenerator</code> that could implement an interface <code>MoveGenerator</code>?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T14:05:34.113",
"Id": "252713",
"ParentId": "252697",
"Score": "5"
}
},
{
"body": "<p>First, the spec is crap. It uses the words chess and chessboard but gives them completely unusual meanings. The best thing to do is with such a spec is to reject it and require clear instructions, using the exact same terms that the rest of the world uses as well. Even if refining the spec costs a day of work, this is worth it since later in the implementation changing any small detail will cost 100 days. If you spot something wrong at the very beginning, fix it quickly before you get used to it.</p>\n<p>This spec is crap for the following reasons:</p>\n<ul>\n<li>It names the rows A to H. In chess, the rows are called ranks instead, and they are numbered from 1 to 8.</li>\n<li>It names the columns 1 to 8. In chess, the columns are called files instead, and they are numbered from A to H.</li>\n<li>It calls the Knight a Horse. It's called a knight, that's the international standard when talking about chess in English.</li>\n<li>2 vertical + 1 horizontal step are not 2.5 steps. In the usual drawings of knight moves, it's either <span class=\"math-container\">\\$\\sqrt5 \\approx 2.236\\$</span> steps for a direct move or <span class=\"math-container\">\\$1+\\sqrt2\\approx2.414\\$</span> steps for a straight move followed by a diagonal move. To go exactly 2.5 steps, the horse would first have to go 1.25 steps straight, then make a sharp turn towards the target cell, which at that point is exactly 1.25 steps away. What could be the point of requiring exactly 2.5 steps in the spec?</li>\n<li>I hope they meant "on an otherwise empty chessboard" when they wrote "on an empty chessboard". I'll interpret it that way for now.</li>\n</ul>\n<p>All these are things you should have noticed when trying to implement the full exercise.</p>\n<p>Now to your code:</p>\n<pre class=\"lang-java prettyprint-override\"><code> private static final int n = 8;\n</code></pre>\n<p>This line already reveals that you don't know the Java naming conventions. This is a constant (because of the <code>static final</code>), and constants are written in uppercase.</p>\n<p>The variable name is complete crap. The name <code>n</code> stands for a number. It's obvious from the code that 8 is a number, and it's also obvious that 8 is an integer. Therefore the variable name does not add a single bit of information to the code. In cases like this, just omit the variable name and write the number directly. Or, pick a better name. One that describes the purpose of the variable. This one could be named <code>FILES</code> or <code>RANKS</code>. The same applies to your other variables, they are equally bad. On the other hand, the method names you chose are good, which means you just need to apply this knowledge to the variable names as well.</p>\n<pre class=\"lang-java prettyprint-override\"><code>new Horse()\n</code></pre>\n<p>Why do you create a new horse each time you want to find the possible moves? Your Horse class does not have any fields or other state that it might need to preserve. Therefore, creating a new object each time is a waste of computing time.</p>\n<pre class=\"lang-java prettyprint-override\"><code> List<Point> result = new ArrayList<Point>();\n</code></pre>\n<p>The second <code><Point></code> is redundant, you can just write <code><></code> without repeating the type name. Your IDE should have offered to fix this for you. If it didn't, your IDE is not good enough. Get a better one, IntelliJ can do this, and it has over 1000 other inspections that help you write good code. Even Eclipse can fix this for you, and Eclipse is lagging behind almost 10 years in Java features, and 20 years in usability. So there is absolutely no excuse having this redundancy in the code.</p>\n<p>As others already said, the <code>PositionTransformer</code> looks really boring and unimaginative. You're lucky that a chess board is only 8×8 and not 19×19 like a go board. For comparison, here is some C code that I wrote to transform a string into a square:</p>\n<pre class=\"lang-c prettyprint-override\"><code>static bool\nParse_Square(const char *str, Square *out_square)\n{\n const char *files = "ABCDEFGH";\n const char *file = strchr(files, str[0]);\n if (file == NULL)\n return false;\n\n const char *ranks = "12345678";\n const char *rank = strchr(ranks, str[1]);\n if (rank == NULL)\n return false;\n\n out_square->file = file - files;\n out_square->rank = rank - ranks;\n return true;\n}\n</code></pre>\n<p>That is much shorter and it is easily extendible to other board sizes, with minimal effort. Just imagine if you wanted to have lowercase board coordinates instead of uppercase ones. In your code, you had to adjust 64 lines of code. In my code, it would be a single line of code.</p>\n<pre><code> private static final Map<String, Point> transformer = new HashMap<>() {{\n put("A1", new Point(7,0));\n put("A2", new Point(6,0));\n }};\n</code></pre>\n<p>The double braces <code>{{ … }}</code> are an anti-pattern. They needlessly create a class that derives from HashMap, while all you need is a HashMap. In this program, there is no need for inheritance or derived classes.</p>\n<p>Your code is not only missing 5 of the 6 chess pieces, it is also lacking unit tests, and this was part of the requirement. You wrote that you didn't have enough time. This may be an excuse for the exam, but not for your post to Code Review. Here you have plenty of time and you should have added the full code and the unit tests.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T14:48:13.617",
"Id": "498167",
"Score": "0",
"body": "Your parsing code is C++, and not plain C. I would not place so much emphasis on the spec being not-really-chess, because implementations can really show quite a lot about how someone programs; being too similar to real chess could lead to copy-pasting of actual chess implementations, of which there are many."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T15:19:15.850",
"Id": "498170",
"Score": "0",
"body": "@tucuxi My parsing code is pure C. Why do you think it could be C++?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T15:49:16.910",
"Id": "498174",
"Score": "1",
"body": "\"This may be an excuse for the exam, but not for your post to Code Review\" I disagree. The code works fine here and this is a reviewable code unit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T17:15:27.370",
"Id": "498182",
"Score": "0",
"body": "@RolandIllig today I learnt that the `static` keyword could be used to limit the scope of plain-C functions, and that C99 added a `bool` `#define` to the standard via `stdbool.h`. I stand corrected (and feel old because I still remember declaring my own `#defines`). On the other hand, I still think that OP's spec is not as bad as you make it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T17:44:58.247",
"Id": "498184",
"Score": "0",
"body": "@tucuxi Yep, the other parts of the spec are fine. But switching the coordinate axes is a real problem in other contexts, and naming the Knight a Horse is also unusual enough that as a software developer you should ask whether these choices have been made intentionally to deviate from well-established standards."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T23:56:50.967",
"Id": "252735",
"ParentId": "252697",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "252713",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T07:32:06.953",
"Id": "252697",
"Score": "2",
"Tags": [
"java",
"beginner",
"interview-questions"
],
"Title": "Chess knight move simulator"
}
|
252697
|
<p>I am writing a pong game in Python that uses voice input to move the paddles.
I have implemented multithreading so that the google speech recognition module can always run in a separate thread from the main game. However, it doesn't seem to be running on the separate thread and I have no way of finding out how. I want to improve the code so that it can run the speech recognition on a separate thread and stop the game from hanging.</p>
<p>I am also open to any other criticism of the code provided here (readability, clarity, organization, etc).</p>
<h3>Here are the imports and global variables</h3>
<pre class="lang-py prettyprint-override"><code># native imports
import math
import random
import pyglet
import sys
from playsound import playsound
from gtts import gTTS
import pyttsx3
import os
# speech recognition library
# -------------------------------------#
# threading so that listenting to speech would not block the whole program
import threading
# speech recognition (default using google, requiring internet)
import speech_recognition as sr
# -------------------------------------#
# pitch & volume detection
# -------------------------------------#
import aubio
import numpy as num
import pyaudio
import wave
# -------------------------------------#
quit = False
debug = 1
# pitch & volume detection
# -------------------------------------#
# PyAudio object.
p = pyaudio.PyAudio()
# Open stream.
stream = p.open(format=pyaudio.paFloat32,
channels=1, rate=44100, input=True,
frames_per_buffer=1024)
# Aubio's pitch detection.
pDetection = aubio.pitch("default", 2048,
2048//2, 44100)
# Set unit.
pDetection.set_unit("Hz")
pDetection.set_silence(-40)
# -------------------------------------#
# keeping score of points:
p1_score = 0
p2_score = 0
r = sr.Recognizer()
</code></pre>
<h3>Here is the method for voice input</h3>
<pre class="lang-py prettyprint-override"><code>def listen_to_audio():
# speech_thread.start()
results = None
with sr.Microphone() as source:
print("[speech recognition] Say something!")
audio = r.listen(source)
# recognize speech using Google Speech Recognition
try:
# for testing purposes, we're just using the default API key
# to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
# instead of `r.recognize_google(audio)`
recog_results = r.recognize_google(audio)
print(
"[speech recognition] Google Speech Recognition thinks you said \"" + recog_results + "\"")
results = recog_results
except sr.UnknownValueError:
results ="Unknown Value error! Google Speech Recognition could not understand audio"
except sr.RequestError as e:
results = "Request error! Could not request results from Google Speech Recognition service; {0}".format(e)
return results
</code></pre>
<h3>Here is the code for gameplay</h3>
<pre class="lang-py prettyprint-override"><code>
def main():
class Ball(object):
def __init__(self):
self.debug = 0
self.TO_SIDE = 5
self.x = 50.0 + self.TO_SIDE
self.y = float(random.randint(0, 450))
self.x_old = self.x # coordinates in the last frame
self.y_old = self.y
self.vec_x = 2**0.5 / 2 # sqrt(2)/2
self.vec_y = random.choice([-1, 1]) * 2**0.5 / 2
class Player(object):
def __init__(self, NUMBER, screen_WIDTH=800):
"""NUMBER must be 0 (left player) or 1 (right player)."""
self.NUMBER = NUMBER
self.x = 50.0 + (screen_WIDTH - 100) * NUMBER
self.y = 50.0
self.last_movements = [0]*4 # short movement history
# used for bounce calculation
self.up_key, self.down_key = None, None
self.move_up, self.move_down = None, None
if NUMBER == 0:
self.up_key = pyglet.window.key.W
self.down_key = pyglet.window.key.S
self.move_up = "up"
self.move_down = "down"
elif NUMBER == 1:
self.up_key = pyglet.window.key.O
self.down_key = pyglet.window.key.L
self.move_up = "forward"
self.move_down = "backward"
class Model(object):
"""Model of the entire game. Has two players and one ball."""
def __init__(self, DIMENSIONS=(800, 450)):
"""DIMENSIONS is a tuple (WIDTH, HEIGHT) of the field."""
# OBJECTS
WIDTH = DIMENSIONS[0]
self.players = [Player(0, WIDTH), Player(1, WIDTH)]
self.ball = Ball()
# DATA
self.pressed_keys = set() # set has no duplicates
self.quit_key = pyglet.window.key.Q
self.speed = 6 # in pixels per frame
self.ball_speed = self.speed # * 2.5
self.WIDTH, self.HEIGHT = DIMENSIONS
# STATE VARS
self.paused = False
self.i = 0 # "frame count" for debug
def reset_ball(self, who_scored):
"""Place the ball anew on the loser's side."""
if debug:
print(str(who_scored)+" scored. reset.")
self.ball.y = float(random.randint(0, self.HEIGHT))
self.ball.vec_y = random.choice([-1, 1]) * 2**0.5 / 2
if who_scored == 0:
self.ball.x = self.WIDTH - 50.0 - self.ball.TO_SIDE
self.ball.vec_x = - 2**0.5 / 2
elif who_scored == 1:
self.ball.x = 50.0 + self.ball.TO_SIDE
self.ball.vec_x = + 2**0.5 / 2
elif who_scored == "debug":
self.ball.x = 70 # in paddle atm -> usage: hold f
self.ball.y = self.ball.debug
self.ball.vec_x = -1
self.ball.vec_y = 0
self.ball.debug += 0.2
if self.ball.debug > 100:
self.ball.debug = 0
def check_if_oob_top_bottom(self):
"""Called by update_ball to recalc. a ball above/below the screen."""
# bounces. if -- bounce on top of screen. elif -- bounce on bottom.
b = self.ball
if b.y - b.TO_SIDE < 0:
illegal_movement = 0 - (b.y - b.TO_SIDE)
b.y = 0 + b.TO_SIDE + illegal_movement
b.vec_y *= -1
elif b.y + b.TO_SIDE > self.HEIGHT:
illegal_movement = self.HEIGHT - (b.y + b.TO_SIDE)
b.y = self.HEIGHT - b.TO_SIDE + illegal_movement
b.vec_y *= -1
def check_if_oob_sides(self):
global p2_score, p1_score
"""Called by update_ball to reset a ball left/right of the screen."""
b = self.ball
if b.x + b.TO_SIDE < 0: # leave on left
self.reset_ball(1)
p2_score += 1
elif b.x - b.TO_SIDE > self.WIDTH: # leave on right
p1_score += 1
self.reset_ball(0)
def check_if_paddled(self):
"""Called by update_ball to recalc. a ball hit with a player paddle."""
b = self.ball
p0, p1 = self.players[0], self.players[1]
angle = math.acos(b.vec_y)
factor = random.randint(5, 15)
cross0 = (b.x < p0.x + 2*b.TO_SIDE) and (b.x_old >= p0.x + 2*b.TO_SIDE)
cross1 = (b.x > p1.x - 2*b.TO_SIDE) and (b.x_old <= p1.x - 2*b.TO_SIDE)
if cross0 and -25 < b.y - p0.y < 25:
playhit = threading.Thread(target=hit(), args=())
playhit.start()
hit()
if debug:
print("hit at "+str(self.i))
illegal_movement = p0.x + 2*b.TO_SIDE - b.x
b.x = p0.x + 2*b.TO_SIDE + illegal_movement
angle -= sum(p0.last_movements) / factor / self.ball_speed
b.vec_y = math.cos(angle)
b.vec_x = (1**2 - b.vec_y**2) ** 0.5
elif cross1 and -25 < b.y - p1.y < 25:
playhit = threading.Thread(target=hit(), args=())
playhit.start()
hit()
if debug:
print("hit at "+str(self.i))
illegal_movement = p1.x - 2*b.TO_SIDE - b.x
b.x = p1.x - 2*b.TO_SIDE + illegal_movement
angle -= sum(p1.last_movements) / factor / self.ball_speed
b.vec_y = math.cos(angle)
b.vec_x = - (1**2 - b.vec_y**2) ** 0.5
# -------------- Ball position: you can find it here -------
def update_ball(self):
"""
Update ball position with post-collision detection.
I.e. Let the ball move out of bounds and calculate
where it should have been within bounds.
When bouncing off a paddle, take player velocity into
consideration as well. Add a small factor of random too.
"""
self.i += 2 # "debug"
b = self.ball
b.x_old, b.y_old = b.x, b.y
b.x += b.vec_x * self.ball_speed
b.y += b.vec_y * self.ball_speed
self.check_if_oob_top_bottom() # oob: out of bounds
self.check_if_oob_sides()
self.check_if_paddled()
def update(self, move_options):
"""Work through all pressed keys, update and call update_ball."""
pks = self.pressed_keys
if quit:
sys.exit(1)
if self.quit_key in pks:
exit(0)
if pyglet.window.key.R in pks and debug:
self.reset_ball(1)
if pyglet.window.key.F in pks and debug:
self.reset_ball("debug")
# -------------- If you want to change paddle position, change it here
# player 1: the user controls the left player by W/S but you should change it to VOICE input
p1 = self.players[0]
p1.last_movements.pop(0)
# if p1.up_key in pks and p1.down_key not in pks: # change this to voice input
if p1.move_up in move_options and p1.move_down not in move_options:
p1.y -= self.speed
p1.last_movements.append(-self.speed)
# elif p1.up_key not in pks and p1.down_key in pks: # change this to voice input
elif p1.move_up not in move_options and p1.move_down in move_options:
p1.y += self.speed
p1.last_movements.append(+self.speed)
else:
# notice how we popped from _place_ zero,
# but append _a number_ zero here. it's not the same.
p1.last_movements.append(0)
# ----------------- DO NOT CHANGE BELOW ----------------
# player 2: the other user controls the right player by O/L
p2 = self.players[1]
p2.last_movements.pop(0)
# if p2.up_key in pks and p2.down_key not in pks: # change this to voice input
if p2.move_up in move_options and p2.move_down not in move_options:
p2.y -= self.speed
p2.last_movements.append(-self.speed)
# elif p2.up_key not in pks and p2.down_key in pks: # change this to voice input
elif p2.move_up not in move_options and p2.move_down in move_options:
p2.y += self.speed
p2.last_movements.append(+self.speed)
else:
# notice how we popped from _place_ zero,
# but append _a number_ zero here. it's not the same.
p2.last_movements.append(0)
self.update_ball()
label.text = str(p1_score)+':'+str(p2_score)
class Controller(object):
def __init__(self, model):
self.m = model
# self.move_options = None
def listen(self):
self.move_options = listen_to_audio()
return self.move_options
def on_key_press(self, symbol, modifiers):
# `a |= b`: mathematical or. add to set a if in set a or b.
# equivalent to `a = a | b`.
# XXX p0 holds down both keys => p1 controls break # PYGLET!? D:
self.m.pressed_keys |= set([symbol])
def on_key_release(self, symbol, modifiers):
if symbol in self.m.pressed_keys:
self.m.pressed_keys.remove(symbol)
def update(self):
self.m.update(self.listen())
class View(object):
def __init__(self, window, model):
self.w = window
self.m = model
# ------------------ IMAGES --------------------#
# "white_square.png" is a 10x10 white image
lplayer = pyglet.resource.image("white_square.png")
self.player_spr = pyglet.sprite.Sprite(lplayer)
def redraw(self):
# ------------------ PLAYERS --------------------#
TO_SIDE = self.m.ball.TO_SIDE
for p in self.m.players:
self.player_spr.x = p.x//1 - TO_SIDE
# oh god! pyglet's (0, 0) is bottom right! madness.
self.player_spr.y = self.w.height - (p.y//1 + TO_SIDE)
self.player_spr.draw() # these 3 lines: pretend-paddle
self.player_spr.y -= 2*TO_SIDE
self.player_spr.draw()
self.player_spr.y += 4*TO_SIDE
self.player_spr.draw()
# ------------------ BALL --------------------#
self.player_spr.x = self.m.ball.x//1 - TO_SIDE
self.player_spr.y = self.w.height - (self.m.ball.y//1 + TO_SIDE)
self.player_spr.draw()
class Window(pyglet.window.Window):
def __init__(self, *args, **kwargs):
DIM = (800, 450) # DIMENSIONS
super(Window, self).__init__(width=DIM[0], height=DIM[1],
*args, **kwargs)
# ------------------ MVC --------------------#
the_window = self
self.model = Model(DIM)
self.view = View(the_window, self.model)
self.controller = Controller(self.model)
# ------------------ CLOCK --------------------#
fps = 30.0
pyglet.clock.schedule_interval(self.update, 1.0/fps)
# pyglet.clock.set_fps_limit(fps)
def on_key_release(self, symbol, modifiers):
self.controller.on_key_release(symbol, modifiers)
def on_key_press(self, symbol, modifiers):
self.controller.on_key_press(symbol, modifiers)
def update(self, *args, **kwargs):
# XXX make more efficient (save last position, draw black square
# over that and the new square, don't redraw _entire_ frame.)
self.clear()
self.controller.update()
self.view.redraw()
window = Window()
label = pyglet.text.Label(str(p1_score)+':'+str(p2_score),
font_name='Times New Roman',
font_size=36,
x=window.width//2, y=window.height//2,
anchor_x='center', anchor_y='center')
@window.event
def on_draw():
# window.clear()
label.draw()
if debug:
print("init window...")
if debug:
print("done! init app...")
pyglet.app.run()
speech_thread = threading.Thread(target=listen_to_audio, args=(), name="Speech Thread")
speech_thread.start()
# -------------------------------------#
spoken_voice_thread = threading.Thread(target=SpeakText, args=(), name="Spoken voice thread")
spoken_voice_thread.start()
# pitch & volume detection
# -------------------------------------#
# start a thread to detect pitch and volume
microphone_thread = threading.Thread(target=sense_microphone, args=(), name="microphone thread")
microphone_thread.start()
# -------------------------------------#
</code></pre>
<h3>Code to implement multithreading</h3>
<pre class="lang-py prettyprint-override"><code>speech_thread = threading.Thread(target=listen_to_audio, args=(), name="Speech Thread")
speech_thread1 = threading.Thread(target=listen_to_audio, args=(), name="Speech Thread")
speech_thread.start()
speech_thread1.start()
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T08:47:24.867",
"Id": "252700",
"Score": "1",
"Tags": [
"python-3.x",
"multithreading",
"pygame",
"pong"
],
"Title": "Python console pong game - multithreading"
}
|
252700
|
<p>I have completed my lab assignment for class, but I'm still wondering if there's any ways I could better optimize my code. specifically my methods isSeatAvailable and reserveSeat.
Here is my problem: Write a program that displays, examines and manipulates a two dimensional array
representing plane seats for a plane with 12 rows and 4 seats per row.
Write methods for the following operations:</p>
<p>fillSeatsRandomly:Fills the array with random values in range from 0 to 1.
Zero represents an empty seat and one represents a reserved seat.</p>
<p>displaySeats: Displays all the seats in the plane row by row. Empty seat is
displayed as 0 and a reserved seat is displayed as X. Create vertical headings
for the row numbers from 1 to 12 on the left hand side and horizontal column
headings from A to D (for the 4 seats in the row).</p>
<p>isSeatAvailable: Receives an integer representing a row number and a character
representing a seat from A to D. This method tests if the specified seat is
available, otherwise it returns false. This method displays an error message
when the seat selection is invalid.</p>
<p>reserveSeat: Reserves a specified seat.
Receives two parameters: an integer representing a row number and a character
representing a seat number from A to D. This method displays an error message
when the seat is invalid.</p>
<p>seatsAvailInRow: counts and returns number of seats available in given row.
Receives an integer representing row number.</p>
<p>findRowWithTwoSeats: This method look for the closest row with two adjacent
available seats. If two adjacent seats are not available it returns 0.</p>
<p>countSeatsAvail: counts the number of all seats available in the plane and
returns that number.</p>
<p>countTakenSeats: counts the number of all seats reserved in the plane and
returns that number.</p>
<p>Here is my code:</p>
<pre><code>public class ArraysLab {
public static void main(String[] args) {
Plane p = new Plane();
p.fillSeatsRandomly();
p.displaySeats();
if (p.isSeatAvailable(2, 'B')) {
System.out.println("You have reserved seat: 2,B");
p.reserveSeat(2, 'B');
p.displaySeats();
}
System.out.println("Sorry, seat: 2,B is already taken");
System.out.println("There is " + p.seatsAvailInRow(5)
+ " seat(s) available in row 5");
System.out.println("Row " + p.findRowWithTwoSeats()
+ " has 2 adjacent seats");
System.out.println("Seats available: " + p.countSeatsAvail());
System.out.println("Seats taken: " + p.countTakenSeats());
}//end of main
}//end of class ArraysLab
class Plane {
int[][] seats = new int[12][4];
public void fillSeatsRandomly() {//fills seats randomly
for (int[] seats1 : seats) {
for (int col = 0; col < seats1.length; col++) {
seats1[col] = (int) Math.round(Math.random());
}//end of nested for
}//end of for
}//end of fill seats randomly
public void displaySeats() {//displays the seats
System.out.print("\tA \tB \tC \tD \n");
for (int row = 0; row < seats.length; row++) {
System.out.print(row + 1 + "");
for (int seatNum = 0; seatNum < seats[row].length; seatNum++) {
if (seats[row][seatNum] == 1) {
System.out.print("\tX ");
} else {
System.out.print("\t0 ");
}
}//end of nested for
System.out.println();
}//end of for
}//end of displaySeats
public boolean isSeatAvailable(int row, char column) { //checks if seat is
//available, returns true if it is and false if not
int rowNum = row - 1;//row number of the seat chosen
char colChar = column;//character of the seat chosen
int colNum = 0;//char converted to int for ease of use
switch (colChar) {
case 'A':
colNum = 0;
break;
case 'B':
colNum = 1;
break;
case 'C':
colNum = 2;
break;
case 'D':
colNum = 3;
}
//end of switch
return seats[rowNum][colNum] == 0;
}//end of isSeatAvail
public void reserveSeat(int row, char column) {//reserves a seat updates array
int rowNum = row - 1;//Row number of seat chosen
int colNum = 0;//Column number of seat chosen
char seatSelect = column;//Character of column chosen
switch (seatSelect) {
case 'A':
colNum = 0;
break;
case 'B':
colNum = 1;
break;
case 'C':
colNum = 2;
break;
case 'D':
colNum = 3;
}//end of switch
seats[rowNum][colNum] = 1;
} //end of reserveSeat
public int seatsAvailInRow(int row) {//checks how many seats are available
//in a row determined returns int value
int rowNum = row - 1;
int rowSum = 0;
int avail;
for (int[] plane1 : seats) {
rowSum = 0;
for (int j = 0; j < plane1.length; j++) {
rowSum += seats[rowNum][j];
} //end of nested for
} //end of for
avail = 4 - rowSum;
return avail;//returns number of seats available
}//end of seatsAvailInRow
public int findRowWithTwoSeats() {//finds the closest row that has
//2 adjacent seats, returns row num, or 0 if none
for (int i = 0; i < seats.length; i++) {
for (int j = 0; j < seats[i].length; j++) {
if (seats[i][0] + seats[i][1] == 0 || seats[i][1]
+ seats[i][2] == 0
|| seats[i][2] + seats[i][3] == 0) {
return i + 1;//returns row num with adjacent seats
}//end of if
} //end of nested for
} //end of for
return 0;//returns 0 if there is no adjacent seats
}//end of findRowWithTwoSeats
public int countSeatsAvail() {//counts how many seats are available on the
//plane, returns int value
int count = 0;//used to keep track of how many seats are available
for (int[] plane1 : seats) {
for (int j = 0; j < plane1.length; j++) {
if (plane1[j] == 0) {
count++;
} //end of if
} //end of nested for
} //end of for
return count;//returns the number of seats available
}//end of countSeatsAvail
public int countTakenSeats() {//counts number of seats taken on the plane,
//returns int value
int count = 0;//used to keep track of how many seats are taken
for (int[] plane1 : seats) {
for (int j = 0; j < plane1.length; j++) {
if (plane1[j] == 1) {
count++;
}
} //end of nested for
} //end of for
return count;//returns number of seats taken
}//end of countTakenSeats
}//end of class plane
</code></pre>
|
[] |
[
{
"body": "<p>You can improve your code in multiple ways:</p>\n<ol>\n<li><p>I believe you are using at least Java 8 version, so consider using <strong>Stream API</strong> for iteration. (please take example from enum static block)</p>\n</li>\n<li><p><strong>Remove duplicate code</strong> or your code. Extract duplicate code in another private method. Like : <code>isSeatAvailable</code> and <code>reserveSeat</code> uses same switch code. And <code>countSeatsAvail</code> and <code>countTakenSeats</code> use almost same logic only one condition is different. (Added updated code below, where I have used Lambda to avoid code duplication)</p>\n</li>\n<li><p><strong>Method names should have consistency</strong> like <code>countSeatsAvail</code> and <code>countTakenSeats</code> should be like <code>countTakenSeats</code> and <code>countAvailSeats</code>. (updated code with change is added, these method are not needed any more)</p>\n</li>\n<li><p><code>Avoid using abbreviations for names</code> like Available to Avail. Until unless it's well-known abbreviation or it makes method too long.</p>\n</li>\n<li><p><code>Avoid unnecessary variable creation</code> like in <code>reserveSeat</code> and <code>isSeatAvailabe</code> assign column to seatSelect and colChar variable. Even the names should have consistency as they indicate same value.</p>\n</li>\n<li><p>You can <strong>avoid these switch cases condition</strong> with enum. (updated code with change is added and you don't need it anymore)</p>\n</li>\n<li><p><strong>Method name should be clear to give the method details</strong> as <code>seatsAvailInRow</code> should be rather <code>adjusentSeatsAvailableInRow</code>.</p>\n</li>\n<li><p>You can <strong>avoid these unwanted comments</strong> on each and every line. (ex endOfIf, endOfFor, endOfMethod etc.)</p>\n</li>\n</ol>\n<hr />\n<pre><code>package test.file;\n\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.function.IntPredicate;\n\npublic class LatestClass {\n\n public static void main(final String[] args) {\n final Plane p = new Plane();\n p.fillSeatsRandomly();\n p.displaySeats();\n if (p.isSeatAvailable(2, 'B')) {\n System.out.println("You have reserved seat: 2,B");\n p.reserveSeat(2, 'B');\n p.displaySeats();\n }\n System.out.println("Sorry, seat: 2,B is already taken");\n System.out.println("There is " + p.seatsAvailInRow(5) + " seat(s) available in row 5");\n System.out.println("Row " + p.findRowWithTwoSeats() + " has 2 adjacent seats");\n System.out.println("Seats available: " + p.countSeats(panel -> panel == 0));\n System.out.println("Seats taken: " + p.countSeats(panel -> panel == 1));\n }\n}\n</code></pre>\n<hr />\n<pre><code>class Plane {\n\n int[][] seats = new int[12][4];\n\n public int countSeats(final IntPredicate condition) {//counts how many seats are available on the\n //plane, returns int value\n int count = 0;//used to keep track of how many seats are available\n for (final int[] plane1 : seats) {\n for (int j = 0; j < plane1.length; j++) {\n if (condition.test(plane1[j])) {\n count++;\n } //end of if\n } //end of nested for\n } //end of for\n return count;//returns the number of seats available\n }\n\n public void displaySeats() {//displays the seats\n System.out.print("\\tA \\tB \\tC \\tD \\n");\n for (int row = 0; row < seats.length; row++) {\n System.out.print(row + 1 + "");\n for (int seatNum = 0; seatNum < seats[row].length; seatNum++) {\n if (seats[row][seatNum] == 1) {\n System.out.print("\\tX ");\n } else {\n System.out.print("\\t0 ");\n }\n } //end of nested for\n System.out.println();\n } //end of for\n }//end of displaySeats\n\n public void fillSeatsRandomly() {//fills seats randomly\n for (final int[] seats1 : seats) {\n for (int col = 0; col < seats1.length; col++) {\n seats1[col] = (int) Math.round(Math.random());\n } //end of nested for\n } //end of for\n }//end of fill seats randomly\n\n public int findRowWithTwoSeats() {//finds the closest row that has\n //2 adjacent seats, returns row num, or 0 if none\n for (int i = 0; i < seats.length; i++) {\n for (int j = 0; j < seats[i].length; j++) {\n if (seats[i][0] + seats[i][1] == 0 || seats[i][1] + seats[i][2] == 0 || seats[i][2] + seats[i][3] == 0) {\n return i + 1;//returns row num with adjacent seats\n } //end of if\n } //end of nested for\n } //end of for\n return 0;//returns 0 if there is no adjacent seats\n }//end of findRowWithTwoSeats\n\n public boolean isSeatAvailable(final int row, final char colChar) { //checks if seat is\n //available, returns true if it is and false if not\n final int rowNum = row - 1;//row number of the seat chosen\n final int colNum = SeatColumn.getColumn(colChar);\n //end of switch\n return seats[rowNum][colNum] == 0;\n }//end of isSeatAvail\n\n public void reserveSeat(final int row, final char seatSelect) {//reserves a seat updates array\n final int rowNum = row - 1;//Row number of seat chosen\n final int colNum = SeatColumn.getColumn(seatSelect);\n seats[rowNum][colNum] = 1;\n } //end of reserveSeat\n\n public int seatsAvailInRow(final int row) {//checks how many seats are available\n //in a row determined returns int value\n final int rowNum = row - 1;\n int rowSum = 0;\n int avail;\n for (final int[] plane1 : seats) {\n rowSum = 0;\n for (int j = 0; j < plane1.length; j++) {\n rowSum += seats[rowNum][j];\n } //end of nested for\n } //end of for\n avail = 4 - rowSum;\n return avail;//returns number of seats available\n }//end of seatsAvailInRow\n}//end of class plane\n</code></pre>\n<hr />\n<pre><code>enum SeatColumn {\n A(0), B(1), C(2), D(3);\n\n private static final Map<Character, Integer> seatColumnMapping = new HashMap<>();\n\n static {\n Arrays.stream(values()).forEach(v -> {\n seatColumnMapping.put(Character.valueOf(v.toString().charAt(0)), Integer.valueOf(v.column));\n });\n }\n\n private int column;\n\n SeatColumn(final int column) {\n this.column = column;\n }\n\n public static int getColumn(final char seat) {\n return seatColumnMapping.get(Character.valueOf(seat)).intValue();\n }\n\n public int getColumn() {\n return column;\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T13:26:58.687",
"Id": "498056",
"Score": "0",
"body": "Nice answer. When you edit a question it is better not to edit the code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T12:39:27.477",
"Id": "252709",
"ParentId": "252701",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "252709",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T09:35:15.427",
"Id": "252701",
"Score": "3",
"Tags": [
"java",
"array"
],
"Title": "Seat Reservation 2D Array Applied to Methods"
}
|
252701
|
<p>I'd like some feedback/suggestions on how to improve the following. Specifically I want to know if what I'm doing is reliable and fast, or if there is a better way to accomplish this.</p>
<p><strong>The problem:</strong></p>
<p>I have some dataset containing counts of sales made at different times throughout the day, across different locations/shops. Let's say there are 4 different shops contained in this data (A, B, C, D), and there are 4 different time bins in the day [0,1,2,3]. I query this and return a query dataset, but the issue I have is that for this query there may be no transactions for a certain time bin. Or there may be no transactions even for a specific shop (maybe there was a rat infestation and it closed for the day).</p>
<p>Nevertheless, the end result must have the same number of rows (4 locations x 4 time bins), and simply contain zeros if there were no transactions there. In other words, I want records for all possible occurrences, even if they were not returned by the query itself.</p>
<p><strong>Example:</strong></p>
<pre><code>import pandas as pd
# Specify the complete list of possible time bins
max_timebins = 3
bin_nums = list(range(max_timebins + 1))
# Specify the complete list of shops
shop_ids = ['A', 'B','C','D']
# Make a dataframe for all possible results without the counts
# This is just a dataframe with an index and no columns... this feels a little strange to me but it worked...
dat = {'shop':[], 'timebin':[]}
for shop in shop_ids:
dat['shop']+=[shop]*len(bin_nums)
dat['timebin'] += bin_nums
df_all = pd.DataFrame(dat)
df_all = df_all.set_index(list(dat.keys()))
# Example of a result of a query
dfq = pd.DataFrame(
{
'shop':['A', 'A', 'A', 'A',
'B', 'B',
'C', 'C', 'C',
'D'],
'time_bins':[0,1,2,3,
0, 3,
0,2,3,
2],
'counts':[100,220, 300, 440,
500, 660,
120, 340, 90,
400]}).set_index(['shop', 'time_bins'])
result_df = pd.concat([df_all, dfq], axis=1).fillna(0).astype(int)
</code></pre>
|
[] |
[
{
"body": "<p>You can create the index directly:</p>\n<pre class=\"lang-py prettyprint-override\"><code>pd.MultiIndex.from_product(\n (shop_ids, range(max_timebins + 1)), names=("shop", "timebin")\n)\n</code></pre>\n<p>Here is how you can achieve the same result (including the full index even if there is no data) in a simpler way:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import pandas as pd\n\n# Specify the complete list of possible time bins\nmax_timebins = 3\n\n# Specify the complete list of shops\nshop_ids = ["A", "B", "C", "D"]\n\ntarget_index = pd.MultiIndex.from_product(\n (shop_ids, range(max_timebins + 1)), names=("shop", "timebin")\n)\n\n# Example of a result of a query\ndfq = pd.DataFrame(\n {\n "shop": ["A", "A", "A", "A", "B", "B", "C", "C", "C", "D"],\n "time_bins": [0, 1, 2, 3, 0, 3, 0, 2, 3, 2],\n "counts": [100, 220, 300, 440, 500, 660, 120, 340, 90, 400],\n }\n).set_index(["shop", "time_bins"])\n\nresult_df = dfq.reindex(target_index, fill_value=pd.NA)\n\nprint(result_df)\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code> counts\nshop timebin \nA 0 100\n 1 220\n 2 300\n 3 440\nB 0 500\n 1 <NA>\n 2 <NA>\n 3 660\nC 0 120\n 1 <NA>\n 2 340\n 3 90\nD 0 <NA>\n 1 <NA>\n 2 400\n 3 <NA>\n</code></pre>\n<p>There might be a better solution, but that would require knowing a bit more context.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T21:55:31.413",
"Id": "252729",
"ParentId": "252704",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T10:12:28.080",
"Id": "252704",
"Score": "1",
"Tags": [
"python",
"pandas"
],
"Title": "Fill a pandas dataframe (of predetermined size) with results from a similar dataframe (of size less than or equivalent to the original)"
}
|
252704
|
<p>I have been trying to improve python combined with Postgres.</p>
<p>At this moment im only sending two values to database which are etc:</p>
<pre><code>link = "https://www.mathem.se/varor/vegetarisk-fars/vegofars-fairtrade-1000g-anamma"
store = "mathem"
</code></pre>
<p>and I do have few options that I want to be able to do with Postgres and that is to fetch all, commit and count.</p>
<p>And here I do have few options such as to check if the link exists already, if its has been deactivated from before, delete the link, get the ID from the product etc etc:</p>
<pre><code>#!/usr/bin/python3
# -*- coding: utf-8 -*-
from datetime import datetime
import psycopg2
DATABASE_CONNECTION = {
"host": "testing.com",
"database": "test",
"user": "test",
"password": "test"
}
def execute_fetch_all(query):
"""
Fetch all queries
:param query:
:return:
"""
try:
connection = psycopg2.connect(**DATABASE_CONNECTION)
cursor = connection.cursor()
cursor.execute(query)
response = cursor.fetchall()
cursor.close()
connection.close()
return response
except (Exception, psycopg2.DatabaseError) as error:
logger.exception(f"Database error: {error}")
return
def execute_commit(query):
"""
Commit database
:param query:
:return:
"""
try:
connection = psycopg2.connect(**DATABASE_CONNECTION)
cursor = connection.cursor()
cursor.execute(query)
connection.commit()
cursor.close()
connection.close()
return True
except (Exception, psycopg2.DatabaseError) as error:
logger.exception(f"Database error: {error}")
return
def execute_count(query):
"""
Count elements in database
:param query:
:return:
"""
try:
connection = psycopg2.connect(**DATABASE_CONNECTION)
cursor = connection.cursor()
cursor.execute(query)
if cursor.rowcount:
cursor.close()
connection.close()
return True
else:
cursor.close()
connection.close()
return False
except (Exception, psycopg2.DatabaseError) as error:
logger.exception(f"Database error: {error}")
return
def check_if_link_exists(store, link):
"""
Check if link exists
:param store:
:param link:
:return:
"""
if execute_count(f"SELECT DISTINCT link FROM public.store_items WHERE store='{store.lower()}' AND link='{link}';"):
return True
else:
return False
def check_if_links_deactivated(store, link):
"""
Check if link is deactivated
:param store:
:param link:
:return:
"""
if execute_count(f"SELECT DISTINCT link FROM public.store_items WHERE store='{store.lower()}' AND link='{link}' AND visible='no';"):
return True
else:
return False
def delete_manual_links(store, link):
"""
Delete given link
:param store:
:param link:
:return:
"""
execute_commit(f"DELETE FROM public.manual_urls WHERE store='{store.lower()}' AND link='{link}';")
return True
def get_product_id(store, link):
"""
Get id from database for specific link
:param store:
:param link:
:return:
"""
product = execute_fetch_all(f"SELECT DISTINCT id, store, link FROM public.store_items WHERE store='{store.lower()}' AND link='{link}' AND visible='yes';")
return {"id": product[0][0], "store": product[0][1], "link": product[0][2]}
def get_all_links(store):
"""
Return all links in database
:param store:
:return:
"""
cur = execute_fetch_all(f"SELECT DISTINCT id, link FROM public.store_items WHERE store='{store.lower()}' AND visible='yes';")
return [{"id": links[0], "link": links[1]} for links in cur]
def check_if_store_exists(store):
"""
Check if the store exists in database
:param store:
:return:
"""
if execute_count(f"SELECT DISTINCT store FROM public.store_config WHERE store='{store.lower()}';"):
return True
else:
return False
def register_store(store):
"""
Register the store
:param store:
:return:
"""
if check_if_store_exists(store=store) is False:
execute_commit(f"INSERT INTO public.store_config (store) VALUES ('{store.lower()}');")
return True
else:
return False
</code></pre>
<p>I wonder if there is a way to maybe even short the code by alot or to also improve when using postgres combined with Python since it is new for me still but I do see potential that I might be able to shorter the code quite alot here</p>
<p>If there is any missing information, please let me know in comments and I will try my best to give the information that I might have forgot to add here</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T13:11:29.237",
"Id": "498049",
"Score": "1",
"body": "What about using an ORM like sqlalchemy?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T13:15:45.600",
"Id": "498052",
"Score": "0",
"body": "Hi @hjpotter92 - Im actually not sure what is that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T13:23:42.727",
"Id": "498055",
"Score": "1",
"body": "https://www.sqlalchemy.org/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T13:28:18.153",
"Id": "498057",
"Score": "0",
"body": "@hjpotter92 - Hmm im not sure what that is, is it like a replacement of postgres?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T14:17:03.377",
"Id": "498063",
"Score": "0",
"body": "@ProtractorNewbie ORM (like SQLAlchemy) is not a replacement, it is an abstraction layer over PostgreSQL or another db server"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T14:23:17.337",
"Id": "498064",
"Score": "0",
"body": "@n1k9 Oh I see, that would also work but it is abit out of my knowledge and I think I would need a small example out of the code I provided to know/understand how it would look for my case if that is possible? :D"
}
] |
[
{
"body": "<h2>Injection</h2>\n<pre><code>f"SELECT DISTINCT link FROM public.store_items WHERE store='{store.lower()}' AND link='{link}';"\n</code></pre>\n<p>is wide open to injection attacks. <code>psycopg2</code> has excellent support for parameters in prepared statements; use that instead of string formatting.</p>\n<h2>Hard-coded credentials</h2>\n<p><code>DATABASE_CONNECTION</code> needs to be externalized to somewhere secure in the operating system environment, for a handful of reasons including protecting the password, and keeping reconfiguration easy. This can take the form of environmental variables or a config file.</p>\n<h2>Context management</h2>\n<p>This block:</p>\n<pre><code> connection = psycopg2.connect(**DATABASE_CONNECTION)\n cursor = connection.cursor()\n cursor.execute(query)\n response = cursor.fetchall()\n cursor.close()\n connection.close()\n</code></pre>\n<p>has a number of issues:</p>\n<ul>\n<li>You're opening and closing a new connection every time you do a fetch. Connections are expensive and should be longer-lived.</li>\n<li>You need to replace explicit <code>close</code> with the use of a context-management <code>with</code> statement.</li>\n<li>Your <code>except</code> effectively swallows all exceptions and returns <code>None</code> if there's a failure. That behaviour should not be baked into <code>execute_fetch_all</code> and should exist outside, at the caller level instead. This is true for <code>execute_count</code> and <code>execute_commit</code> as well.</li>\n</ul>\n<h2>Explicit commit</h2>\n<p><code>execute_commit</code> does not benefit from <code>commit()</code> in its current form. Read this for example - <a href=\"https://stackoverflow.com/questions/51880309/what-does-autocommit-mean-in-postgresql-and-psycopg2\">https://stackoverflow.com/questions/51880309/what-does-autocommit-mean-in-postgresql-and-psycopg2</a> - autocommit is the default.</p>\n<h2>Existence checks</h2>\n<pre><code>SELECT DISTINCT\n</code></pre>\n<p>is not the best way to check for existence. Instead, consider use of the actual PostgreSQL <code>exists</code> clause.</p>\n<h2>Dictionary construction</h2>\n<p>Don't do this:</p>\n<pre><code>[{"id": links[0], "link": links[1]} for links in cur]\n</code></pre>\n<p>yourself.</p>\n<p>Read <a href=\"https://www.psycopg.org/docs/extras.html#dictionary-like-cursor\" rel=\"nofollow noreferrer\">https://www.psycopg.org/docs/extras.html#dictionary-like-cursor</a> for the built-in alternative.</p>\n<h2>Booleans</h2>\n<pre><code>if x is False:\n</code></pre>\n<p>should be</p>\n<pre><code>if not x:\n</code></pre>\n<p>and</p>\n<pre><code>if x:\n return True\nelse:\n return False\n</code></pre>\n<p>should be</p>\n<pre><code>return bool(x)\n</code></pre>\n<p>or, if you're comparing a count, more explicitly:</p>\n<pre><code>return x > 0\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T18:34:45.330",
"Id": "498093",
"Score": "0",
"body": "Hi! I forgot to mention that this script will only be locally PC and will not be uploaded anywhere in the web! So only me will be able to do anything with this script! :) - About the database connection, I was not sure what would be the best option, etc, if I run etc 100 scripts where each script has a import of database.py, Wouldn't that mean that all of them would be connected to the database at the same time and hit the maximium connection? Thats the reason I have a close() at this moment but might be wrong too!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T18:35:40.980",
"Id": "498094",
"Score": "1",
"body": "_this script will only be locally PC_ - For learning purposes, you should still strive for production-quality code. Get into good habits sooner rather than later."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T18:36:58.600",
"Id": "498095",
"Score": "1",
"body": "_all of them would be connected to the database at the same time and hit the maximium connection_ - Sure; but that would still potentially happen even if you close your connection more often. It's still possible for there to be 100 concurrent calls to your fetch routine. The solution is not to close the connection more often; it's to centralize connection management into a smaller number of processes with connection pools."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T18:42:36.370",
"Id": "498096",
"Score": "0",
"body": "That is true. However im not sure how to solve that issue in that case where I can have a connection pool. What should it actually happend if you etc have 150 scripts where all of them are connected to the db, My idea and reason I did is that I just wanted to connect -> to my add/update/delete to the db -> close it. To never reach the connection issue. But I assume as you mentioned this is not the correct way and im not sure what else I can do from here code-wise :("
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T18:50:24.287",
"Id": "498098",
"Score": "0",
"body": "If you're running 150 scripts that all connect to the database at once, you have bigger problems."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T18:50:42.300",
"Id": "498099",
"Score": "0",
"body": "If you actually need something like this, you need to revisit your architecture."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T18:55:16.157",
"Id": "498101",
"Score": "0",
"body": "Hmm im pretty sure you are right, however I do not use the database constantly aswell for all scripts but I do agree what you mean. Im sure the problem I might have would belongs to stackoverflow. In the meanwhile I tried to find any information about \"prepared statements\" but did not find any good examples besides some stackoverflow questions."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T18:28:53.340",
"Id": "252722",
"ParentId": "252710",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "252722",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T13:06:53.330",
"Id": "252710",
"Score": "2",
"Tags": [
"python",
"sql",
"postgresql"
],
"Title": "Managing a store in PostgreSQL"
}
|
252710
|
<p>I recently came across a coding challenge on some sort of technological basket weaving forum, where you had to pick 2 cards from a shuffled deck. I believe the challenge can be interpreted 2 ways:</p>
<ol>
<li>Generate random deck, pick first 2</li>
<li>Generate sequential (or any) deck, pick 2 random cards</li>
</ol>
<p>I went for option one. I believe I have used a good shuffling algorithm and accounted for modulo bias.</p>
<p>My main priorities:</p>
<ol>
<li>correctness</li>
<li>code easy to handle and read</li>
</ol>
<h1>cards.c</h1>
<pre><code>#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define SWAP_INT(a,b) {int tmp=a; a=b; b=tmp;}
const char const* suits[4] = {"Diamonds","Clubs","Hearts","Spades"};
const char const* ranks[13] = {"Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"};
// from min inclusive to max inclusive
int rand_ranged_inclusive(int min, int max)
{
if (min > max)
SWAP_INT(min, max);
if (min == max)
return min;
int range = max-min+1;
int biased_interval = RAND_MAX%(range-1);
int x;
// prevent modulo bias by choosing a number outside biased interval
do {
x = rand();
} while (x < biased_interval);
return x%range + min;
}
// Fisher-Yates (Durstenfield)
int shuffle(int arr[], int len)
{
for (int i = 0; i < len; ++i) {
int j = rand_ranged_inclusive(i, len-1);
SWAP_INT(arr[i], arr[j]);
}
}
void print_card(int c)
{
if (c < 0 || c > 52)
printf("Joker\n");
const char const* suit = suits[c/13];
const char const* rank = ranks[c%13];
printf("%s of %s\n", rank, suit);
}
int main(int argc, char const *argv[])
{
srand(time(NULL));
int cards[52] = {0};
for (int i = 0; i < 52; ++i)
cards[i] = i;
shuffle(cards, 52);
print_card(cards[0]);
print_card(cards[1]);
return 0;
}
</code></pre>
<p>I feel like it can be optimized some more, especially picking random numbers, but reading from <code>dev/urandom</code> seems overall slower, when the modulo bias is so small and easily overcome.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T15:54:53.367",
"Id": "498072",
"Score": "0",
"body": "I just noticed that I can do an XOR-swap instead of a temp variable. This would also allow the `SWAP_INT` macro to remain untyped. `#define SWAP(a,b) {a^=b; b^=a; a^=b;}`. Branchless check to see if not equal: `#define SWAP(a,b) {a^=(b*(a!=b)); b^=(a*(a!=b)); a^=(b*(a!=b));}`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T17:45:08.850",
"Id": "498088",
"Score": "0",
"body": "Oops, just noticed shuffle supposedly returns an int. It doesn't. Should be `void shuffle()`"
}
] |
[
{
"body": "<h2>Premature optimization</h2>\n<blockquote>\n<p>I just noticed that I can do an XOR-swap instead of a temp variable. This would also allow the SWAP_INT macro to remain untyped</p>\n</blockquote>\n<p>That's unfortunately incorrect - xor-swapping in fact has a reliance on type. Aside from your declared <code>int</code> type, the "naive" implementation of your swap would work with (for example) struct instances where xor cannot.</p>\n<p>Unless you're on a microcontroller that has a poor compiler and every nanosecond is precious, do not bother writing out a xor-swap yourself. An optimizing compiler will either do this, or better (with an actual swap instruction where applicable) for you. Your existing swap macro is fine, and if you want this to be type-parametric, you can always accept the variable type as another macro parameter.</p>\n<h2>Parameter validation</h2>\n<pre><code>if (min > max)\n SWAP_INT(min, max);\n</code></pre>\n<p>seems risky to me. If the application gets into a state where the min is greater than the max, I would consider this fairly surprising and erroneous behaviour, and would want to call that out as an error instead of silently fixing it.</p>\n<p>Given that C of course does not have exception handling, your options to do this are somewhat constrained - you can have an output parameter separate from your return value, where the former receives the random result and the latter indicates success or failure. An <code>assert</code> would also be appropriate.</p>\n<p>Likewise,</p>\n<pre><code>if (c < 0 || c > 52)\n printf("Joker\\n");\n</code></pre>\n<p>seems too permissive. You should choose one well-defined value for a joker, and consider all others out-of-range to be erroneous.</p>\n<h2>Random sources</h2>\n<p>Cryptographic-quality randomness is not important for this application, so I consider the <code>/dev</code> approach to be overkill. Something like the Mersenne Twister would work well because it has better numerical characteristics while remaining extremely fast.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T16:40:52.807",
"Id": "498083",
"Score": "0",
"body": "Interesting. I thought the xor operator would just take whatever size data and xor the literal bits. Not so, then? Also, thank you for suggesting the Mersenne Twister."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T17:14:57.650",
"Id": "498086",
"Score": "2",
"body": "No, for example `3.14 ^ 2.72` simply doesn't compile. Also, just as a practical matter, on hardware XOR-swap is going to be much slower than your naïve swap, because the former involves ALU operations whereas the latter is a simple register-rename that introduces no dependencies. Remember that the world is optimized for \"ordinary\" code; the more \"extraordinary\" your code looks, the less you'll benefit from the optimizations everyone else is getting."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T16:07:40.907",
"Id": "252715",
"ParentId": "252712",
"Score": "6"
}
},
{
"body": "<p><code>rand_ranged_inclusive(a, b)</code> is a surprisingly long function name, for how little information it communicates to the reader. I have frequently seen versions of this function named <code>randint(a, b)</code> or <code>randint0(b)</code> — but where the possible outputs are between <code>0</code> inclusive and <code>b</code> <em>exclusive!</em></p>\n<p>Using "half-open ranges" like this has huge advantages in C, because C uses half-open ranges for everything else. To pick a random element from an array, you want <code>randint0(NELEM(a))</code>. To pick a random character from a string, you want <code>randint0(strlen(s))</code>. And so on.</p>\n<pre><code>if (min > max)\n SWAP_INT(min, max);\n</code></pre>\n<p>Here and throughout, I strongly recommend curly-bracing all your control flow, including <code>if</code> and <code>for</code> bodies which are <em>currently</em> only one line long. These braces may one day save you from a <a href=\"https://nakedsecurity.sophos.com/2014/02/24/anatomy-of-a-goto-fail-apples-ssl-bug-explained-plus-an-unofficial-patch/\" rel=\"noreferrer\"><code>goto fail</code> bug</a>.</p>\n<p>Also, I think it's un-idiomatic that you are going out of your way to produce well-defined behavior for <code>rand_ranged_inclusive(6, 1)</code>. I claim that that kind of input clearly indicates a bug in the caller, and you should be using <code>assert(min <= max)</code> here. (Or, if you switch to half-open ranges, <code>assert(min < max)</code>.)</p>\n<p>Your choice to handle <code>rand_ranged_inclusive(6, 1)</code> becomes even weirder when you consider that you do <em>not</em> handle seemingly valid parameters such as <code>rand_ranged_inclusive(-10, INT_MAX)</code>. (The caller who tries that gets integer overflow and undefined behavior.)</p>\n<pre><code>int range = max-min+1;\nint biased_interval = RAND_MAX%(range-1);\n</code></pre>\n<p>The use of <code>RAND_MAX % ...</code> instead of <code>(RAND_MAX+1) % ...</code> is an immediate red flag for me, after our discussion of half-open ranges. (<code>RAND_MAX</code> is an endpoint-which-is-included, similar to <code>INT_MAX</code>.) All these <code>+1</code> and <code>-1</code> would go away if you switched to half-open ranges. I bet they're hiding some off-by-one errors. Let's trace through a sample input.</p>\n<p>Suppose <code>min</code>=1, <code>max</code>=6, <code>RAND_MAX</code>=10. (This is <em>legitimately</em> the first input I traced.) Then <code>range</code>=6, <code>biased_interval</code>=0... so the <code>do-while</code> loop runs only once before dropping out... but you end up choosing 1-4 twice as often as 5-6.</p>\n<p>Did you test this code at all? How did you test it?</p>\n<p>I think the algorithm you want here is more like</p>\n<pre><code>int range = max - min + 1;\nint discard_top_k = ((RAND_MAX % range) + 1) % range;\nint real_max = RAND_MAX - discard_top_k;\ndo {\n x = rand();\n} while (x > real_max);\n</code></pre>\n<hr />\n<pre><code>int j = rand_ranged_inclusive(i, len-1);\n</code></pre>\n<p>Your Fisher-Yates shuffle looks correct; but notice again that you're having to add a <code>-1</code> to fix up the lack of half-open ranges in your random-number code.</p>\n<hr />\n<pre><code>if (c < 0 || c > 52)\n printf("Joker\\n");\n</code></pre>\n<p>Is this situation possible? If it's supposed to be impossible, you should <code>assert(0 <= c && c < 52)</code> (hey look! half-open ranges!)</p>\n<p>Also notice the off-by-one error in your code because of (say it with me) the lack of half-open ranges.</p>\n<hr />\n<pre><code>char const *argv[]\n</code></pre>\n<p><a href=\"https://quuxplusone.github.io/blog/2020/03/12/contra-array-parameters/\" rel=\"noreferrer\">I agree with Linus on this one.</a> Prefer</p>\n<pre><code>const char **argv\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T16:24:59.787",
"Id": "498080",
"Score": "0",
"body": "I tested the interval by running (10, 20) a couple million times which produces 15 avg. And you are right, without the +1 -1 it produced slightly under or above 15, can't remember. ### My logic was that any remainder of the division would cause the bias, so choose larger than the remainder. ### The reason I went with both-inclusive, as well as such a verbose name is because such details always leave me wondering (is this random function inclusive? tail inclusive?). Thanks for clearing that up for me. ### I also like your `assert` suggestions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T03:08:26.367",
"Id": "498266",
"Score": "0",
"body": "Link to `char const *argv[]` is about a function lacking a size parameter and in that case, `helper(char *mcs_mask)` is a good idea. Here, `main()` has a leading `argc`. C spec uses the idiomatic `int main(int argc, char *argv[])`, so until the spec changes its style, `main()` coded as `[]` remains the clearer choice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T17:09:16.467",
"Id": "498305",
"Score": "0",
"body": "@chux-ReinstateMonica: Strong disagree, for the reasons stated in Linus's rant. The function takes a parameter of type \"pointer to pointer to char,\" which is idiomatically spelled `char **argv`. You physically _can_ spell it `char *argv[]`, or even `char *argv[argc]` or `char *argv[47]` — they're all _physically_ synonymous in this specific position, because the language spec has special cases to make them synonymous — but logically you _should_ spell it `char **argv` so that the spelling matches the actual pointer-to-pointer type. Reserve the `[]` declaration syntax for array declarations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T20:38:40.993",
"Id": "498329",
"Score": "0",
"body": "@Quuxplusone The proposed new C principle for C2x [15. Application Programming Interfaces (APIs) should be self-documenting when possible](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2086.htm) promotes VLA notation. As with such style issues, best to follow your group's style guide vs. personal preference."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T16:07:56.463",
"Id": "252716",
"ParentId": "252712",
"Score": "9"
}
},
{
"body": "<p><strong>Limited range</strong></p>\n<p>For this application, shuffling 52 cards, <code>rand_ranged_inclusive()</code> limitations are not an issue, yet should be noted.</p>\n<p><code>rand_ranged_inclusive()</code> has trouble when:</p>\n<ol>\n<li><p><code>max-min+1</code> overflows (UB)</p>\n</li>\n<li><p><code>RAND_MAX < range - 1</code>. (Note even some 32/64 bit systems have <code>RAND_MAX = 32767</code>)</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T13:35:39.517",
"Id": "498295",
"Score": "0",
"body": "This is a good note, I overlooked that."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T03:38:06.790",
"Id": "252806",
"ParentId": "252712",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "252716",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T13:45:10.803",
"Id": "252712",
"Score": "7",
"Tags": [
"c"
],
"Title": "Shuffle a deck of cards and draw 2"
}
|
252712
|
<p>I studied segment tree recently and I made this code of segment tree and its queries. Is my code correct in terms of time complexity?</p>
<pre><code>class segmentTree{
private:
vector<int> mini;
vector<int> tree;
vector<int> maxi;
int n;
</code></pre>
<p>Here in the constructor I passed the dynamic array.</p>
<pre><code>public:
segmentTree(vector<int> a)
{
mini=a;
tree=a;
maxi=a;
n=tree.size();
}
</code></pre>
<p>makeTree function builds three segment trees for different queries like sum, maximum and minimum.</p>
<pre><code> void makeTree()
{
reverse(tree.begin(),tree.end());
reverse(mini.begin(),mini.end());
reverse(maxi.begin(),maxi.end());
for(int i=0;i<tree.size();i+=2)
{
tree.pb(tree[i]+tree[i+1]);
mini.pb(min(mini[i],mini[i+1]));
maxi.pb(max(maxi[i],maxi[i+1]));
}
tree.PB();
mini.PB();
maxi.PB();
reverse(tree.begin(),tree.end());
reverse(mini.begin(),mini.end());
reverse(maxi.begin(),maxi.end());
}
</code></pre>
<p>The sum function calculates the sum of given range.</p>
<pre><code> int sum(int a,int b)
{
a+=(n);
b+=(n);
int sum=0;
while(a<=b)
{
if(a%2==1)
{
sum+=tree[a-1];
a++;
}
if(b%2==0)
{
sum+=tree[b-1];
b--;
}
a/=2;
b/=2;
}
return sum;
}
</code></pre>
<p>The minimum function finds the minimum value of given range.</p>
<pre><code> int minimum(int a,int b)
{
a+=(n);
b+=(n);
int minu;
while(a<=b)
{
if(a%2==1)
{
minu=mini[a-1];
a++;
}
if(b%2==0)
{
minu=mini[b-1];
b--;
}
a/=2;b/=2;
}
return minu;
}
</code></pre>
<p>The maximum function finds the maximum value of given range.</p>
<pre><code>int maximum(int a,int b)
{
a+=(n);
b+=(n);
int maxu;
while(a<=b)
{
if(a%2==1)
{
maxu=maxi[a-1];
a++;
}
if(b%2==0)
{
maxu=maxi[b-1];
b--;
}
a/=2;b/=2;
}
return maxu;
}
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T15:15:45.997",
"Id": "498065",
"Score": "1",
"body": "Welcome to the Code Review Community. It is very difficult to see where the class ends and the code doesn't look complete. Can you please post the code as it is in your IDE or editor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T15:21:21.960",
"Id": "498068",
"Score": "3",
"body": "_correct in terms of time complexity_? Are you asking whether this has a _low_ time complexity? What do you think it is now?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T16:36:14.067",
"Id": "498082",
"Score": "2",
"body": "Are `vector` and `reverse` from the standard library, or written by yourself? `std::vector` does not have a member function named `pb()` or `PB()`, so if it is a custom class you should include it as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T09:29:17.060",
"Id": "498144",
"Score": "0",
"body": "pb() is for push_back() and PB() is pop_back(). I defined them as a macros."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T17:33:05.020",
"Id": "498306",
"Score": "0",
"body": "\"I defined them as a macros\" — Well, don't do that. I recommend updating your question now while you can, before you get any answers. Also, the presentation of your question would be improved by a link to the Wikipedia article on [segment trees](https://en.wikipedia.org/wiki/Segment_tree)."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T15:08:25.697",
"Id": "252714",
"Score": "1",
"Tags": [
"c++"
],
"Title": "Segment tree and queries"
}
|
252714
|
<p>for a thesis I am creating a program that constructs curling sequences.
The curling number of a sequence is defined as 'the largest frequency of any period at the end of the sequence'. (For example, 11232323 has curling number 3, because 23 is repeated three times)</p>
<p>Currently, I am mostly interested in the appearance of a 1 as curling number, when the sequence is generated with any possible combination of 2's and 3's (for example, we generate 2322322 and want to find the first occurence of '1' as curling number).</p>
<p>I changed to multi-threading recently, but my performance lacks for what I need.</p>
<p>Does anyone have any suggestions on how to improve the speed of this multi-threaded program? I hope I provided enough comments to make it clear, but any questions will be answered.</p>
<pre><code>#include <vector>
#include <iostream>
#include <chrono>
#include <thread>
#include <mutex>
#include <cmath>
#pragma warning (disable : 26451)
using namespace std::chrono;
const int range = 200; // used to reserve size for each sequence
std::mutex m_tail; // thread-lock for the tail
int tail = 0; // value to keep track of the longest tail encountered
int length = 0; // user input to define length of generator
thread_local std::vector<short int> sequence(range); // sequence for each individual thread
thread_local long double duur = 0; // value for each individual thread to time functions
// this function finds the curling number (curl) of a sequence
// the curl of a sequence is defined as: the highest frequency of a period at the end of a sequence
// some examples:
// the curl of 11232323 is 3, because 23 is the most-repeated element at the end of the sequence
// the curl of 2222 is 4, because 2 is the most-repeated element at the end of the sequence
// the curl of 1234 is 1, because every period at the end of the sequence is repeated only once
int krul(short int j, short int last_curl) {
short int curl = 1; // the minimum curl of a sequence is 1
for (short int length = 1; length <= int(j / (curl + 1) + 1); ++length) {
short int freq = 1; // the minimum frequency of any period is 1
while ((freq + 1) * length <= j and std::equal(sequence.begin() + j - (freq + 1) * length, sequence.begin() + j - freq * length, sequence.begin() + j - length)) {
// while within length of the sequence, and while periods match, continue
++freq; // if they match, the frequency is increased with 1
if (freq > curl) { // if the frequency of this period is higher than the curl yet
curl = freq; // update the value for curl
if (curl > last_curl) { // mathematical break: the curl can't be 'last_curl + 2', so when we encounter 'last_curl + 1' we can stop
return curl;
}
}
}
}
return curl;
}
// this function constructs a whole sequence by adding the curling number and then recalculating the curling number since the sequence got a new element
// and then adds the new curling number and recalculates and so on and so on
int constructor(std::vector<short int> sequence_generator) {
sequence = (std::move(sequence_generator)); // we move the sequence from the generator to the main sequence
short int j = length;
short int last_curl = length;
for (j; j <= range; ++j) { // the sequence is built from starting length to given range
krul(j, last_curl);
short int curl = krul(j, last_curl); // the resulting curling number is the highest of all the candidate curling numbers.
if (curl == 1) { return j; } // for this program, we want to stop if the curling number == 1 and return the length of the sequence (j)
sequence[j] = curl;
if (curl >= 4) { return j + 1; } // if the curling number >= 4, the next curling number is 1 so we can already break and return the length of the sequence (j + 1)
last_curl = curl; // we update the value of last_curl for the next calculation
}
return 0; // we don't encounter this because each sequence breaks, but just in case we return 0
}
// this function takes a number and generates its binary twin, but then existing of 2's and 3's
// because we want every possible generator existing of any combination of 2's and 3's
// and after construction of the generator we call the constructor of the sequence
int decToBinary(unsigned long long n) {
std::vector<short int> sequence_generator(range);
for (long int i = length - 1; i >= 0; i--) {
long int k = n >> i;
if (k & 1) {
sequence_generator[length - 1 - i] = 3;
}
else {
sequence_generator[length - 1 - i] = 2;
}
}
return (constructor(sequence_generator) - length); // the 'tail' of the sequence is the total length ('j' of constructor) minus the length of the generator
}
// this function starts a thread and calls the decToBinary function for a range of sequences
void multi_threader(int thread_number, int thread_count) {
std::cout << "thread " << thread_number << " initiated!" << std::endl;
auto start_time = high_resolution_clock::now(); // timer to keep track of elapsed time of thread
int thread_tail = 0; // value to keep track of maximum tail length of this thread
unsigned long long start = (thread_number - 1) * pow(2, length) / (thread_count); // start value for this thread
unsigned long long stop = pow(2, length) / (thread_count)*thread_number; // end value for this thread
for (unsigned long long int i = start; i < stop; ++i) {
auto start2 = high_resolution_clock::now(); // partial timer start
int local_tail = decToBinary(i); // tail of this sequence
if (local_tail > thread_tail) { // if larger than any earlier tail in this sequence...
thread_tail = local_tail; // update its value
}
auto stop2 = high_resolution_clock::now(); // partial timer end
duur = duur + duration_cast<microseconds>(stop2 - start2).count(); // print elapsed partial time
}
{
std::lock_guard<std::mutex> l(m_tail); // lock 'tail' while editing
if (thread_tail > tail) { // if largest tail in this thread is larger than any thread before...
tail = thread_tail; // update the value
}
}
std::cout << duur / 1000 << std::endl;
auto stop_time = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop_time - start_time).count() / 1000;
std::cout << "thread " << thread_number << " exited, duration: " << duration << " ms, result " << thread_tail << std::endl;
}
// this function calls for as many threads as the user requests and passes the length the user requested on to the thread
void iterate_generator() {
std::vector<std::thread> thread_vector;
int thread_count, thread_number;
thread_number = 0;
std::cout << "enter the length for the sequence generator (e.g. 10, maximum 40)" << std::endl;
std::cin >> length;
length = 25; // example value
std::cout << "enter the desired number of threads (e.g. 2, maximum 4)" << std::endl;
std::cin >> thread_count;
thread_count = 4; //example value
// start the threads and join them
for (int i = 0; i < thread_count; ++i) {
++thread_number;
std::thread th = std::thread([thread_number, thread_count]() {multi_threader(thread_number, thread_count); });
thread_vector.push_back(std::move(th));
}
for (auto& th : thread_vector) { th.join(); }
}
int main() {
while (true) {
iterate_generator();
std::cout << tail << std::endl << std::endl;
}
}
</code></pre>
<p>Thanks in advance!!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T17:57:47.477",
"Id": "498090",
"Score": "1",
"body": "Great first question! The Code Review required format is somewhat unforgiving, but you met it on the first try."
}
] |
[
{
"body": "<p>Here are my suggestions:</p>\n<ul>\n<li><p>Don't use "cin >>". Use "getline(cin,str)" and write a parsing function. I typed "q", intending to quit the program, and it repeatedly started and joined threads and crashed with a "Resource temporarily unavailable" error.</p>\n</li>\n<li><p>Don't cap the number of threads at 4. My main box has 12 threads (6 cores, 2 per core), and I'm thinking of getting one with 144 threads (2 processors, 18 cores each, 4 per core). Use thread::hardware_concurrency() as a default, and make it configurable.</p>\n</li>\n<li><p>I ran it with 1 and 4 threads on length 15 (after commenting out the example values) and got 177 ms vs. (41,43,43,45) ms. This is not bad. The time with one thread should be close to the sum of the times with many threads (which is 172 ms), and it is.</p>\n</li>\n<li><p>As far as the locking goes, it is good. You have one mutex, and it protects a short piece of code.</p>\n</li>\n<li><p>I ran the program with length 23 and 4 threads and stopped it with the debugger. All worker threads were in the krul function at line 29. If there were a problem with multithreading, some threads would have been asleep or waiting for a lock. I suggest therefore that you try to improve the algorithm.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T09:40:41.793",
"Id": "498145",
"Score": "0",
"body": "Thank you for taking the time to look at the program! As of yet, I didn't do any error handling, so cin can indeed easily crash the program. I will fix this. Next, the cap at 4 isn't functioning, that's some old text, sorry. I will probably implement hardware_concurrency, though! I do have a question: do you know a better way to use the thread_local sequence? Because when I switched from global to thread_local (because otherwise they mix results), I quadrupled the times... Oh.. and if you do get a 144-core box.. do you mind to run a calculation? ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T10:57:12.550",
"Id": "498154",
"Score": "0",
"body": "I don't know much about thread_local. I use a runnable object (one with an operator() method) with local variables.\nUnless someone dumps a huge amount of money in my lap, it'll be months before I buy the box. It'll be a POWER box, so not directly comparable to the AMD box I'm on now.\nWhat compiler and OS are you using? This may affect performance; I've seen readers-writer locks behave differently on Linux and Windows. I develop on Linux, usually compiling with clang."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T15:39:06.013",
"Id": "498173",
"Score": "0",
"body": "I'm using VS on Windows. I timed the mutex lock function and it is totally neglectable!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T09:25:02.520",
"Id": "252742",
"ParentId": "252718",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "252742",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T16:57:57.643",
"Id": "252718",
"Score": "4",
"Tags": [
"c++",
"performance",
"multithreading",
"vectors"
],
"Title": "C++ multi-threaded determination of curling numbers in vectors"
}
|
252718
|
<p>I'd like, from a <code>DataFrame</code>, to retrieve a <code>Series</code> which contains the index of the minimal value per row (so <code>axis=1</code>). From the documentation it seems <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.idxmin.html" rel="nofollow noreferrer"><code>idxmin</code></a> may be useful</p>
<p>Let' take</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({
'col1': [0, 10, 2, 30, 4],
'col2': [2, 3, 4, 5, 6],
'col3': [9, 7, 5, 3, 1],
})
</code></pre>
<ol>
<li><p>I've managed to get column names of minimal value</p>
<pre><code>> df.idxmin(axis=1)
0 col1
1 col2
2 col1
3 col3
4 col3
dtype: object
</code></pre>
</li>
<li><p>I've managed to get the index of column of minimal vlaue</p>
<pre><code>df.apply(np.argmin, axis=1)
0 0
1 1
2 0
3 2
4 2
dtype: int64
</code></pre>
</li>
</ol>
<p>Is there any better way to obtain the <code>2.</code> result using maybe a full-pandas code ?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T21:49:27.717",
"Id": "498116",
"Score": "1",
"body": "What is this for? Some context would help find the most appropriate solution."
}
] |
[
{
"body": "<p><code>df.apply</code> over axis 1 is generally avoid for performance issues. <a href=\"https://stackoverflow.com/questions/54432583/when-should-i-not-want-to-use-pandas-apply-in-my-code\"><em>When should I (not) want to use pandas <code>.apply()</code> in my code</em></a></p>\n<h3>1. <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.get_indexer.html\" rel=\"nofollow noreferrer\"><code>pd.Index.get_indexer</code></a></h3>\n<pre><code>cols = df.idxmin(axis=1)\nidx = df.columns.get_indexer(cols) # return a numpy array\nidx_series = pd.Series(idx, index=df.index)\n# Here, index=df.index is important when your DataFrame has custom index values\n\nprint(idx_series)\n0 0\n1 1\n2 0\n3 2\n4 2\ndtype: int64\n</code></pre>\n<h3>2. <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_numpy.html#pandas.DataFrame.to_numpy\" rel=\"nofollow noreferrer\"><code>df.to_numpy</code></a> and <a href=\"https://numpy.org/doc/stable/reference/generated/numpy.ndarray.argmin.html#:%7E:text=Return%20indices%20of%20the%20minimum%20values%20along%20the%20given%20axis%20of%20a.\" rel=\"nofollow noreferrer\"><code>np.ndarray.argmin</code></a></h3>\n<pre><code>idx = df.to_numpy().argmin(axis=1) # returns numpy array\nidx_series = pd.Series(idx, index=df.index)\nprint(idx_series)\n\n0 0\n1 1\n2 0\n3 2\n4 2\ndtype: int64\n</code></pre>\n<hr />\n<p>Some <code>timeit</code> benchs</p>\n<pre><code>from datetime import timedelta\nfrom timeit import timeit\n\nif __name__ == '__main__':\n\n setup = """\nimport pandas as pd\nimport numpy as np\nfrom random import randrange\ntotal = 10000\ndf = pd.DataFrame({\n 'col1': [randrange(10000) for i in range(total)],\n 'col2': [randrange(10000) for i in range(total)],\n 'col3': [randrange(10000) for i in range(total)],\n 'col4': [randrange(10000) for i in range(total)],\n 'col5': [randrange(10000) for i in range(total)],\n 'col6': [randrange(10000) for i in range(total)],\n 'col7': [randrange(10000) for i in range(total)],\n })\n """\n\n for stmt in ["pd.Series(df.to_numpy().argmin(axis=1), index=df.index)",\n "pd.Series(df.columns.get_indexer(df.idxmin(axis=1)), index=df.index)",\n "df.apply(np.argmin, axis=1)"]:\n t = timeit(stmt=stmt, setup=setup, number=20)\n print(f"{str(timedelta(seconds=t)):20s}{stmt}")\n\n\n# Results\n0:00:00.012226 pd.Series(df.to_numpy().argmin(axis=1), index=df.index)\n0:00:00.408151 pd.Series(df.columns.get_indexer(df.idxmin(axis=1)), index=df.index)\n0:00:23.908125 df.apply(np.argmin, axis=1)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-28T10:14:41.733",
"Id": "498216",
"Score": "0",
"body": "Would you like to add some `timeit` examples in your code ? I've made them, you code is amazingly faster"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-28T12:45:43.230",
"Id": "498226",
"Score": "0",
"body": "@azro `df.apply` over axis 1 is not vectorized it's slow and in general it should be used as last resort. Thank you the timeits ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-28T13:40:23.790",
"Id": "498227",
"Score": "0",
"body": "I noticed that I don't need the `pd.Series` cast, I can dircetly do `df['newCol'] = df.to_numpy().argmin(axis=1)` , which is about 5% faster than the same with Series cast :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T05:04:54.847",
"Id": "252738",
"ParentId": "252721",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "252738",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T18:08:31.670",
"Id": "252721",
"Score": "1",
"Tags": [
"python",
"pandas"
],
"Title": "How to get the indexes of smallest value per row in a DF, as column index and not column name?"
}
|
252721
|
<p>I am new to Python but I aspire to become a 'proper' Python coder, (maybe even one day help the noobs on CodeReview :)</p>
<p>Therefore I want to get into good habits early, and would really appreciate some feedback on my first mini-project.</p>
<p><strong>Notes</strong></p>
<ol>
<li>The code deals cards for a simple board game. If you are interested, this is explained in more detail below under 'Rules'. Full game rules <a href="https://cdn.1j1ju.com/medias/2c/50/2b-flamme-rouge-rulebook.pdf" rel="nofollow noreferrer">here</a>.</li>
<li>There are no bugs or problems I can detect.</li>
<li>I have made extensive use of tkinter as a means-to-an-end, however I am less interested in tkinter-specific feedback, but rather <em>the fundamentals of Python itself</em>: classes/objects, decorators, scope, code design/efficiency/elegance. Please point out any barn-door design mistakes, stylistic shortfalls, areas for improvement.</li>
<li>I know i need to change some function names in line with PEP.</li>
</ol>
<hr />
<p><strong>Rules</strong> (What the Code Does)</p>
<ul>
<li>The user selects their team type and team colour from 'launch window'.</li>
<li>A 'game window' then appears, showing two decks of shuffled cards, 'R' and 'S', 15 per deck.</li>
<li>User can click either deck to draw a hand of 4 cards.</li>
<li>User can click on any of the 4 cards to 'play' the card, whereafter the card is discarded from the game, and the 3 remaining cards are set aside in a hidden 'recycle' deck (one for R, one for S).</li>
<li>When fewer than 4 cards remain in either of the <em>main</em> 'R' or 'S' decks, the R or S hidden recycled deck is shuffled and its cards are re-added to the bottom of the respective 'R' or 'S' main deck, and can be drawn on demand, as before.</li>
<li>Sometimes, a user is compelled to collect an 'exhaustion' card for R or for S, which is placed directly into the respective hidden recycle deck.</li>
<li>If the user can not draw 4 cards even after replenishing the R or S deck with its respective hidden recycle deck, the shortfall is made up by taking further 'exhaustion' cards as required.</li>
<li>There is no mixing between R and S decks.</li>
<li>Local image files of the cards are used as the 'buttons', so they can click on the card they want to choose it.</li>
</ul>
<p>That's it! Simple stuff. The <a href="https://cdn.1j1ju.com/medias/2c/50/2b-flamme-rouge-rulebook.pdf" rel="nofollow noreferrer">game</a> itself is not coded here. The reason for the lengthy code is mainly due to the graphical elements.</p>
<hr />
<p><strong>The Code</strong></p>
<p>Am I using @property appropriately/excessively/unneccessarily below?</p>
<pre class="lang-py prettyprint-override"><code>################
# GameLogic.py #
################
import random
# Global constants
# (The lists represent the decks, the elements are the numbers shown on each card.
ROULEUR = [3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7]
SPRINTER =[2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 9, 9, 9]
class Deck:
def __init__(self, team: str, rider: str, teamtype: str):
self._team = team
self._rider = rider
self._cards = []
self._teamtype = teamtype
@property
def show(self):
i = 0
total = self.count_cards
for crd in self.cards:
i += 1
print(f'Value of card {i} of {total} in {self.team} {self.rider} deck is {crd.value}')
if not isinstance(self,MainDeck):
print('This is not the main deck')
# Getters
@property
def team(self):
return self._team
@property
def rider(self):
return self._rider
@property
def cards(self):
return self._cards # Returns list of Card objects
@property
def teamtype(self):
return self._teamtype
# Functions
def get_card(self, index: int):
return self.cards[index]
@property
def count_cards(self):
return len(self.cards)
def pick_cards(self, num: int):
return self.cards[0:num]
@property
def shuffle(self):
for i in range(self.count_cards -1, -1, -1):
rnd = random.randint(0, i)
self.cards[i], self.cards[rnd] = self.cards[rnd], self.cards[i]
def add(self, newCard: object):
self.cards.append(newCard)
def remove_card(self, index: int):
return self.cards.pop(index)
@property
def countExhaustion(self) -> int:
cnt = 0
for crd in self.cards:
if isinstance(crd, ExhaustCard):
cnt += 1
return cnt
def getFilePaths(self) -> str:
filepaths = []
for card in self.cards:
if isinstance(card,ExhaustCard):
filepaths.append(f'Images/exhaust_{self.rider[0:1].upper()}_{str(card.value)}.jpg')
else:
filepaths.append(f'Images/{self.team.lower()}_{self.rider[0:1].upper()}_{str(card.value)}.jpg')
return filepaths
# For a given card[index = i], return a tuple with all the remaining original indices of the other cards in that deck. Used for recycling hands of variable size. Reverse order for ease of processing later.
def getRemainders(self, i: int) -> int:
indices = list(range(self.count_cards))
del indices[i]
return indices[::-1]
class MainDeck(Deck):
def __init__(self, team: str, rider: str, teamtype: str):
self._team = team
self._rider = rider
self._cards = []
self._teamtype = teamtype
self._recycleDeck = Deck(team,rider,teamtype)
if self.teamtype.lower() == 'player':
if rider[0:1].upper() == 'R':
for i in range(len(ROULEUR)):
self._cards.append(Card(ROULEUR[i]))
elif rider[0:1].upper() == 'S':
for i in range(len(SPRINTER)):
self._cards.append(Card(SPRINTER[i]))
@property
def recycleDeck(self):
return self._recycleDeck
def recycle(self, index: int):
self.recycleDeck.cards.append(self.remove_card(index))
def refresh_deck(self):
self.recycleDeck.shuffle # Shuffle the recycled cards (not those remaining in main deck)
for i in range(self.recycleDeck.count_cards -1, -1,-1): # Add the shuffled recycled cards back in to the back of the main deck
self.cards.append(self.recycleDeck.remove_card(i))
class Card():
def __init__(self, value):
self._value = value
@property
def value(self):
return self._value
class ExhaustCard(Card):
def __init__(self):
self._value = 2
# TO DO:
# - error handling on init verificaction
</code></pre>
<p>By contrast the file below feels bloated and messy. There must be a cleaner way to perform the interactive image initialisation instead of laboriously coding each item individually?</p>
<pre class="lang-py prettyprint-override"><code>############
# GUI Module
############
import tkinter as tk
from PIL import Image, ImageTk
import GameLogic as GL
from tkinter import messagebox
# Constants
CARD_W = 180
CARD_H = 300
W_MULT = 1.2
TEAMS = ('Blue', 'Red', 'Green', 'Black', 'White', 'Pink')
RIDERS = ('Rouleur', 'Sprinter')
PLAYER = ('Player', 'Bot: Muscle Team', 'Bot: Peloton Team')
HANDSIZE = 4
DECK_PATHS = ('deck_main_R', 'deck_exhaust_R', 'FR_logo', 'deck_main_S', 'deck_exhaust_S')
##################
# LaunchWindow Class
##################
class LaunchWindow:
def __init__(self, master):
self.master = master
# Make the frames
self.frm_header = tk.Frame(self.master)
self.frm_options = tk.Frame(self.master)
self.frm_colour = tk.Frame(master=self.frm_options)
self.frm_player = tk.Frame(master=self.frm_options)
self.frm_footer = tk.Frame(master=self.master)
# (1) Header widgets
tk.Label(master=self.frm_header, text='Flamme Rouge', anchor=tk.NW, font=('Verdana', 50), fg='red').pack(side=tk.TOP, pady=10, padx=10)
tk.Label(master=self.frm_header, text='Select team type options', anchor=tk.NW, font=('Verdana', 25)).pack(side=tk.TOP,pady=5)
# (2) Team Choice Widgets
# (A) Team Colour Choice Input
colour_choice = tk.StringVar()
tk.Label(master= self.frm_colour, text='Team colour:').pack(side=tk.TOP, pady = 3)
for team in TEAMS:
textcolour = 'White'
if team == 'White' or team == 'Pink':
textcolour = 'Black'
rb_teams = tk.Radiobutton(master= self.frm_colour, text=team, value=team, variable=colour_choice, bg=team, fg=textcolour)
rb_teams.pack(anchor=tk.N)
# (B) Player (Human or Bot) Choice Input
player_choice = tk.StringVar()
tk.Label(master=self.frm_player, text='Team Type:').pack(side=tk.TOP, pady=3)
for p in PLAYER:
rb_teams = tk.Radiobutton(master=self.frm_player, text=p, value=p, variable=player_choice, indicatoron=0)
rb_teams.pack(anchor=tk.N)
# (3) Footer Widgets
self.btn_start = tk.Button(master=self.frm_footer, text='Start Game', anchor=tk.S,
relief=tk.RAISED, font=('Verdana', 35),
command=lambda: self.start_game(colour_choice.get(), player_choice.get()),
padx=20, pady=10).pack(side=tk.LEFT)
self.btn_close = tk.Button(master=self.frm_footer, text='Close', anchor=tk.S, padx=20, pady=10,
relief=tk.RAISED, font=('Verdana', 25), command=self.handle_close).pack(side=tk.LEFT)
#Pack the frames
self.frm_header.pack(side=tk.TOP)
self.frm_colour.pack(side=tk.LEFT)
self.frm_player.pack(side=tk.LEFT)
self.frm_options.pack(side=tk.TOP)
self.frm_footer.pack(side=tk.BOTTOM, pady = 10)
# Handle events, clicks etc
def handle_close(self):
self.master.destroy()
def start_game(self, colour: str, team_type: str):
self.master.destroy()
game_window = tk.Tk()
game = GameWindow(game_window, colour, team_type)
##################
# GameWindow Class
##################
class GameWindow:
def __init__(self, master, colour, teamtype): # Create labels, entries,buttons
self.master = master
# Make the frames
self.frm_header = tk.Frame(self.master)
self.frm_decks = tk.Frame(self.master)
self.frm_cards = tk.Frame(self.master)
self.frm_footer = tk.Frame(self.master)
# Initialise the Card decks according to user input on launch window
self._deck_R = GL.MainDeck(colour, 'Rouleur', teamtype)
self._deck_S = GL.MainDeck(colour, 'Sprinter', teamtype)
self.deck_R.shuffle
self.deck_S.shuffle
# (1) Header Widgets
tk.Label(master=self.frm_header, text=colour+' Team', fg=colour, bg='grey', anchor=tk.NW, font=('Verdana', 35, 'bold')).pack(side=tk.TOP, pady=10)
# (2) Deck Widgets
deck_images = []
deck_btns = []
# (a) Rouleur deck
deck_images.append(ImageTk.PhotoImage(Image.open(f'Images/{DECK_PATHS[0]}.jpg').resize((int(CARD_W*W_MULT), CARD_H))))
deck_btns.append(tk.Button(master=self.frm_decks, width=int(CARD_W*W_MULT), height=CARD_H, image=deck_images[0],
command=lambda:self.show_hand(self.deck_R)))
deck_btns[0].image = deck_images[0]
deck_btns[0].grid(row=2, column=1, padx=20, pady=20)
# (b) Rouleur Exhaustion
deck_images.append(ImageTk.PhotoImage(Image.open(f'Images/{DECK_PATHS[1]}.jpg').resize((int(CARD_W*W_MULT), CARD_H))))
deck_btns.append(tk.Button(master=self.frm_decks, width=int(CARD_W*W_MULT), height=CARD_H, image=deck_images[1],
command=lambda:self.pickup_exhaust(self.deck_R.recycleDeck)))
deck_btns[1].image = deck_images[1]
deck_btns[1].grid(row=2, column=2, padx=20, pady=20)
# (c) FR Logo
deck_images.append(ImageTk.PhotoImage(Image.open(f'Images/{DECK_PATHS[2]}.jpg').resize((int(CARD_W*2), CARD_H))))
deck_btns.append(tk.Label(master=self.frm_decks, width=int(CARD_W*2.2), height=CARD_H, image=deck_images[2]))
deck_btns[2].image = deck_images[2]
deck_btns[2].grid(row=2, column=3, padx=20, pady=20)
# (d) Sprinter Deck
deck_images.append(ImageTk.PhotoImage(Image.open(f'Images/{DECK_PATHS[3]}.jpg').resize((int(CARD_W * W_MULT), CARD_H))))
deck_btns.append(tk.Button(master=self.frm_decks, width=int(CARD_W * W_MULT), height=CARD_H, image=deck_images[3],
command=lambda: self.show_hand(self.deck_S)))
deck_btns[3].image = deck_images[3]
deck_btns[3].grid(row=2, column=4, padx=20, pady=20)
# (e) Sprinter Exhaustion
deck_images.append(ImageTk.PhotoImage(Image.open(f'Images/{DECK_PATHS[4]}.jpg').resize((int(CARD_W * W_MULT), CARD_H))))
deck_btns.append(tk.Button(master=self.frm_decks, width=int(CARD_W * W_MULT), height=CARD_H, image=deck_images[4],
command=lambda: self.pickup_exhaust(self.deck_S.recycleDeck)))
deck_btns[4].image = deck_images[4]
deck_btns[4].grid(row=2, column=5, padx=20, pady=20)
# (f) Rouleur: deck label & card count
tk.Label(master=self.frm_decks, text='Rouleur Deck', font=('Verdana', 20), anchor=tk.S).grid(row=1,column=1)
self.vR = tk.StringVar()
tk.Label(master=self.frm_decks, textvariable=self.vR, font=('Verdana', 12), anchor=tk.N).grid(row=3,column=1)
self.vRrec = tk.StringVar()
tk.Label(master=self.frm_decks, textvariable=self.vRrec, font=('Verdana', 12), anchor=tk.N).grid(row=4, column=1)
# (g) Sprinter: deck label & card count
tk.Label(master=self.frm_decks, text='Sprinter Deck', font=('Verdana', 20), anchor=tk.S).grid(row=1, column=4)
self.vS = tk.StringVar()
tk.Label(master=self.frm_decks, textvariable=self.vS, font=('Verdana', 12), anchor=tk.N).grid(row=3, column=4)
self.vSrec = tk.StringVar()
tk.Label(master=self.frm_decks, textvariable=self.vSrec, font=('Verdana', 12), anchor=tk.N).grid(row=4, column=4)
# (h) Exhaustion labels
tk.Label(master=self.frm_decks, text='Rouleur Exhaustion Cards', font=('Verdana', 20), anchor=tk.S).grid(row=1, column=2)
tk.Label(master=self.frm_decks, text='Sprinter Exhaustion Cards', font=('Verdana', 20), anchor=tk.S).grid(row=1, column=5)
# (4) Footer Widgets
self.btn_close = tk.Button(master=self.frm_footer, text='Close', anchor=tk.S,
relief=tk.RAISED, font=('Verdana', 25), command=self.handle_close,
padx=10, pady=10).pack(side=tk.BOTTOM)
# Pack the frames
self.frm_header.pack(side=tk.TOP)
self.frm_decks.pack(side=tk.TOP)
self.frm_cards.pack(side=tk.TOP)
self.frm_footer.pack(side=tk.BOTTOM)
self.update_counts()
### END INIT
#Properties, getters
@property
def deck_R(self):
return self._deck_R
@property
def deck_S(self):
return self._deck_S
# Handle events, clicks etc
def handle_close(self):
self.master.destroy()
def show_hand(self, deck: GL.MainDeck, num=HANDSIZE):
# Check we have enough cards, if not, shuffle and reintroduce cards in the recycle deck
if deck.count_cards < num:
messagebox.askokcancel('information', f'You have used all your {deck.rider} cards! Shuffling and reintroducing recycled cards...',)
deck.refresh_deck()
self.update_counts()
hand = GL.Deck(deck.team, deck.rider, deck.teamtype)
self.frm_cards.pack()
for i in range(0,num):
crd = deck.get_card(i)
hand.add(crd)
# Hand widgets
imgs = hand.getFilePaths()
hand_photos = []
for im in imgs:
hand_photos.append(ImageTk.PhotoImage(Image.open(im).resize((CARD_W, CARD_H))))
hand_btns = []
for i in range(len(imgs)):
hand_btns.append(tk.Button(master=self.frm_cards, width=CARD_W, height=CARD_H,
image=hand_photos[i],
command=lambda i=i: self.playthecard(hand, i)))
hand_btns[i].image = hand_photos[i]
hand_btns[i].grid(row=1, column=i, padx=20, pady=20)
# Pick up an exhaustion card and add to the recycle deck for that rider
def pickup_exhaust(self, deck: GL.Deck, num=1):
for i in range(0,num):
answer = messagebox.askokcancel("Question", f'Collect an exhaustion card for your {deck.rider.upper()}?')
if answer:
ex_crd = GL.ExhaustCard()
deck.add(ex_crd)
self.update_counts()
# Given a subdeck (e.g. a hand), returns the relevant main deck of cards, i.e. either the player's Rouleur deck or Sprinter Deck
def getTargetDeck(self, D: GL.Deck) -> GL.MainDeck:
if D.rider[0:1].upper() == 'R':
return self.deck_R
elif D.rider[0:1].upper() == 'S':
return self.deck_S
# Play the selected card; i.e. burn it, eliminate from the deck without recycling. Recycle the rest of the hand.
def playthecard(self, hand: GL.Deck, i: int):
answer = messagebox.askokcancel('information', f'Play the {hand.rider} {hand.get_card(i).value} card and recycle the other cards?', )
if answer:
currentDeck = self.getTargetDeck(hand)
ToRecycle = hand.getRemainders(i)
for index in ToRecycle:
currentDeck.recycle(index) #Recycle the unused cards into recycle deck
currentDeck.remove_card(0) # Index 0 not index i. After remainder cards have been recycled (above), the first card in the Maindeck list will be that selected by the player.
self.frm_cards.pack_forget() # Clear the hand widgets from view (does not destroy!)
self.update_counts()
# Update the main deck card counts on the GUI
def update_counts(self):
self.vR.set(f'{self.deck_R.count_cards} cards in Rouleur deck')
self.vS.set(f'{self.deck_S.count_cards} cards in Sprinter deck')
self.vRrec.set(f'and {self.deck_R.recycleDeck.count_cards} recycled cards')
self.vSrec.set(f'and {self.deck_S.recycleDeck.count_cards} recycled cards')
# Run it
def main():
window = tk.Tk()
app = GameWindow(window, 'Pink', 'Player')
window.mainloop()
if __name__ == '__main__':
print('GUI Main called')
main()
</code></pre>
<p>And finally... this probably didn't need a file of it's own did it lololol..</p>
<pre class="lang-py prettyprint-override"><code>import GUI
import tkinter as tk
# Launch the game window
window = tk.Tk()
app = GUI.LaunchWindow(window)
window.mainloop()
</code></pre>
<p>Thank you very much in advance!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T18:53:48.047",
"Id": "498100",
"Score": "1",
"body": "Hey RoadBadger :) There's one important skill you can learn using the CodeReview website and it's to give good context on what code is supposed to do :) Right now, you state that game rules aren't important, but that's you'd like to make sure your code doesn't have bugs you didn't see. But how can we know this if we don't know the rules :) You'll need to give us the context of the code (and change your post title to what the code does!) in order for us to help!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T19:15:10.960",
"Id": "498102",
"Score": "1",
"body": "I don't want to vote to close this question, since a little edit that adds proper context will make it good!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T20:07:08.337",
"Id": "498108",
"Score": "1",
"body": "Thanks for the feedback guys - will edit the question to explain what the code is supposed to do."
}
] |
[
{
"body": "<p>I can point out a few Python language features that will make the code a bit simpler. In <code>show()</code>:</p>\n<pre><code>@property\ndef show(self):\n i = 0\n total = self.count_cards\n for crd in self.cards:\n i += 1\n print(f'Value of card {i} of {total} in {self.team} {self.rider} deck is {crd.value}')\n if not isinstance(self,MainDeck):\n print('This is not the main deck')\n</code></pre>\n<ol>\n<li>Not a <code>@property</code> since it doesn't return anything</li>\n<li>Use the <code>enumerate()</code> function, let python handle the index variable</li>\n<li>The "not main deck" warning should be shown just once, not every card.</li>\n</ol>\n<p>So, for instance:</p>\n<pre class=\"lang-py prettyprint-override\"><code> def show(self):\n total = self.count_cards\n for (i, crd) in enumerate(self.cards):\n print(f'Value of card {i} of {total} in {self.team} {self.rider} deck is {crd.value}')\n if not isinstance(self,MainDeck):\n print('This is not the main deck')\n</code></pre>\n<p>In <code>shuffle()</code>:</p>\n<pre><code>@property\ndef shuffle(self):\n for i in range(self.count_cards -1, -1, -1):\n rnd = random.randint(0, i)\n self.cards[i], self.cards[rnd] = self.cards[rnd], self.cards[i]\n</code></pre>\n<ol>\n<li><p>Again, definitely not a <code>@property</code></p>\n</li>\n<li><p>Python has a <code>shuffle()</code> in the <code>random</code> module, no need to reinvent the wheel</p>\n<pre><code> import random\n\n ...\n\n def shuffle(self):\n random.shuffle(self.cards)\n</code></pre>\n</li>\n</ol>\n<p>In <code>countExhaustion()</code>:</p>\n<pre><code>@property\ndef countExhaustion(self) -> int:\n cnt = 0\n for crd in self.cards:\n if isinstance(crd, ExhaustCard):\n cnt += 1\n return cnt\n</code></pre>\n<ol>\n<li>Yes this is a <code>@property</code></li>\n<li>But it might be easier to just have an additional variable and keep it updated, since you know exactly when cards are added or removed whether it's an <code>ExhaustCard</code></li>\n<li>If you decide not to do that, use <code>sum()</code> to count:</li>\n</ol>\n<pre><code> @property\n def countExhaustion(self) -> int:\n return sum(1 for crd in self.cards if isinstance(crd, ExhaustCard))\n</code></pre>\n<p>In <code>MainDeck.__init__</code>:</p>\n<pre><code> if rider[0:1].upper() == 'R':\n for i in range(len(ROULEUR)):\n self._cards.append(Card(ROULEUR[i]))\n elif rider[0:1].upper() == 'S':\n for i in range(len(SPRINTER)):\n self._cards.append(Card(SPRINTER[i]))\n</code></pre>\n<p>This code is duplicated. You should write the code only once and use a <code>dict</code> to map between the first character of <code>rider</code> and which deck. Also the <code>extend()</code> method is defined for sequences which should be preferred over <code>append()</code> in a loop.</p>\n<pre><code>deckMap = {'R': ROULEUR, 'S': SPRINTER}\ndeck = deckMap[rider[0]].upper()\nself._cards.extend(deck)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T07:47:51.623",
"Id": "498137",
"Score": "2",
"body": "Just a small nitpick: there's no need to wrap `(i, crd)` around parentheses here: `for (i, crd) in enumerate(self.cards)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-28T15:46:58.260",
"Id": "498235",
"Score": "0",
"body": "Hi @Snowbody, thank you very much for the useful feedback! Much appreciated."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T02:00:05.193",
"Id": "252736",
"ParentId": "252723",
"Score": "1"
}
},
{
"body": "<p>I'll include inline comments on your second file.</p>\n<pre class=\"lang-py prettyprint-override\"><code>############\n# GUI Module\n############\nimport tkinter as tk\nfrom PIL import Image, ImageTk\nimport GameLogic as GL\nfrom tkinter import messagebox\n\n# Constants\nCARD_W = 180\nCARD_H = 300\nW_MULT = 1.2\nTEAMS = ('Blue', 'Red', 'Green', 'Black', 'White', 'Pink')\nRIDERS = ('Rouleur', 'Sprinter')\nPLAYER = ('Player', 'Bot: Muscle Team', 'Bot: Peloton Team')\nHANDSIZE = 4\nDECK_PATHS = ('deck_main_R', 'deck_exhaust_R', 'FR_logo', 'deck_main_S', 'deck_exhaust_S')\n</code></pre>\n<p>Parentheses are the syntax for a <code>tuple</code>, which usually signifies a heterogeneous bunch of related things that are parts of a whole. But it would be more idiomatic here to use square brackets and create a <code>list</code>, since it is a bunch of things of the same type which are accessed sequentially and are distinct from each other. It doesn't change the functionality.</p>\n<pre class=\"lang-py prettyprint-override\"><code>##################\n# LaunchWindow Class\n##################\nclass LaunchWindow:\n\n def __init__(self, master):\n self.master = master\n\n # Make the frames\n self.frm_header = tk.Frame(self.master)\n self.frm_options = tk.Frame(self.master)\n self.frm_colour = tk.Frame(master=self.frm_options)\n self.frm_player = tk.Frame(master=self.frm_options)\n self.frm_footer = tk.Frame(master=self.master)\n\n # (1) Header widgets\n tk.Label(master=self.frm_header, text='Flamme Rouge', anchor=tk.NW, font=('Verdana', 50), fg='red').pack(side=tk.TOP, pady=10, padx=10)\n tk.Label(master=self.frm_header, text='Select team type options', anchor=tk.NW, font=('Verdana', 25)).pack(side=tk.TOP,pady=5)\n\n # (2) Team Choice Widgets\n # (A) Team Colour Choice Input\n colour_choice = tk.StringVar()\n tk.Label(master= self.frm_colour, text='Team colour:').pack(side=tk.TOP, pady = 3)\n</code></pre>\n<p>Both here and in other places, the spacing around the named parameters' <code>=</code>s is inconsistent -- pick a style and stick with it.</p>\n<pre class=\"lang-py prettyprint-override\"><code> for team in TEAMS:\n textcolour = 'White'\n if team == 'White' or team == 'Pink':\n textcolour = 'Black'\n</code></pre>\n<p>It would be slightly more idiomatic to define <code>LIGHT_COLOURS</code> outside the loop and then condense this to one line, e.g. <code>textcolour = 'Black' if team in LIGHT_COLOURS else 'White'</code> to avoid repeating <code>team</code> and <code>textcolour</code></p>\n<pre class=\"lang-py prettyprint-override\"><code> rb_teams = tk.Radiobutton(master= self.frm_colour, text=team, value=team, variable=colour_choice, bg=team, fg=textcolour)\n rb_teams.pack(anchor=tk.N)\n</code></pre>\n<p>Why do you create a variable <code>rb_teams</code> only to immediately throw it away? Just put the <code>.pack()</code> at the end of the line like you did with the other UI elements you're not concerned with.</p>\n<pre class=\"lang-py prettyprint-override\"><code> # (B) Player (Human or Bot) Choice Input\n player_choice = tk.StringVar()\n tk.Label(master=self.frm_player, text='Team Type:').pack(side=tk.TOP, pady=3)\n for p in PLAYER:\n rb_teams = tk.Radiobutton(master=self.frm_player, text=p, value=p, variable=player_choice, indicatoron=0)\n rb_teams.pack(anchor=tk.N)\n</code></pre>\n<p>This is wrong and confusing; these aren't teams buttons but player buttons. Lose the variable name and put the <code>.pack</code> on the same line.</p>\n<pre class=\"lang-py prettyprint-override\"><code> # (3) Footer Widgets\n self.btn_start = tk.Button(master=self.frm_footer, text='Start Game', anchor=tk.S,\n relief=tk.RAISED, font=('Verdana', 35),\n command=lambda: self.start_game(colour_choice.get(), player_choice.get()),\n padx=20, pady=10).pack(side=tk.LEFT)\n</code></pre>\n<p>The <code>lambda</code> here is confusing, as you're mixing program logic into the middle of UI definitions. Create a separate method.</p>\n<pre class=\"lang-py prettyprint-override\"><code> self.btn_close = tk.Button(master=self.frm_footer, text='Close', anchor=tk.S, padx=20, pady=10,\n relief=tk.RAISED, font=('Verdana', 25), command=self.handle_close).pack(side=tk.LEFT)\n #Pack the frames\n self.frm_header.pack(side=tk.TOP)\n self.frm_colour.pack(side=tk.LEFT)\n self.frm_player.pack(side=tk.LEFT)\n self.frm_options.pack(side=tk.TOP)\n self.frm_footer.pack(side=tk.BOTTOM, pady = 10)\n</code></pre>\n<p>This is confusing; other items were packed at the time of creation, but these are packed after a bunch of other stuff is done. Also the comment doesn't add anything, it's obvious from the code. Comments should explain <em>why</em> something is being done. The code itself should make it clear <em>what</em> is being done.</p>\n<pre class=\"lang-py prettyprint-override\"><code> # Handle events, clicks etc\n def handle_close(self):\n self.master.destroy()\n\n def start_game(self, colour: str, team_type: str):\n self.master.destroy()\n game_window = tk.Tk()\n game = GameWindow(game_window, colour, team_type)\n\n\n\n##################\n# GameWindow Class\n##################\nclass GameWindow:\n</code></pre>\n<p>One class per file usually, please.</p>\n<pre class=\"lang-py prettyprint-override\"><code> def __init__(self, master, colour, teamtype): # Create labels, entries,buttons\n</code></pre>\n<p>Again this comment is more confusing than helpful. Anyone looking at the code and see that's what it's doing. Don't add comments just for the sake of having comments; the comments should explain your thinking and make it easier for someone to understand the code.</p>\n<pre class=\"lang-py prettyprint-override\"><code> self.master = master\n\n # Make the frames\n self.frm_header = tk.Frame(self.master)\n self.frm_decks = tk.Frame(self.master)\n self.frm_cards = tk.Frame(self.master)\n self.frm_footer = tk.Frame(self.master)\n\n # Initialise the Card decks according to user input on launch window\n</code></pre>\n<p>Except you don't know that. Classes/methods/functions called with parameters shouldn't know or care where their parameters came from. What if you at some point created a "game replay" feature that allowed replaying of a past game -- then the params would <em>not</em> come from user input in the launch window.</p>\n<pre class=\"lang-py prettyprint-override\"><code> self._deck_R = GL.MainDeck(colour, 'Rouleur', teamtype)\n self._deck_S = GL.MainDeck(colour, 'Sprinter', teamtype)\n self.deck_R.shuffle\n self.deck_S.shuffle\n</code></pre>\n<p>This is confusing; these two decks are clearly the same kind of thing. Looks like the code will alternate between them. Why not put them in a <code>list</code> that you then index into? Then you could do things like <code>for deck in self.decks: deck.shuffle</code> rather than duplicating code.</p>\n<p>Also I don't understand why you're sometimes using the underscore version and sometimes the non-underscore version. What's the benefit of making a member private if you then go and make it completely accessible?</p>\n<pre class=\"lang-py prettyprint-override\"><code> # (1) Header Widgets\n tk.Label(master=self.frm_header, text=colour+' Team', fg=colour, bg='grey', anchor=tk.NW, font=('Verdana', 35, 'bold')).pack(side=tk.TOP, pady=10)\n</code></pre>\n<p>I don't like repeated strings <code>'Verdana'</code> -- you should put the font name in a constant so you can easily change it everywhere.</p>\n<pre class=\"lang-py prettyprint-override\"><code> # (2) Deck Widgets\n deck_images = []\n deck_btns = []\n</code></pre>\n<p>Okay. Here is a key clue about what you're doing wrong. Python has very strong list manipulation techniques. It's almost never ideal to start with an empty list and then add items to it. Instead, create a list that defines how it will be created, and then use list comprehensions.</p>\n<p>A related issue is, are <code>deck_images</code> and <code>deck_btns</code> the same size and corresponding to each other? If so they should probably be a single list of <code>tuple</code>s, <code>class</code>es, or <code>collections.namedtuple</code>s.</p>\n<p>e.g. <code>DECK_CONFIG</code> as a mixture of DECK_PATHS and DECK_IMAGES, then say <code>deck_ui = [(ImageTk.PhotoImage(Image.open(f'Images/{dc.path}.jpg').resize(dc.dimensions), tk.Button(..., image=dc.image, command=dc.command) for dc in deck_config]</code></p>\n<pre><code> # (a) Rouleur deck\n deck_images.append(ImageTk.PhotoImage(Image.open(f'Images/{DECK_PATHS[0]}.jpg').resize((int(CARD_W*W_MULT), CARD_H))))\n deck_btns.append(tk.Button(master=self.frm_decks, width=int(CARD_W*W_MULT), height=CARD_H, image=deck_images[0],\n command=lambda:self.show_hand(self.deck_R)))\n deck_btns[0].image = deck_images[0]\n</code></pre>\n<p>You already set that in the previous line.</p>\n<pre class=\"lang-py prettyprint-override\"><code> deck_btns[0].grid(row=2, column=1, padx=20, pady=20)\n\n # (b) Rouleur Exhaustion\n deck_images.append(ImageTk.PhotoImage(Image.open(f'Images/{DECK_PATHS[1]}.jpg').resize((int(CARD_W*W_MULT), CARD_H))))\n deck_btns.append(tk.Button(master=self.frm_decks, width=int(CARD_W*W_MULT), height=CARD_H, image=deck_images[1],\n command=lambda:self.pickup_exhaust(self.deck_R.recycleDeck)))\n deck_btns[1].image = deck_images[1]\n deck_btns[1].grid(row=2, column=2, padx=20, pady=20)\n\n # (c) FR Logo\n deck_images.append(ImageTk.PhotoImage(Image.open(f'Images/{DECK_PATHS[2]}.jpg').resize((int(CARD_W*2), CARD_H))))\n deck_btns.append(tk.Label(master=self.frm_decks, width=int(CARD_W*2.2), height=CARD_H, image=deck_images[2]))\n deck_btns[2].image = deck_images[2]\n deck_btns[2].grid(row=2, column=3, padx=20, pady=20)\n\n # (d) Sprinter Deck\n deck_images.append(ImageTk.PhotoImage(Image.open(f'Images/{DECK_PATHS[3]}.jpg').resize((int(CARD_W * W_MULT), CARD_H))))\n deck_btns.append(tk.Button(master=self.frm_decks, width=int(CARD_W * W_MULT), height=CARD_H, image=deck_images[3],\n command=lambda: self.show_hand(self.deck_S)))\n deck_btns[3].image = deck_images[3]\n deck_btns[3].grid(row=2, column=4, padx=20, pady=20)\n\n # (e) Sprinter Exhaustion\n deck_images.append(ImageTk.PhotoImage(Image.open(f'Images/{DECK_PATHS[4]}.jpg').resize((int(CARD_W * W_MULT), CARD_H))))\n deck_btns.append(tk.Button(master=self.frm_decks, width=int(CARD_W * W_MULT), height=CARD_H, image=deck_images[4],\n command=lambda: self.pickup_exhaust(self.deck_S.recycleDeck)))\n deck_btns[4].image = deck_images[4]\n deck_btns[4].grid(row=2, column=5, padx=20, pady=20)\n\n # (f) Rouleur: deck label & card count\n tk.Label(master=self.frm_decks, text='Rouleur Deck', font=('Verdana', 20), anchor=tk.S).grid(row=1,column=1)\n self.vR = tk.StringVar()\n tk.Label(master=self.frm_decks, textvariable=self.vR, font=('Verdana', 12), anchor=tk.N).grid(row=3,column=1)\n self.vRrec = tk.StringVar()\n tk.Label(master=self.frm_decks, textvariable=self.vRrec, font=('Verdana', 12), anchor=tk.N).grid(row=4, column=1)\n</code></pre>\n<p>It's confusing here to intersperse UI setup and setting members of the class. Again this should probably be a config list and then a loop.</p>\n<pre class=\"lang-py prettyprint-override\"><code> # (g) Sprinter: deck label & card count\n tk.Label(master=self.frm_decks, text='Sprinter Deck', font=('Verdana', 20), anchor=tk.S).grid(row=1, column=4)\n self.vS = tk.StringVar()\n tk.Label(master=self.frm_decks, textvariable=self.vS, font=('Verdana', 12), anchor=tk.N).grid(row=3, column=4)\n self.vSrec = tk.StringVar()\n tk.Label(master=self.frm_decks, textvariable=self.vSrec, font=('Verdana', 12), anchor=tk.N).grid(row=4, column=4)\n</code></pre>\n<p>I really suggest putting these v* elements into a list or map rather than having a bunch of separate variables.</p>\n<pre class=\"lang-py prettyprint-override\"><code> # (h) Exhaustion labels\n tk.Label(master=self.frm_decks, text='Rouleur Exhaustion Cards', font=('Verdana', 20), anchor=tk.S).grid(row=1, column=2)\n tk.Label(master=self.frm_decks, text='Sprinter Exhaustion Cards', font=('Verdana', 20), anchor=tk.S).grid(row=1, column=5)\n\n # (4) Footer Widgets\n self.btn_close = tk.Button(master=self.frm_footer, text='Close', anchor=tk.S,\n relief=tk.RAISED, font=('Verdana', 25), command=self.handle_close,\n padx=10, pady=10).pack(side=tk.BOTTOM)\n\n # Pack the frames\n self.frm_header.pack(side=tk.TOP)\n self.frm_decks.pack(side=tk.TOP)\n self.frm_cards.pack(side=tk.TOP)\n self.frm_footer.pack(side=tk.BOTTOM)\n self.update_counts()\n\n ### END INIT\n\n #Properties, getters\n @property\n def deck_R(self):\n return self._deck_R\n</code></pre>\n<p>This is useless. The purpose of having a getter is to control access to the member and make sure that only authorized actions are performed. But you're allowing anyone to perform any action. Better to not even have it.</p>\n<pre class=\"lang-py prettyprint-override\"><code> @property\n def deck_S(self):\n return self._deck_S\n\n\n # Handle events, clicks etc\n def handle_close(self):\n self.master.destroy()\n\n def show_hand(self, deck: GL.MainDeck, num=HANDSIZE):\n # Check we have enough cards, if not, shuffle and reintroduce cards in the recycle deck\n if deck.count_cards < num:\n messagebox.askokcancel('information', f'You have used all your {deck.rider} cards! Shuffling and reintroducing recycled cards...',)\n deck.refresh_deck()\n self.update_counts()\n\n hand = GL.Deck(deck.team, deck.rider, deck.teamtype)\n self.frm_cards.pack()\n\n for i in range(0,num):\n</code></pre>\n<p>Just use <code>range(num)</code>; 0 is the default start</p>\n<pre class=\"lang-py prettyprint-override\"><code> crd = deck.get_card(i)\n hand.add(crd)\n\n # Hand widgets\n imgs = hand.getFilePaths()\n hand_photos = []\n for im in imgs:\n hand_photos.append(ImageTk.PhotoImage(Image.open(im).resize((CARD_W, CARD_H))))\n hand_btns = []\n for i in range(len(imgs)):\n hand_btns.append()\n hand_btns[i].image = hand_photos[i]\n hand_btns[i].grid(row=1, column=i, padx=20, pady=20)\n</code></pre>\n<p>Use list comprehension: <code>hand_btns = [tk.Button(master=self.frm_cards, width=CARD_W, height=CARD_H, image=ImageTk.PhotoImage(Image.open(im).resize((CARD_W, CARD_H))), command=lambda i=i: self.playthecard(hand, i)) for (i,im) in enumerate(imgs)]</code></p>\n<pre class=\"lang-py prettyprint-override\"><code> # Pick up an exhaustion card and add to the recycle deck for that rider\n def pickup_exhaust(self, deck: GL.Deck, num=1):\n for i in range(0,num):\n answer = messagebox.askokcancel("Question", f'Collect an exhaustion card for your {deck.rider.upper()}?')\n if answer:\n ex_crd = GL.ExhaustCard()\n deck.add(ex_crd)\n self.update_counts()\n\n # Given a subdeck (e.g. a hand), returns the relevant main deck of cards, i.e. either the player's Rouleur deck or Sprinter Deck\n def getTargetDeck(self, D: GL.Deck) -> GL.MainDeck:\n if D.rider[0:1].upper() == 'R':\n</code></pre>\n<p>You can just use <code>D.rider[0].upper()</code>, but this makes it clear that <code>deck_R</code> and <code>deck_S</code> should be in a <code>map</code> that's indexed by <code>'R'</code> or <code>'S'</code></p>\n<pre class=\"lang-py prettyprint-override\"><code> return self.deck_R\n elif D.rider[0:1].upper() == 'S':\n return self.deck_S\n\n # Play the selected card; i.e. burn it, eliminate from the deck without recycling. Recycle the rest of the hand.\n def playthecard(self, hand: GL.Deck, i: int):\n answer = messagebox.askokcancel('information', f'Play the {hand.rider} {hand.get_card(i).value} card and recycle the other cards?', )\n if answer:\n currentDeck = self.getTargetDeck(hand)\n ToRecycle = hand.getRemainders(i)\n for index in ToRecycle:\n currentDeck.recycle(index) #Recycle the unused cards into recycle deck\n currentDeck.remove_card(0) # Index 0 not index i. After remainder cards have been recycled (above), the first card in the Maindeck list will be that selected by the player.\n self.frm_cards.pack_forget() # Clear the hand widgets from view (does not destroy!)\n self.update_counts()\n\n # Update the main deck card counts on the GUI\n def update_counts(self):\n self.vR.set(f'{self.deck_R.count_cards} cards in Rouleur deck')\n self.vS.set(f'{self.deck_S.count_cards} cards in Sprinter deck')\n self.vRrec.set(f'and {self.deck_R.recycleDeck.count_cards} recycled cards')\n self.vSrec.set(f'and {self.deck_S.recycleDeck.count_cards} recycled cards')\n\n# Run it\ndef main():\n window = tk.Tk()\n app = GameWindow(window, 'Pink', 'Player')\n window.mainloop()\n\nif __name__ == '__main__':\n print('GUI Main called')\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-02T17:33:12.497",
"Id": "498607",
"Score": "1",
"body": "Hi @Snowbody thank you so much! That's just what I needed. Your comments are insightful and clear. I am delighted with the feedback. You clearly know your stuff. Just one question: I completely agree with the sentiment of \"why make a member private if you then go and make it completely accessible?\" and \"the purpose of a getter is to control access to the member and make sure that only authorised actions are performed but you're allowing anyone to perform any action\", but I don't quite see how/where I am doing that? I am so grateful, please let me know if I can return the favour somehow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-04T06:45:04.230",
"Id": "498774",
"Score": "0",
"body": "Yeah, I think you're right. I misunderstood that one. You can return the favor by becoming a better programmer day by day, and when you have spare time helping out other programmers become better, in whatever location suits you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-12T20:15:45.593",
"Id": "499697",
"Score": "0",
"body": "Ok, it's a deal! Thanks again"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-30T14:18:22.730",
"Id": "252846",
"ParentId": "252723",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T18:31:58.253",
"Id": "252723",
"Score": "7",
"Tags": [
"python",
"python-3.x",
"tkinter"
],
"Title": "Dealing cards for a game - my first Python project"
}
|
252723
|
<p>I've learn to code almost alone, so I really need some ideas/advice, as it started to get really difficult to advance.</p>
<p>Because this is mostly server side, I can't provide a running snippet, but yet it's a short snippet.</p>
<p><strong>Code</strong></p>
<p>When I press a UI button, it fetches a resource, and this should create a set of <strong>list items</strong>. Simple enough:</p>
<pre><code>const btn = document.getElementById("btn")
const ul = document.getElementById("ul")
const putItems = (items)=>{items.forEach(item=>ul.innerHTML=`
<li>${item.msg}</li>`)}
btn.addEventListener("click", ()=>{
fetch("https://localhost:3000/todos")
.then(res=>res.json())
.then(d=>putItems(d))
.catch(e=>console.log(e))
})
</code></pre>
<p>On the server side, the main function and imports are:</p>
<pre><code>const { MongoClient } = require("mongodb")
const cors = require('cors')
app.use(cors())
async function callDB(){ //get data from mongoDB
const call = await MongoClient.connect( uri, {useNewUrlParser:true, useUnifiedTopology:true})
let result
try{
result = await call
.db("todos")
.collection("items")
.find({})
.toArray()
} catch(e){
console.log(e)
}
return result;
}
app.get("/todos", cors(), (req, res)=>{
const items = callDB().then(d=>res.json(d)).catch(e=>console.log(e))
});
</code></pre>
<p>This code imports <code>dotenv</code> to hide my sensible parts, and uses <code>express</code> I removed those imports just to be concise.</p>
<p>Mainly, I'd like to know if my asynchronous practice makes sense, or not. And I'm also getting a CORS error, that couldn't fix after an hour. That would help too.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T15:53:26.300",
"Id": "498175",
"Score": "0",
"body": "If this code is not working, then it does not belong on codereview. It would be more appropriate on stakcoverflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T16:09:47.167",
"Id": "498178",
"Score": "0",
"body": "The `putItems()` code does not seem to do the right thing. It runs a loop, but only the last iteration of the loop ever ends up in the HTML as each successive iteration of the loop just replace the previous HTML."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T16:12:31.597",
"Id": "498179",
"Score": "0",
"body": "@jfriend00 right. it needs `+=` thanks."
}
] |
[
{
"body": "<p>There is a problem regarding error handling: in <code>callDB()</code> you catch all exceptions and log them in the console without passing them on to the caller. Either you should rethrow the exception (or a modified version that is more helpful for the caller) or not catch it at all. Since the <code>MongoClient.connect()</code> can also fail, I would move it into the try/catch as well:</p>\n<pre><code>async function getDataFromMongoDB() { // renamed so you don't need the comment\n try{\n const connection = await MongoClient.connect( uri, {\n useNewUrlParser: true,\n useUnifiedTopology: true\n });\n return await connection\n .db("todos")\n .collection("items")\n .find({})\n .toArray();\n } catch(e) {\n console.log(e);\n throw e; // or throw something else\n }\n}\n</code></pre>\n<p>This would be even more concise if you would extract the creation of the connection into its own function. However, I think you would like to write the whole function in one expression after the return, you would have to write it like this:</p>\n<pre><code>return await (await getConnection()).db("todos")...\n</code></pre>\n<p>The first await is required to keep error handling in this function.</p>\n<p>The request handler can also make use of async/await:</p>\n<pre><code>app.get("/todos", cors(), async (req, res)=> {\n try {\n const response = await callDB();\n res.json(response);\n }\n catch (e) {\n console.log(e);\n }\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T03:23:24.453",
"Id": "498123",
"Score": "0",
"body": "Why `return await await ...`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T06:55:03.770",
"Id": "498130",
"Score": "1",
"body": "It's actually not `await await` but written in two statements it would be `let c = await getConnection(); return await c.db(...)...;`I just substituted the c in the second statement with the right hand side expression of the first. If you would omit the await in the parentheses, you would call `db()` on a promise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T07:05:53.643",
"Id": "498131",
"Score": "0",
"body": "But, there's no point at all to `return await c.db(...).` That works the same as `return c.db()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T14:40:35.887",
"Id": "498164",
"Score": "0",
"body": "thanks. is the 1st function correct? `.then(d=>putItems(d)).catch(e=>console.log(e))` I'm not sure what is the importance of the catch there @jfriend00"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T14:52:23.853",
"Id": "498169",
"Score": "0",
"body": "@Minsky yes, the async handler will return/resolve As soon as the async db task finishes and writes to res. Your handler will return as soon as the async db task starts."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T15:57:25.917",
"Id": "498176",
"Score": "1",
"body": "@jfriend00 I'm afraid that's not correct. As I pointed out in my answer you need the await to have errors handled in the `catch` block. If you omit it, an unresolved promise will be returned that bypasses the error handling in the function. You can try it out here https://jsfiddle.net/4zj7u6yw/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T16:07:15.587",
"Id": "498177",
"Score": "0",
"body": "I'd also suggest in your suggestion for the request handler, you send an error response in the catch."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T18:34:04.103",
"Id": "498309",
"Score": "0",
"body": "Any reason for preferring `console.log` over `console.error`? It seems a little odd to catch the error, log it and then rethrow it. I'd just leave that out and let the caller have total control over the error handler since they need to write a `catch` block anyway."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T21:50:38.553",
"Id": "252728",
"ParentId": "252727",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "252728",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T21:17:59.547",
"Id": "252727",
"Score": "3",
"Tags": [
"javascript",
"beginner",
"asynchronous",
"promise"
],
"Title": "Starting with asynchronous JS and promises"
}
|
252727
|
<p>I want to use structs as a container for data packets for asynchronous networking in C#. Found out that you can create a union style struct without the need to mark the struct itself as unsafe--instead marking the field as unsafe.</p>
<p>Example:</p>
<pre><code>[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi, Size = 8, Pack = 4)]
struct DataPacketStruct {
private unsafe fixed byte bytes[8];
// Publicly accessible fields.
public byte header;
public int size;
public void Serialize(ref byte[] buffer, int startIndex) {
unsafe {
for (int i = 0; i < 8; i++) buffer[startIndex + i] = bytes[i];
}
}
public void Deserialize(byte[] buffer) {
unsafe {
for (int i = 0; i < 8; i++) bytes[i] = buffer[i];
}
}
public int SizeOf() { unsafe { return sizeof(DataPacketStruct); } }
}
</code></pre>
<p>I know I need array out of bounds checking--but apart from that. Potential downsides or undefined behaviors? Or is this usage valid? Also are there any potential performance concerns or any alternatives with similar performance?</p>
<p>Also an issue I can see right off the bat is not having compile-time numeric constants like in C++. Unfortunately have to hard code in the field offsets and structure size because of this: <code>Size = 8</code> and <code>byte[8]</code>.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-28T22:38:31.837",
"Id": "498259",
"Score": "0",
"body": "Afaik, .NET has enough powerful networking API that doesn't require any `unsafe` stuff. What's the purpose of the structure? Can you show and explain the usage example? `Explicit` structure can be needed for marshaling it to P/Invoke unmanaged function call e.g. send it as byte array. As option you may use `BinaryWriter` as managed alternative if you need just a byte array not P/Invoke."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-28T22:44:51.407",
"Id": "498260",
"Score": "1",
"body": "Did you see [this](https://stackoverflow.com/questions/3278827/how-to-convert-a-structure-to-a-byte-array-in-c)? Also consider `Buffer.BlockCopy` from `System.Buffers` as loop replacement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T01:50:01.763",
"Id": "498262",
"Score": "0",
"body": "@aepot it's a nice convenient way of creating packet data structures. You can write a byte stream to a struct and use the struct as a nice wrapper to represent your packet data."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T01:50:15.477",
"Id": "498263",
"Score": "1",
"body": "@aepot no, but thank you I'll be using it now."
}
] |
[
{
"body": "<p>There's a <code>safe</code> way to do that using <code>System.Runtime.InteropServices.Marshal</code> (<a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.marshal?view=netframework-4.8\" rel=\"nofollow noreferrer\">link</a>).</p>\n<pre class=\"lang-cs prettyprint-override\"><code>[StructLayout(LayoutKind.Sequential, Size = 8, Pack = 4)]\nstruct DataPacketStruct\n{\n public byte Header { get; set; }\n public int Size { get; set; }\n\n public void Serialize(byte[] buffer, int startIndex)\n {\n int size = SizeOf();\n IntPtr ptr = Marshal.AllocHGlobal(size);\n Marshal.StructureToPtr(this, ptr, true);\n Marshal.Copy(ptr, buffer, startIndex, size);\n Marshal.FreeHGlobal(ptr);\n }\n\n public static DataPacketStruct Deserialize(byte[] buffer, int startIndex)\n {\n var result = new DataPacketStruct();\n int size = result.SizeOf();\n IntPtr ptr = Marshal.AllocHGlobal(size);\n Marshal.Copy(buffer, startIndex, ptr, size);\n result = (DataPacketStruct)Marshal.PtrToStructure(ptr, typeof(DataPacketStruct));\n Marshal.FreeHGlobal(ptr);\n return result;\n }\n\n public int SizeOf() => Marshal.SizeOf(this);\n}\n</code></pre>\n<p>Also I used public properties and followed the <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/naming-guidelines\" rel=\"nofollow noreferrer\">Naming Guidelines</a> in the example.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>static void Main(string[] args)\n{\n var data = new DataPacketStruct() { Header = byte.MaxValue, Size = int.MaxValue };\n byte[] a = new byte[8];\n data.Serialize(a, 0);\n Console.WriteLine(string.Join(" ", a.Select(x => x.ToString("X2"))));\n var data2 = DataPacketStruct.Deserialize(a, 0);\n Console.WriteLine(JsonSerializer.Serialize(data2, new JsonSerializerOptions { WriteIndented = true }));\n Console.ReadKey();\n}\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>FF 00 00 00 FF FF FF 7F\n{\n "Header": 255,\n "Size": 2147483647\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T09:24:24.143",
"Id": "498270",
"Score": "1",
"body": "Nice! I've seen this implementation using Marshal, problem is if you run a test on it, I bet it's not nearly as fast."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T09:34:12.327",
"Id": "498271",
"Score": "1",
"body": "@FatalSleep there's no performance concern in the question above. Anyway, you may test it as you have the more real environment. In production environment I prefer something like JSON and HTTPS to transfer the data. It's more safe in terms of security. Writing network input directly to memory can be done only if you 100% trust the source. For socket-like data exchange i use WebSockets. That allows me to make browser client and desktop or mobile app clients using the same server."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T09:51:32.127",
"Id": "498272",
"Score": "0",
"body": "I have updated my question accordingly. I like the answer, but it doesn't really address the question, more so just says do it `safe`. Which, while I am using an unsafe methodology here, I did it in a specific manner to avoid having to mark the struct unsafe. Which normally one wouldn't do, but from a safety aspect not much is happening here IMO that is entirely problematic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T10:10:01.550",
"Id": "498274",
"Score": "1",
"body": "@FatalSleep Thank you for the feedback. I'm not sure that your way guarantee GC will not move the fields across the memory. You're making `unsafe` access to managed fields with no `fixed` directive which tells GC not to move that fields. That's why i can't confirm the correctness of your solution. By the first sight it looks suspicious. Maybe I'm wrong."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T22:24:21.760",
"Id": "498333",
"Score": "0",
"body": "could you put that in your answer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T22:27:24.807",
"Id": "498334",
"Score": "0",
"body": "@FatalSleep i don't like put something to the answer if i'm not absolutely sure in that. I'm not."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T08:46:45.910",
"Id": "252810",
"ParentId": "252730",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "252810",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T22:05:43.407",
"Id": "252730",
"Score": "4",
"Tags": [
"c#",
"serialization"
],
"Title": "Struct Serialization using Unsafe Field"
}
|
252730
|
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/251983/231235">A recursive_count Function For Various Type Arbitrary Nested Iterable Implementation in C++</a> and <a href="https://codereview.stackexchange.com/q/251295/231235">A Summation Function For Boost.MultiArray in C++</a>. I am trying to implement an <code>arithmetic_mean</code> template function for calculating the arithmetic mean value of various type arbitrary nested iterable things. The <code>recursive_reduce</code> function (thanks to <a href="https://codereview.stackexchange.com/a/251310/231235">G. Sliepen's answer</a>) and the <code>recursive_size</code> function are used here. Because both <code>recursive_reduce</code> function and <code>recursive_size</code> function are needed in the <code>arithmetic_mean</code> function here, there are two new concepts <code>is_recursive_reduceable</code> and <code>is_recursive_sizeable</code> created as follows.</p>
<pre><code>template<typename T>
concept is_recursive_reduceable = requires(T x)
{
recursive_reduce(x, 0.0);
};
template<typename T>
concept is_recursive_sizeable = requires(T x)
{
recursive_size(x);
};
</code></pre>
<p>Next, the main part of <code>arithmetic_mean</code> template function:</p>
<pre><code>template<class T> requires (is_recursive_reduceable<T> && is_recursive_sizeable<T>)
auto arithmetic_mean(const T& input)
{
return (recursive_reduce(input, 0.0)) / (recursive_size(input));
}
</code></pre>
<p>Some test cases of this <code>arithmetic_mean</code> template function.</p>
<pre><code>// std::vector<int> case
std::vector<int> test_vector = {
1, 2, 3
};
auto arithmetic_mean_result1 = arithmetic_mean(test_vector);
std::cout << arithmetic_mean_result1 << std::endl;
// std::vector<std::vector<int>> case
std::vector<decltype(test_vector)> test_vector2 = {
test_vector, test_vector, test_vector
};
auto arithmetic_mean_result2 = arithmetic_mean(test_vector2);
std::cout << arithmetic_mean_result2 << std::endl;
// std::deque<int> case
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(1);
test_deque.push_back(1);
auto arithmetic_mean_result3 = arithmetic_mean(test_deque);
std::cout << arithmetic_mean_result3 << std::endl;
// std::deque<std::deque<int>> case
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
auto arithmetic_mean_result4 = arithmetic_mean(test_deque2);
std::cout << arithmetic_mean_result4 << std::endl;
</code></pre>
<p><a href="https://godbolt.org/z/x8bz4W" rel="nofollow noreferrer">A Godbolt link is here.</a></p>
<p>All suggestions are welcome.</p>
<p>The summary information:</p>
<ul>
<li><p>Which question it is a follow-up to?</p>
<p><a href="https://codereview.stackexchange.com/q/251983/231235">A recursive_count Function For Various Type Arbitrary Nested Iterable Implementation in C++</a> and</p>
<p><a href="https://codereview.stackexchange.com/q/251295/231235">A Summation Function For Boost.MultiArray in C++</a></p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<p>The <code>arithmetic_mean</code> template function is the main part here.</p>
</li>
<li><p>Why a new review is being asked for?</p>
<p>I am not sure if it is a good idea to add <code>is_recursive_sizeable</code> and <code>is_recursive_reduceable</code> concepts here. Moreover, I am wondering that the name of used concept is understandable.</p>
</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T13:44:53.490",
"Id": "498161",
"Score": "0",
"body": "Arithmetic mean, even of two integers, has more [pitfalls](//stackoverflow.com/q/6735259/4850040) than you might expect!"
}
] |
[
{
"body": "<p>Instead of simply printing output, it would be better to have self-checking unit tests, so you can fail your build as soon as you break something, rather than having to notice a change in the output.</p>\n<p>You probably want to include some tests with very large (positive and negative) values to make sure you get accurate results with these, and don't fall foul of integer overflow (which will cause gross inaccuracy with unsigned types, and is Undefined Behaviour with signed integer types).</p>\n<p>It's disappointing that there are no tests using primitive types other than <code>int</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T13:35:40.530",
"Id": "252751",
"ParentId": "252732",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "252751",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T23:17:37.797",
"Id": "252732",
"Score": "2",
"Tags": [
"c++",
"recursion",
"c++20"
],
"Title": "An arithmetic_mean Function For Various Type Arbitrary Nested Iterable Implementation in C++"
}
|
252732
|
<p>I am working on a project where I need to work with http apis and call them using <code>Python</code> language. Below is what I need to do:</p>
<ul>
<li>Take few input parameters like - <code>environmentName</code>, <code>instanceName</code>, <code>configName</code>.</li>
<li>Call get API on a service. Get the JSON data and compare the <code>configName</code> it already has vs what you want to update from the command line.</li>
<li>If config is same then don't do anything and return back with a message.</li>
<li>But if config is different then post new JSON data with new <code>configName</code> passed from command line in it to the service using http api. In this there are two things:
<ul>
<li>We will make new JSON with new <code>configName</code> in it along with one more key which is <code>action</code> and value of that will be <code>download</code>. After successfully posting this new JSON then we will call another api (<code>verifyApi</code>) to verify whether all machines have downloaded successfully that config or not. If they downloaded successfully then we will move to the next step otherwise we will fail and return.</li>
<li>If all machines downloaded successfully, then we will change <code>action</code> key to <code>verify</code> in the same JSON and then we will post it again. After successfully posting this new JSON, we will call same <code>verifyApi</code> to make sure all machines have verified successfully.</li>
</ul>
</li>
</ul>
<p>Once everything is successful return, otherwise fail it. Below is my code which does the job:</p>
<pre><code>import requests
import json
import sys
import base64
# define all constants
actions=['download', 'verify']
endpoint="http://consul.{}.demo.com/"
config_path="v1/kv/app-name/{}/config"
status_path="v1/kv/app-name/{}/status/{}"
catalog_path="v1/catalog/service/app-name?ns=default&tag={}"
raw="?raw"
def update( url, json ):
"""
This will make a PUT api call to update with new json config.
"""
try:
r = requests.put(url, data=json, headers={'Content-type': 'application/json'})
r.raise_for_status()
return True
except requests.exceptions.HTTPError as errh:
print ("Http Error:",errh)
except requests.exceptions.ConnectionError as errc:
print ("Error Connecting:",errc)
except requests.exceptions.Timeout as errt:
print ("Timeout Error:",errt)
except requests.exceptions.RequestException as err:
print ("OOps: Something Else",err)
return False
def check( environment, instance, config, action ):
"""
This will get list of all ipAddresses for that instance in that environment.
And then check whether each machine from that list have downloaded and verified successfully.
Basically for each 'action' type I need to verify things.
If successful at the end then print out the message.
"""
flag = True
catalog_url = endpoint.format(environment) + catalog_path.format(instance)
response = requests.get(catalog_url)
url = endpoint.format(environment) + status_path.format(instance) + raw
json_array = response.json()
count = 0
for x in json_array:
ip = x['Address']
count++
r = requests.get(url.format(ip))
data = r.json()
if action == 'download' and "isDownloaded" in data and data['isDownloaded'] and "currentCfg" in data and data['currentCfg'] == config:
continue
elif action == 'verify' and "activeCfg" in data and data['activeCfg'] == config:
continue
else:
flag = False #set to False if above two if statements fail
print("failed to " +action+ " on " +ip)
if flag and action == 'download':
print("downloaded successfully on all "+count+" machines")
elif flag and action == 'verify':
print("verified successfully on all "+count+" machines")
return flag
def main():
# capture inputs from command line
environment = sys.argv[1]
instance = sys.argv[2]
new_config = sys.argv[3]
# make url for get api to verify whether configs are same or not
# as mentioned in point 1.
url=endpoint.format(environment) + config_path.format(instance)
response = requests.get(url + raw)
data = json.loads(response.content)
remote_config = data['remoteConfig']
# compare remote_config in the json with config passed from command prompt
if remote_config == new_config:
print("cannot push same config")
return
# config is different
data['remoteConfig'] = new_config
# now for each action, update json and then verify whether that action completed successfully.
for action in actions:
data['action'] = action
if update(url, json.dumps(data)):
if check(environment, instance, new_config, action):
continue
else:
print(action+ " action failed")
return
else:
print("failed to update")
return
if __name__ == "__main__":
try:
sys.exit(main())
except KeyboardInterrupt:
print("\nCaught ctrl+c, exiting")
</code></pre>
<p><strong>Problem Statement</strong></p>
<p>I have my above code which works fine so opting for code review to see if there is any better way to do the above things efficiently. I am also sure we can rewrite the above code in a much cleaner manner compared to the way I have since I am relatively new to <code>Python</code> and may have made a lot of mistakes in designing it. Given this code will be running in production wanted to see what can be done to improve it.</p>
<p>The idea is something like this when I run it from the command line.</p>
<p>If everything is successful then it should look like this:</p>
<pre><code>python test.py dev master-instace test-config-123.tgz
downloaded successfully on all 10 machines
verified successfully on all 10 machines
config pushed successfully!!
</code></pre>
<p>In case of <code>download</code> action failure:</p>
<pre><code>python test.py dev master-instace test-config-123.tgz
failed to download on 1.2.3.4
failed to download on 4.2.3.4
download action failed
</code></pre>
<p>In the case of <code>verify</code> action failure:</p>
<pre><code>python test.py dev master-instace test-config-123.tgz
downloaded successfully on all 10 machines
failed to verify on 1.2.3.4
failed to verify on 4.2.3.4
verify action failed
</code></pre>
<p>or if there is any better way to make the output cleaner - I am open to the suggestion as well.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T08:12:12.547",
"Id": "498139",
"Score": "0",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T19:46:34.567",
"Id": "498192",
"Score": "0",
"body": "I updated my question title to match with my question. Thanks for the feedback."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T23:49:01.990",
"Id": "498338",
"Score": "0",
"body": "Are the function `verify` and the action `verify` related? I feel not, but in either cases it makes for a confusing piece of code!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T23:51:41.727",
"Id": "498339",
"Score": "0",
"body": "yeah they aren't related. Sorry let me change that to avoid confusion. Fixed it now. @IEatBagels"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-01T09:11:47.383",
"Id": "498456",
"Score": "0",
"body": "`if flag and action='download'` is a `SyntaxError`, it should be `if flag and action == 'download'`. Same for the `elif` branch following it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-01T14:27:07.537",
"Id": "498470",
"Score": "1",
"body": "@Graipher Fixed it, that was a copy mistake error I had. I modified few things on my notepad before posting it here. Sorry about that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-01T15:43:55.357",
"Id": "498474",
"Score": "0",
"body": "My thoughts are (a) there is some inconsistent error handling of http requests. Requests in update have exception handling but else where (primarily `get`) don't do that. Consider consolidating the error handling for generic errors (connection failed etc.) in a single method. (b) I would consider collecting errors, then printing them in the `check` function, over the use of `continue` and `Flag` (c) style points, encapsulate the checks (if) conditions into functions, avoid the repeated `environment.format` etc. Overall pretty good, just try not repeating any code and being consistent"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-01T20:16:51.337",
"Id": "498492",
"Score": "0",
"body": "yeah there are lot of areas in which this code can be improved, specially the areas you mentioned. I know I am not doing a good job in error handling so will read more about it and see what I can do. That's why I was hoping for a code review on my entire code and see if someone can help me redesign it in better way. @Bhaskar"
}
] |
[
{
"body": "<p>First of all, you did a pretty good job but there are definitely things that can be improved. Let's take them one by one.</p>\n<h2>1. Fix the bug</h2>\n<p>In Python, we can't do <code>count++</code> so your code would immediately fail. There are some possible reasons for why this hasn't been adopted by Python core developers, <a href=\"https://stackoverflow.com/questions/3654830/why-are-there-no-and-operators-in-python\">some of them being</a>:</p>\n<ul>\n<li>It generally encourages people to write less readable code;</li>\n<li>It mixes together statements and expressions, which is not good practice;</li>\n<li>Extra complexity in the language implementation, which is unnecessary in Python;</li>\n</ul>\n<p>To fix this, just replace that statement with: <code>count += 1</code>. It does the exact same thing.</p>\n<h2>2. Remove unused imports and reorder them</h2>\n<p>It is always a good practice to cleanup your code after you've written it. If you would've done this, you would've noticed that there's an unused import: <code>base64</code>. Remove it.</p>\n<p>Second, if you have some spare time, give <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8 (the official Python styleguide)</a> a read. <a href=\"https://www.python.org/dev/peps/pep-0008/#imports\" rel=\"nofollow noreferrer\">There</a>, you'll find out that the order of the imports can also be improved by grouping together stdlib imports (e.g.: <code>json</code>), 3rd party imports (e.g.: <code>requests</code>) and local specific imports. This has the advantage of making the code easier to read and the imports easier to spot. It might not seem too big of a deal now, but I've seen cases where there were like tens of imports used in the same file.</p>\n<h2>3. Digging into PEP8</h2>\n<p>I've already brought PEP8 into discussion and you should now be able to at least tell what it is. Let's try and apply some of its rules on your code:</p>\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/#constants\" rel=\"nofollow noreferrer\"><h3>3.1 Constants</h3></a></p>\n<blockquote>\n<p>Constants are usually defined on a module level and written in all\ncapital letters with underscores separating words. Examples include\n<code>MAX_OVERFLOW</code> and <code>TOTAL</code>.</p>\n</blockquote>\n<p><em>Exercise: figure out what constants you do have in your code snippet and do the proper changes</em></p>\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/#naming-conventions\" rel=\"nofollow noreferrer\"><h3>3.2 Naming conventions</h3></a></p>\n<ul>\n<li><p><code>def update( url, json ):</code> -> there should be no space before <code>url</code> and after <code>json</code>. You should also rename <code>json</code> into something else because it "<em>Shadows name 'json' from outer scope</em>" (this name is the same as the <code>json</code> library that you imported). A common convention here, if you still want to stick to this name, would be to add a <code>_</code> after <code>json</code>. As a result, you'll have: <code>def update(url, json):</code>.</p>\n</li>\n<li><p><code>print ("Http Error:",errh)</code> -> there should be no space after <code>print</code> (or any other called function); you should (<em>almost</em>) always add a space after a comma. As a result, you'll have <code>print("Http Error:", errh)</code>. There're other two things that I don't like here:</p>\n<p>a) The way you've formatted the string. There're other recommended ways of formatting a string: print("Http Error: {}".format(errh))<code>or in Python3.6+ using [f-strings](https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498):</code>print(f"Http Error: {errh}")`.</p>\n<p>b) What's <code>errh</code>? Wouldn't this be better named: <code>http_error</code>? I personally find naming variables / functions / classes / and so on to be the hardest thing in programming so I suggest you pay careful attention to this as better naming could save the future-you understand a piece of code you've written X years ago.</p>\n</li>\n</ul>\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/#comments\" rel=\"nofollow noreferrer\"><h3>3.3 Comments</h3></a></p>\n<p>How is the following comment adding any value to your code: <code># define all constants</code>? Try to ask you this question as if you're reading someone else's code and you'll do much better.</p>\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/#maximum-line-length\" rel=\"nofollow noreferrer\"><h3>3.4 Maximum line length (79 chars)</h3></a></p>\n<p>This is really debatable but I just wanted you to be aware of it.</p>\n<blockquote>\n<p>Some teams strongly prefer a longer line length. For code maintained\nexclusively or primarily by a team that can reach agreement on this\nissue, it is okay to increase the line length limit up to 99\ncharacters, provided that comments and docstrings are still wrapped at\n72 characters.</p>\n</blockquote>\n<hr />\n<p>Let's look how your code would look like after applying all of the above:</p>\n<pre><code>import json\nimport sys\n\nimport requests\n\n\nACTIONS = ['download', 'verify']\nENDPOINT = "http://consul.{}.demo.com/"\nCONFIG_PATH = "v1/kv/app-name/{}/config"\nSTATUS_PATH = "v1/kv/app-name/{}/status/{}"\nCATALOG_PATH = "v1/catalog/service/app-name?ns=default&tag={}"\nRAW = "?raw"\n\n\ndef update(url, json_):\n """\n This will make a PUT api call to update with new json config.\n """\n try:\n r = requests.put(url, data=json_, headers={'Content-type': 'application/json'})\n r.raise_for_status()\n return True\n except requests.exceptions.HTTPError as http_error:\n print(f"Http Error: {http_error}")\n except requests.exceptions.ConnectionError as connection_error:\n print(f"Error Connecting: {connection_error}")\n except requests.exceptions.Timeout as timeout_error:\n print(f"Timeout Error: {timeout_error}")\n except requests.exceptions.RequestException as request_error:\n print(f"Ops: Something Else: {request_error}")\n\n return False\n\n\ndef check(environment, instance, config, action):\n """\n This will get list of all ipAddresses for that instance in that environment.\n And then check whether each machine from that list have downloaded and \n verified successfully. Basically for each 'action' type I need to verify things.\n If successful at the end then print out the message.\n """\n \n flag = True\n catalog_url = ENDPOINT.format(environment) + CATALOG_PATH.format(instance)\n response = requests.get(catalog_url)\n url = ENDPOINT.format(environment) + STATUS_PATH.format(instance) + RAW\n json_array = response.json()\n count = 0\n for x in json_array:\n ip = x['Address']\n count += 1\n r = requests.get(url.format(ip))\n data = r.json()\n if (\n action == 'download' \n and "isDownloaded" in data \n and data['isDownloaded'] \n and "currentCfg" in data \n and data['currentCfg'] == config\n ):\n continue\n elif (\n action == 'verify' and "activeCfg" in data \n and data['activeCfg'] == config\n ):\n continue\n else:\n flag = False\n print(f"Failed to {action} on {ip}")\n\n if flag and action == 'download':\n print(f"Downloaded successfully on all {count} machines")\n elif flag and action == 'verify':\n print(f"Verified successfully on all {count} machines")\n\n return flag\n\n\ndef main():\n environment = sys.argv[1]\n instance = sys.argv[2]\n new_config = sys.argv[3]\n\n # make url for get api to verify whether configs are same or not\n # as mentioned in point 1.\n url = ENDPOINT.format(environment) + CONFIG_PATH.format(instance)\n response = requests.get(url + RAW)\n data = json.loads(response.content)\n remote_config = data['remoteConfig']\n \n if remote_config == new_config:\n print("cannot push same config")\n return\n\n # config is different\n data['remoteConfig'] = new_config\n \n # now for each action, update json and then verify whether that \n # action completed successfully.\n for action in ACTIONS:\n data['action'] = action\n if update(url, json.dumps(data)):\n if check(environment, instance, new_config, action):\n continue\n else:\n print(f"{action} action failed")\n return\n else:\n print("failed to update")\n return\n\n\nif __name__ == "__main__":\n try:\n sys.exit(main())\n except KeyboardInterrupt:\n print("\\nCaught ctrl+c, exiting")\n</code></pre>\n<p>As you can see, there're not too many changes here but let's now see what we can do in regards to your code logic.</p>\n<p>I'm going to do something a bit different. That means, I'm going to go through the problem description, not your code, and build this from scratch as I personally would.</p>\n<blockquote>\n<p>Take few input parameters like - environmentName, instanceName,\nconfigName</p>\n</blockquote>\n<p>For this, I'd build a function which parses the CLI arguments using <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\"><code>argparse</code></a></p>\n<pre><code>def parse_cli_arguments():\n parser = argparse.ArgumentParser(description='My description here')\n parser.add_argument('--environment', required=True, help='Environment')\n parser.add_argument('--instance', required=True, help='Instance')\n parser.add_argument('--new_config', required=True, help='New config')\n return parser\n</code></pre>\n<hr />\n<blockquote>\n<p>Call get API on a service. Get the JSON data and compare the\nconfigName it already has vs what you want to update from the command\nline.</p>\n</blockquote>\n<p>This has to be broken into multiple parts:</p>\n<ol>\n<li>Call API endpoint and get the data:</li>\n</ol>\n<pre><code>class GetDataFailure(Exception):\n pass\n\n\ndef get_data(url, endpoint):\n try:\n response = requests.get(f'{url}{endpoint}')\n response.raise_for_status()\n return response\n except requests.exceptions.RequestException as request_error:\n raise GetDataFailure(str(request_error))\n</code></pre>\n<p>Above, I've created a custom exception which I'm raising if something happens with our request. You should also have in mind that's good practice to always set a default timeout when playing around with requests (exercise for you to figure out how).</p>\n<p>2 & the rest: Now this is pretty confusing and I'm not sure your explanation of what should happen is clear enough. Let's say I don't have your code at my disposal and I want to follow your instructions. Do you think I'm gonna be able to do so given your steps?</p>\n<p>I'd love to see how you'll manage to do from here so I recommend you do what I've told you so far, break your problem into specific & clear tasks and translate everything to code.</p>\n<p>For example (similar to yours), let's say I want to fetch some data (JSON) from a URL and check if a specific value from that JSON matches my CLI argument. How would I start this?</p>\n<ol>\n<li>What's the data I already have? A: URL, CLI argument, JSON value that I'm looking after. Write this down</li>\n<li>Break everything into smaller steps:</li>\n</ol>\n<ul>\n<li>pase CLI arguments</li>\n<li>make a request to a specific url</li>\n<li>check that we have JSON data returned from that endpoint and return it as json</li>\n<li>check cli argument against JSON value (if any) and return True.</li>\n<li>add everything in main</li>\n</ul>\n<p>Following the above, I'd suggest you rewrite your code and ask a separate question on code review.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-03T07:03:24.583",
"Id": "498683",
"Score": "0",
"body": "Thanks for great suggestion. I will go through your suggestion to see if I can make any progress. Yeah I know this code can be rewritten in better way and thats where I was kinda confuse to figure out on how to re-design it in a better way."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-02T21:09:35.533",
"Id": "252951",
"ParentId": "252737",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "252951",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T03:52:28.207",
"Id": "252737",
"Score": "8",
"Tags": [
"python",
"beginner",
"json",
"error-handling",
"http"
],
"Title": "Post json using http and verify whether all actions completed successfully or not"
}
|
252737
|
<p>I've been programming in C++ for over a decade and am thinking of learning Rust. Finding a number whose square is the sum of three different positive squares in at least two disjoint ways, which I used in test code in a C++ program, I wrote a Rust program to find out what other numbers' squares can be written as the sum of three different positive squares. Here's the program; how can it be improved?</p>
<pre><code>fn main()
{
for a in 1..101
{
let mut b=1;
while a*a-b*b>=0
{
let mut c=1;
while a*a-b*b-c*c>=0 && c<b
{
let mut d=1;
while a*a-b*b-c*c-d*d>=0 && d<c
{
if a*a-b*b-c*c-d*d==0
{
println!("{}²={}²+{}²+{}²",a,b,c,d);
}
d+=1;
}
c+=1;
}
b+=1;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>How can it be improved? Well, it all depends on your goals with the code. I'll assume the goal is to make it prettier and more in line with typical Rust style.</p>\n<p>First of all, <code>while</code> loops are rare in Rust code and you should replace them with <code>for</code>. This is because <code>while</code> works on your hand-rolled logic, whereas <code>for .. in ..</code> works with external iteration that is composable and idiomatic Rust.</p>\n<p>I see you have one <code>for</code> loop already. Let's turn all others into <code>for</code>.</p>\n<p>You always start with <code>1</code>, so the first iterator will be <code>(1..)</code>. We keep taking elements of the range as long as a condition is satisfied, so the next element of the iteration pipeline will be <code>.take_while(|&b| </code>...<code>)</code>. This Rust standard library method best fits the situation.</p>\n<pre class=\"lang-rust prettyprint-override\"><code>fn main()\n{\n for a in 1..101\n {\n for b in (1..).take_while(|&b| a*a-b*b >= 0)\n {\n for c in (1..b).take_while(|&c| a*a-b*b-c*c>=0)\n {\n for d in (1..c).take_while(|&d| a*a-b*b-c*c-d*d>=0)\n {\n if a*a-b*b-c*c-d*d==0\n {\n println!("{}²={}²+{}²+{}²",a,b,c,d);\n }\n }\n }\n }\n }\n}\n</code></pre>\n<p>This code is much more idiomatic already. Next up, I noticed that the intent of the two inner loops is to iterate until we hit the number above, so let's make two simple changes:</p>\n<ul>\n<li><code>for c in (1..b).take_while(|&c| a*a-b*b-c*c>=0)</code></li>\n<li><code>for d in (1..c).take_while(|&d| a*a-b*b-c*c-d*d>=0)</code></li>\n</ul>\n<p>For readability, we can Don't-Repeat-Yourself by making a tiny function.</p>\n<pre class=\"lang-rust prettyprint-override\"><code>fn square_diff(a: i32, b: i32, c: i32, d: i32) -> i32 { a*a-b*b-c*c-d*d }\n</code></pre>\n<p>For all instances of <code>a*a-b*b</code> or <code>a*a-b*b-c*c</code> or ..., we replace them with <code>square_diff(a, b, 0, 0)</code> etc.</p>\n<p>One more observation: <code>(1..).take_while(|b| square_diff(a, b, 0, 0) >= 0)</code> is equivalent to <code>1..=a</code>.</p>\n<p>Next up, we don't do C-style indentation in Rust. We put a single space after every comma in arguments. The result so far is:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>fn main() {\n for a in 1..101 {\n for b in 1..=a {\n for c in (1..b).take_while(|&c| square_diff(a, b, c, 0) >= 0) {\n for d in (1..c).take_while(|&d| square_diff(a, b, c, d) >= 0) {\n if square_diff(a, b, c, d) == 0 {\n println!("{}²={}²+{}²+{}²", a, b, c, d);\n }\n }\n }\n }\n }\n}\n\nfn square_diff(a: i32, b: i32, c: i32, d: i32) -> i32 { a*a - b*b - c*c - d*d }\n</code></pre>\n<p>I tried to test whether these abstractions really reduce to zero-cost, but\nalas, Rust@godbolt failed me. Benchmarking is left as a small exercise.</p>\n<p>Good luck on your Rust journeys.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T15:13:45.607",
"Id": "252754",
"ParentId": "252740",
"Score": "1"
}
},
{
"body": "<p>The main readability improvement I see is using <code>for</code> and ranges for all of your loops — this is debatable but I see it as highlighting that the <em>overall structure</em> of your program is about iterating over numbers one by one (there is no 'skipping' where you write <code>c += b</code> or anything like that).</p>\n<p>Secondarily, I reformatted the code with <code>rustfmt</code> so as to follow standard style.</p>\n<pre class=\"lang-rust prettyprint-override\"><code>fn main() {\n for a in 1..=100 {\n for b in (1..).take_while(|b| a * a - b * b >= 0) {\n for c in (1..b).take_while(|c| a * a - b * b - c * c >= 0) {\n for d in (1..c).take_while(|d| a * a - b * b - c * c - d * d >= 0) {\n if a * a - b * b - c * c - d * d == 0 {\n println!("{}²={}²+{}²+{}²", a, b, c, d);\n }\n }\n }\n }\n }\n}\n</code></pre>\n<p>I chose to use <code>take_while</code> to express the stopping conditions that weren't simply upper limits of the numeric ranges, but this is equivalent to explicitly stopping the loop such as by</p>\n<pre class=\"lang-rust prettyprint-override\"><code> ...\n for b in 1.. {\n if !(a * a - b * b >= 0) {\n break;\n }\n ...\n</code></pre>\n<p>After that, the next thing that's bothering me is all the repeated subexpressions. Arguably, keeping them as they are makes the program mathematically clearer, but I think it will further help readability of the <em>algorithm</em> if the expressions are less repeated.</p>\n<pre class=\"lang-rust prettyprint-override\"><code>fn main() {\n for a in 1..=100 {\n let target = a * a;\n for b in (1..).take_while(|b| target - b * b >= 0) {\n let target = target - b * b;\n for c in (1..b).take_while(|c| target - c * c >= 0) {\n let target = target - c * c;\n for d in (1..c).take_while(|d| target - d * d >= 0) {\n if target - d * d == 0 {\n println!("{}²={}²+{}²+{}²", a, b, c, d);\n }\n }\n }\n }\n }\n}\n</code></pre>\n<p>Now it is clear that the program is doing the same search three times nested. <strong>This would be a perfectly fine time to stop</strong> and say we've made it readable.</p>\n<p>But what if we'd like to not actually have to write the search three times? We can do that by moving the repeated algorithm into a function that produces an iterator.</p>\n<pre class=\"lang-rust prettyprint-override\"><code>fn squares_subtracted(minuend: i32, stop_before: i32) -> impl Iterator<Item = (i32, i32)> {\n (1..stop_before)\n .map(move |root| {\n let result = minuend - root * root;\n (root, result)\n })\n .take_while(|(_, result)| *result >= 0)\n}\n\nfn main() {\n for a in 1..=100 {\n for (b, target) in squares_subtracted(a * a, a) {\n for (c, target) in squares_subtracted(target, b) {\n for (d, target) in squares_subtracted(target, c) {\n if target == 0 {\n println!("{}²={}²+{}²+{}²", a, b, c, d);\n }\n }\n }\n }\n }\n}\n</code></pre>\n<p>We could go further and refactor into a form where instead of nested loops, there's one iterator adapter applied three times. However, I don't think that would actually serve readability (or maintainability); it would only make sense if you are working in a larger context of mathematical brute-force searches <em>in general</em>, where you might want to use the same operation in several different combinations.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-03T20:33:21.570",
"Id": "498748",
"Score": "0",
"body": "Thanks, both of you! Can you explain the syntax of take_while? Why do you take the absolute value of c, and what does |&c| mean?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-03T21:01:19.690",
"Id": "498752",
"Score": "0",
"body": "@PierreAbbat `|c| ...` is a [*closure*, an anonymous function](https://doc.rust-lang.org/book/ch13-01-closures.html); the `|` characters enclose its parameter list and are unrelated to absolute value. An alternative would be to use `if ... { break; }` inside each loop to stop it when the condition is no longer met."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T15:15:19.513",
"Id": "252755",
"ParentId": "252740",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T07:54:51.117",
"Id": "252740",
"Score": "1",
"Tags": [
"beginner",
"rust"
],
"Title": "First Rust program - squares which are sum of squares"
}
|
252740
|
<p>Write a bash script for an ABC organization fulfilling the following requirements:</p>
<blockquote>
<ul>
<li>Takes an Employee's Name, designation, age, years of service and salary, extra working hours as an input.</li>
<li>Calculates remaining years of service. An Employee retires at the age of 60.</li>
<li>Check if the Employee is valid for salary appraisal. If an employee has been working for more than an year he deserves to be given an appraisal of 10%.</li>
<li>If an employee has given extra working hours within a month to the organization calculate bonus amount.
Per hour amount varies depending upon the designation. See the given table to calculate bonus according to designations.<br />
Designation Per hour-amount<br />
Higher-Management 1K<br />
Lower-management 800PKR<br />
Other staff 500 PKR</li>
<li>Print the Employee’s information along with bonus and appraisal amount</li>
</ul>
</blockquote>
<pre><code>read -p "Enter employee name: " ename # printing message and scanning variable
read -p "Enter designation: " designation # printing message and scanning variable
read -p "Enter age: " age # printing message and scanning variable
read -p "Enter years of service: " years # printing message and scanning variable
read -p "Enter salary: " salary # printing message and scanning variable
read -p "Enter extra working hours: " hours # printing message and scanning variable
years_remaining=$(( 60-age )) # calculating remaining years
#code to calculate appraisal
if [ "$years" -gt 1 ] # if condition
then
appraisal=$(( salary/10 )) # appraisal value
else
appraisal=0 # appraisal value
fi # end of if statement
#code to calculate the bonus
if [ "$designation" = "Higher-Management" ] # if condition
then
bonus=$(( 1000*hours )) # calculating bonus
elif [ "$designation" = "Lower-management" ] # else if condition
then
bonus=$(( 800*hours )) # calculating bonus
elif [ "$designation" = "Other staff" ] # else if condition
then
bonus=$(( 500*hours )) # calculating bonus
else
bonus=0
fi # end of if statement
echo "Employee name: $ename" # printing message
echo "Age: $age" # printing message
echo "Designation: $designation" # printing message
echo "Years of service: $years" # printing message
echo "Salary: $salary" # printing message
echo "Extra working hours: $hours" # printing message
echo "Bonus: $bonus" # printing message
echo "Appraisal: $appraisal" # printing message
echo "years_remaining:$years_remaining " # printing message
</code></pre>
|
[] |
[
{
"body": "<h2>Better comments</h2>\n<p>You have put a comment on almost every line that just restates what the code already says and does not add any information or clarification.</p>\n<p>This is a bad practice!<br />\nA comment that states "this is an if statement" makes the code less readable, by doubling the length of a line with no added value.</p>\n<p>When adding a comment, you should only do so if it provides information that is not in the code, or is difficult to extract from the code given average knowledge of the programing language.</p>\n<h2>Input validation</h2>\n<p>It is customary to check all user input before using it in your code.<br />\nUnless you have been explicitly instructed to assume that the input is valid, you should add some code, for example to make sure <code>age</code> is actually a number.</p>\n<p>Also, you may want to check for cases where <code>age >= 60</code> i.e. the employee is about to retire, or has retired already.</p>\n<h2>Better flow control</h2>\n<p>The long <code>if elif else</code> tree where you calculate the bonus should be replace with a <code>case</code> statement.<br />\nThis will make the code shorter, more readable, and make adding or removing bonus options easier.</p>\n<p>Also, store bonus multiplier in a variable to avoid repeating code:</p>\n<pre><code>case $designation in\n "Higher-Management")\n hour_bonus=1000\n ;;\n \n "Lower-management")\n hour_bonus=800\n ;;\n\n "Other staff")\n hour_bonus=500\n ;;\n\n *)\n hour_bonus=0\n ;;\nesac\n\nbonus=$((hours * hour_bonus))\n</code></pre>\n<p>Note, that you could also add <code>shopt -s nocasematch</code> before the <code>case</code> block to make the comparison case insensitive, so that if your user forgets to type capital letters (or forgets the caps lock on) your code can still match the <code>designation</code> to the proper bonus value.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T17:54:15.637",
"Id": "252763",
"ParentId": "252741",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T09:12:11.587",
"Id": "252741",
"Score": "1",
"Tags": [
"bash"
],
"Title": "Bash script for an ABC organization fulfilling the following requirements"
}
|
252741
|
<p>I am practicing programing in Java. I have started to make a <strong>Xs and Os</strong> (<strong>Tic-Tac-Toe</strong>) game and I began with baseline logic of the game. I would appreciate any advice on my programming style, what am I doing wrong and what is good about my code.</p>
<h3>Combinations class</h3>
<pre><code>public class Combinations
{
public static Map<Field, Mark> firstRow;
public static Map<Field, Mark> secondRow;
public static Map<Field, Mark> thirdRow;
public static Map<Field, Mark> firstColumn;
public static Map<Field, Mark> secondColumn;
public static Map<Field, Mark> thirdColumn;
public static Map<Field, Mark> backDiagonal;
public static Map<Field, Mark> forwardDiagonal;
private static List<Map<Field, Mark>> combinations = Arrays.asList(firstRow, secondRow, thirdRow,
firstColumn, secondColumn, thirdColumn,
backDiagonal, forwardDiagonal);
private static Map<Field, Mark> winingCombination = null;
public Combinations(Board board)
{
firstRow = Map.of(Field.A1, board.A1,
Field.B1, board.B1,
Field.C1, board.C1);
secondRow = Map.of(Field.A2, board.A2,
Field.B2, board.B2,
Field.C2, board.C2);
thirdRow = Map.of(Field.A3, board.A3,
Field.B3, board.B3,
Field.A2, board.C3);
firstColumn = Map.of(Field.A1, board.A1,
Field.A2, board.A2,
Field.A3, board.A3);
secondColumn = Map.of(Field.B1, board.B1,
Field.B2, board.B2,
Field.B3, board.B3);
thirdColumn = Map.of(Field.C1, board.C1,
Field.C2, board.C2,
Field.C3, board.C3);
backDiagonal = Map.of(Field.A1, board.A1,
Field.B2, board.B2,
Field.C3, board.C3);
forwardDiagonal = Map.of(Field.A3, board.A3,
Field.B2, board.B2,
Field.C1, board.C1);
}
public static boolean isFilled(Map<Field, Mark> combination)
{
for(Entry<Field, Mark> field : combination.entrySet())
{
if(!Mark.isEmpty(field.getValue()))
return false;
}
return true;
}
public static boolean isWiner(Map<Field, Mark> combination, Mark playerMark)
{
for(Entry<Field, Mark> field : combination.entrySet())
{
if(field.getValue() != playerMark)
return false;
}
return true;
}
public static boolean hasWiningCombination()
{
return winingCombination != null;
}
public Map<Field, Mark> getWiningCombination(Mark playerMark)
{
for(Map<Field, Mark> combination : combinations)
{
if(isWiner(combination, playerMark))
{
winingCombination = combination;
}
}
return winingCombination;
}
}
</code></pre>
<h3>Field enum class for fields on the board</h3>
<pre><code>public enum Field
{
A1, A2, A3,
B1, B2, B3,
C1, C2, C3;
public boolean isCorner(Field field)
{
switch(field)
{
case A1:
case A3:
case C1:
case C3:
return true;
default:
return false;
}
}
}
</code></pre>
<h3>Mark enum class for player marks on fields</h3>
<pre><code>public enum Mark
{
EMPTY,
X,
O;
public static boolean isEmpty(Mark field)
{
switch(field)
{
case EMPTY:
return true;
default:
return false;
}
}
public static Mark oposite(Mark mark)
{
switch(mark)
{
case X:
return O;
case O:
return X;
default:
return EMPTY;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T10:30:17.180",
"Id": "498152",
"Score": "3",
"body": "Can you add the class `Board`? And would also be nice to see an example of usage."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T21:51:20.483",
"Id": "498193",
"Score": "2",
"body": "Without the Board class, there's insufficient context for a proper review."
}
] |
[
{
"body": "<p>I would like to mention couple of points.</p>\n<ol>\n<li><p><strong>You don't need to use switch cases in <code>enum</code></strong>. It make code over complicated. You can rather use <code>EnumSet</code> and normal <code>if-else</code> condition for it. (updated code added below)</p>\n</li>\n<li><p><strong>Correct the spelling</strong> of opposite (form oposite). (updated code added below)</p>\n</li>\n<li><p><strong>Static fields should be initialized in static block</strong>, rather than in constructor.</p>\n</li>\n<li><p><strong>Better to initialize all static fields all together.</strong> Rather than initializing few in constructor and few at class level directly. Consider initializing <code>combinations</code> with other fields. Because when you will reset other fields with new object initialization, this field won't get initialized (or update).</p>\n</li>\n<li><p>Rather than making class level fields public, make it accessible through the public method, and <strong>make these class level fields private.</strong></p>\n</li>\n<li><p>Rather than making all methods as static, <strong>make use of Object Oriented Paradigm</strong>. So that if you want to give multiple implementation of class, you can inherit class and override the implementation. And different behavior can be achieved.</p>\n</li>\n<li><p>If all fields and methods are static, there is not use of making constructor and no need to class initialization. Rather mark class final and private constructor. This is <strong>prevent object initialization,</strong> which is not need in case of all static fields/methods of class. And provide static method to reset fields. (Not valid if you convert methods to non-static as per point 6)</p>\n</li>\n<li><p><strong>Rename class to make it self-explanatory.</strong> Combination name doesn't clear what it actually does.</p>\n</li>\n<li><p>I believe you are using Java 8 or above. <strong>Consider using Streams</strong> to iterate or Map/List.</p>\n</li>\n</ol>\n<hr />\n<pre><code>public enum Field {\n A1, A2, A3, \n B1, B2, B3, \n C1, C2, C3;\n\n private static EnumSet<Field> corners;\n\n static {\n corners = EnumSet.of(A1, A3, C1, C3);\n }\n\n public boolean isCorner(final Field field) {\n return corners.contains(field);\n }\n}\n</code></pre>\n<hr />\n<pre><code>public enum Mark {\n EMPTY, O, X;\n\n public static boolean isEmpty(final Mark field) {\n\n return field == EMPTY;\n }\n\n public static Mark oppsite(final Mark mark) {\n\n if (mark == O) {\n return X;\n } else if (mark == X) {\n return O;\n }\n\n return EMPTY;\n }\n}\n</code></pre>\n<hr />\n<p>If you can share <code>Board</code> class, probably we can help you better.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T10:40:38.040",
"Id": "252748",
"ParentId": "252745",
"Score": "4"
}
},
{
"body": "<h3>Mix of static vs. non-static</h3>\n<p>The biggest flaw, in my opinion, is the mix of static vs. non-static in the class. With your current implementation, if you create more than one instance of the class <code>Combinations</code> at the same time, the static maps will become unstable; since they will be shared across all instances and recreated in EACH new instance of the class.</p>\n<p>Make all the code static, with no constructor (using a <a href=\"https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html\" rel=\"nofollow noreferrer\">Static Initialization Blocks</a>), as stated by @notescrew</p>\n<p>Based on the current implementation, in my opinion, this class can be converted to a static utils class that check if there's a winner in the board.</p>\n<h3>Exposition of mutable items</h3>\n<p>Another flaw is that you expose your mutable collections to the outside of the class. This is a bad habit, in my opinion, since you can edit the state from any other class, you lose the control of the data inside the collection. To prevent that, hide the collections with the <code>private</code> keyword and ALWAYS return, either a new instance of the collection or an <a href=\"https://docs.oracle.com/en/java/javase/12/core/creating-immutable-lists-sets-and-maps.html\" rel=\"nofollow noreferrer\">unmodifiable implementation</a> in the getters or methods that return it (Combinations#getWiningCombination, ect).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T18:32:02.003",
"Id": "252765",
"ParentId": "252745",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T09:55:10.753",
"Id": "252745",
"Score": "2",
"Tags": [
"java",
"beginner",
"game",
"tic-tac-toe"
],
"Title": "Xs and Os game logic in Java"
}
|
252745
|
<p>I am using 2 functions written in Python to convert a DLG file to PDB energies:</p>
<pre><code>import glob
import os
import subprocess
import numpy as np
from vmd import vmdnumpy as vnp
from vmd import Molecule
from vmd import atomsel
def dlg_to_multiframepdb(fname):
inputstrings = subprocess.check_output("grep \"DOCKED:\" %s" % fname, shell=True).decode().split("\n")
output = ""
for s in inputstrings:
if s[8:12] == "ATOM" or s[8:12] == "HETA":
output += s[8:] + "\n"
elif s[8:14] == "ENDMDL":
output += "ENDMDL\n"
return output
def dlg_to_energy(fname):
inputstrings = subprocess.check_output("grep \"Estimated\" %s | sed 's/=//g' | awk '{print $8}'" % fname, shell=True).decode().split("\n")[:-1]
energies = np.array(inputstrings).astype(np.float)
return energies
# simple code: loop over the directory of DLG filles and convert each file to PDB
pwd = os.getcwd()
dlg= 'dlg'
#set directory to analyse
data = os.path.join(pwd,dlg)
dirlist = [os.path.basename(p) for p in glob.glob(data + '/*.dlg')]
os.chdir(data)
for dlg_file in dirlist:
energies = dlg_to_energy(dlg_file)
pdb = dlg_to_multiframepdb(dlg_file)
</code></pre>
<p>Briefly, the first function takes some part from the initial file using shell utility GREP, skipping some unused strings; and the second function - use GREP + SED to take specific strings from the same file and store it as a numpy array. How can the code be further improved?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T10:07:32.380",
"Id": "498149",
"Score": "0",
"body": "[Does this SO question help?](https://stackoverflow.com/q/44989808/1014587)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T10:08:38.693",
"Id": "498150",
"Score": "1",
"body": "This question does not match what this site is about. Code Review is about improving existing, working code. Code Review is not the site to ask for help in fixing your code when you already know the current code won't work. Once the code does what you want, we would love to help you do the same thing in a cleaner way! Please see our [help center](/help/on-topic) for more information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T10:48:21.807",
"Id": "498153",
"Score": "1",
"body": "right, thank you! my functions just lacked .decode() option! now the code is working and I am waiting for further suggestions regarding its improvement!"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T10:00:12.180",
"Id": "252746",
"Score": "1",
"Tags": [
"python"
],
"Title": "Subprocess opening files"
}
|
252746
|
<p>This program converts legacy markup in the form seen in the tests to the resulting markdown seen in the test's respective comment.</p>
<p>The full program is as uploaded as a <a href="https://gitlab.com/snippets/1924376" rel="nofollow noreferrer">snippet</a>, or you may see below</p>
<pre class="lang-js prettyprint-override"><code>let tests = [
"OneMatch<span class="math-container">$$$TwoMatch" // [One Match](OneMatch)[Two Match](TwoMatch)
, "OneMatch$$</span>$TwoMatch<span class="math-container">$$$ThreeMatch" // [One Match](OneMatch)[Two Match](TwoMatch)[Three Match](ThreeMatch)
, "E$$</span>$scapeMatch" // Escape Match
, "SimpleMatch" // [Simple Match](SimpleMatch)
, "Prefixed<span class="math-container">$$$MatchyMatch" // Prefixed [Matchy Match](MatchyMatch)
, "MatchMatchWith$$</span>$Suffix" // [Match Match With](MatchMatchWith) Suffix
, "MatchesWithPlural<span class="math-container">$$$s" // [Matches With Plural](MatchesWithPlural)s
, "This$$</span>$Gets$$$Escaped" // This Gets Escaped
]
</code></pre>
<p>The <code>$$$</code> delimits valid matches. Furthermore, a match is only valid if it is composed of two or more StartCased words.</p>
<p>Possible matches are checked against a regex and either formatted, or just returned:</p>
<pre class="lang-js prettyprint-override"><code>function parseWord(word) {
let linkRE = /\b[A-Z][a-z]+([A-Z][a-z]+)+\b/g
let validLinks = word.match(linkRE)
let stripped = word.replace(/\${3}/, '')
if (validLinks) {
return formatLinks(validLinks, stripped)
}
return _.startCase(stripped)
}
</code></pre>
<p>If we are to format the match we find the difference between the matched link and the entire found word. From there we decide whether to add the difference as a prefix or suffix to the link:</p>
<pre class="lang-js prettyprint-override"><code>function formatLinks(matches, stripped) {
let formatted_links = []
for (match of matches) {
let diff = difference(match, stripped)
if (isSimpleLink(diff)) {
formatted_links.push(formatAsSimpleLink(diff))
} else if (hasPrefix(diff)) {
formatted_links.push(formatAsPrefixedLink(diff))
} else if (hasSuffix(diff)) {
formatted_links.push(formatAsSuffixedLink(diff))
}
}
// There might be multiple links within a word
// in which case we join them and strip any duplicated parts
// (which are otherwise interpreted as suffixes)
if (formatted_links.length > 1) {
return combineLinks(formatted_links)
}
// Default case
return formatted_links[0]
}
</code></pre>
<p>The function, <code>difference</code>, is <a href="https://www.npmjs.com/package/fast-diff" rel="nofollow noreferrer">fast-diff</a> from npm. Which is defined as such:</p>
<pre class="lang-js prettyprint-override"><code>let result = difference('Good dog', 'Bad dog');
// [[-1, "Goo"], [1, "Ba"], [0, "d dog"]]
</code></pre>
<p>Here are the remaining helper functions (or you may view the <a href="https://gitlab.com/snippets/1924376" rel="nofollow noreferrer">snippet</a> for the rest):</p>
<pre class="lang-js prettyprint-override"><code>function combineLinks(links) {
links.join('').replace(/(?<=\)).*?(?=\[)/g, '')
}
function formatAsSimpleLink(diff) {
let link = diff[0][1]
let text = _.startCase(link)
return `[${text}](${link})`
}
function formatAsPrefixedLink(diff) {
let link = diff[1][1]
let text = _.startCase(link)
let prefix = _.startCase(diff[0][1])
return `${prefix} [${text}](${link})`
}
function formatAsSuffixedLink(diff) {
let link = diff[0][1]
let text = _.startCase(link)
let suffix = diff[1][1]
// don't capitalize plurals
if (suffixIsPlural(suffix) == false) {
suffix = _.startCase(diff[1][1])
return `[${text}](${link}) ${suffix}`
}
return `[${text}](${link})${suffix}`
}
function isSimpleLink(diff) {
return diff.length == 1
}
function hasPrefix(diff) {
return diff[0][0] == 1 && diff[1][0] == 0
}
function hasSuffix(diff) {
return diff[0][0] == 0 && diff[1][0] == 1
}
function suffixIsPlural(suffix) {
return suffix.slice(-1) == 's'
}
</code></pre>
<hr />
<p>My main concerns are:</p>
<ul>
<li>The looping in <code>formatLinks</code>, which is really only useful if the word has a suffix which is also a link</li>
<li>The magic numbers used to check the <code>diff</code>, e.g., <code>diff[0][1]</code></li>
<li>If there is a better way to tackle the problem.</li>
</ul>
|
[] |
[
{
"body": "<blockquote>\n<p>The magic numbers used to check the diff, e.g., <code>diff[0][0] == 1 && diff[1][0] == 0</code></p>\n</blockquote>\n<p>One small improvement is that <code>fast_diff</code> exports enum values that can be used instead, eg:</p>\n<pre><code>differencesArr[0][0] === diff.INSERT\ndifferencesArr[1][0] === diff.EQUAL\n</code></pre>\n<blockquote>\n<p>The looping in formatLinks, which is really only useful if the word has a suffix which is also a link</p>\n</blockquote>\n<p>The whole looping mechanism looks quite suspicious to me:</p>\n<ul>\n<li><p>Only the first <code>$$$</code> is replaced by the <code>.replace(/\\${3}/, '')</code> - if the word contains multiple <code>$$$</code>s, those beyond the first will be left in place</p>\n</li>\n<li><p>Inside <code>formatLinks</code>, you perform tests on and examine <em>only</em> the first element of the <code>diff</code> array, which is strange if there happen to be multiple matches</p>\n</li>\n<li><p>Then you have to clean the string afterwards - eg <code>OneMatch$$$TwoMatch$$$ThreeMatch</code> turns into <code>[One Match](OneMatch) Two Match Three MatchOne Match [Two Match](TwoMatch)One Match Two Match [Three Match](ThreeMatch)</code>, which needs to be transformed <em>again</em>. Seems inelegant and error-prone.</p>\n</li>\n</ul>\n<blockquote>\n<p>If there is a better way to tackle the problem.</p>\n</blockquote>\n<p>It looks like there are two fundamental categories a substring can fall into:</p>\n<ul>\n<li>One which is escaped, and no <code>[]()</code>s should be produced, like the whole span of <code>E$$$scapeMatch</code></li>\n<li>One which is not escaped, like the whole span of <code>OneMatch$$$TwoMatch</code></li>\n</ul>\n<p>To put each substring into one of these categories, I'd split by <code>$$$</code> which split <em>true, unescaped</em> matches. For example:</p>\n<pre><code>OneMatch$$$TwoMatch -> ['OneMatch', 'TwoMatch']\nE$$$scapeMatch -> ['E$$$scapeMatch']\n</code></pre>\n<p>Then you can iterate over each possible match, transforming the normal matches to their proper format, and leaving the escaped matches alone (save for removing their <code>$$$</code>s). Join the array of results, and there'll be 2 things left to do:</p>\n<ul>\n<li>Add spacing at the edges of match brackets, if they're next to a prefix or suffix (which can be done with a simple regex)</li>\n<li>Insert spaces between each word outside of brackets (which can be done with a simple regex)</li>\n</ul>\n<pre><code>const parseInput = input => input\n // Split into an array containing separate unescaped matches, escaped sequences, or prefixes/suffixes:\n .split(/\\${3}(?=[A-Z]|s?$)/)\n // Add []() brackets around unescaped matches and remove all $s:\n .map(transformSubstr)\n .join('')\n // Add spacing around brackets:\n .replace(/(?<=\\w)\\[/g, ' [')\n // Except right before an "s" suffix:\n .replace(/\\)(?!s)(?=\\w)/g, ') ')\n // Add spaces between each word outside of brackets:\n .replace(\n /(?!s$)\\w+(?=\\[|$)/g,\n words => words.replace(/\\B[A-Z]/g, ' $&')\n );\n\nconst transformSubstr = (substr) => {\n const normalWordsMatch = substr.match(/\\b[A-Z][a-z]+(?:[A-Z][a-z]+)+\\b/g);\n // If this section is an escaped match, a prefix, or a suffix, there won't be a match\n if (!normalWordsMatch) return substr.replace(/\\$/g, '');\n const words = normalWordsMatch[0].match(/[A-Z][a-z]+/g);\n return `[${words.join(' ')}](${words.join('')})`;\n};\n</code></pre>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const tests = [\n \"OneMatch{a1fc471a-9483-4af3-8960-7104aa8d3b97}$TwoMatch{183d6425-9d46-4c32-8ce1-55b02e15b3c1}$scapeMatch\" // Escape Match\n, \"SimpleMatch\" // [Simple Match](SimpleMatch)\n, \"Prefixed{12abb1ad-bc6b-49b9-af33-314c963350ac}$Suffix\" // [Match Match With](MatchMatchWith) Suffix\n, \"MatchesWithPlural{d63f36d7-04f1-446b-80d3-6c09885cb6f3}$Gets$$$Escaped\" // This Gets Escaped\n]\n\nconst parseInput = input => input\n // Split into an array containing separate unescaped matches, escaped sequences, or prefixes/suffixes:\n .split(/\\${3}(?=[A-Z]|s?$)/)\n // Add []() brackets around unescaped matches:\n .map(transformSubstr)\n .join('')\n // Add spacing around brackets:\n .replace(/(?<=\\w)\\[/g, ' [')\n // Except right before an \"s\" suffix:\n .replace(/\\)(?!s)(?=\\w)/g, ') ')\n // Add spaces between each word outside of brackets:\n .replace(\n /(?!s$)\\w+(?=\\[|$)/g,\n words => words.replace(/\\B[A-Z]/g, ' $&')\n );\n\nconst transformSubstr = (substr) => {\n const normalWordsMatch = substr.match(/\\b[A-Z][a-z]+(?:[A-Z][a-z]+)+\\b/g);\n // If this section is an escaped match, a prefix, or a suffix, there won't be a match\n if (!normalWordsMatch) return substr.replace(/\\$/g, '');\n const words = normalWordsMatch[0].match(/[A-Z][a-z]+/g);\n return `[${words.join(' ')}](${words.join('')})`;\n};\nfor (const input of tests) {\n console.log(parseInput(input));\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>I don't see any need for either of the external libraries anymore.</p>\n<hr />\n<p>A couple nitpicks about your original code, if you were to keep using it:</p>\n<p><strong>Always use <code>const</code></strong> when you can, which should be possible 95% of the time - only use <code>let</code> <a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">to warn future readers of the code</a> that you may be reassigning the variable in the future.</p>\n<p><strong>Avoid sloppy comparison</strong> with <code>==</code> and <code>!=</code> - better to use <code>===</code> and <code>!==</code>, whose rules are <a href=\"https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons\">much easier to understand</a>.</p>\n<p><strong>Always declare variables before using them</strong> - with <code>for (match of matches)</code>, you're implicitly creating a global <code>match</code> variable. (Use <code>for (const match of matches)</code> instead)</p>\n<p><strong><code>parseWord</code> name?</strong> There can be multiple words inside the variable passed to <code>parseWord</code>, eg <code>SimpleMatch</code> (though there's no space). Maybe call it something like <code>parseInput</code>.</p>\n<p><strong>Single-letter match?</strong> The current pattern being used in all the code here so far requires words to contain at least two characters. Is that really desirable? Consider, for example, what you'd want to happen given markup of <code>ACuteCat$$$ADog</code>. If that's permitted, you'd just need to change the <code>[a-z]+</code> to <code>[a-z]*</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T19:42:54.030",
"Id": "252769",
"ParentId": "252752",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "252769",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T14:30:02.957",
"Id": "252752",
"Score": "2",
"Tags": [
"javascript",
"markdown"
],
"Title": "Formatter for converting links in a legacy markup to markdown"
}
|
252752
|
<p>I've never messed with batch really so I'm trying to introduce myself. I made this to back up all registry data and organize it like this:</p>
<ul>
<li>RegBackup
<ul>
<li>November
<ul>
<li>11-27-2020
<ul>
<li>[Registry Files]</li>
</ul>
</li>
<li>11-28-2020
<ul>
<li>[Registry Files]</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li>Backup.bat</li>
</ul>
<p>The script is:</p>
<pre><code>@echo off
Rem set bat location as CD
cd /D "%~dp0"
Rem open explorer to CD
explorer "%~dp0"
setlocal EnableDelayedExpansion
Rem set Month string
set m=100
for %%m in (January
February
March
April
May
June
July
August
September
October
November
December
) do (
set /a m+=1
set month[!m:~-2!]=%%m
)
set monthNow=%date:~3,3%
set monthNow=%monthNow: =%
set monthName=!month[%monthNow%]!
Rem create/enter Month string directory
if not exist %monthName% mkdir %monthName%
Rem set for current date in mm-dd-yyyy format
SET Today=%date:~-10,2%"-"%date:~7,2%"-"%date:~-4,4%
Rem create/enter mm-dd-yyyy directory
if not exist %Today% mkdir %Today%
cd %Today%
Rem save registry files into mm-dd-yyyy
REG SAVE HKLM\SOFTWARE SOFTWARE
REG SAVE HKLM\SYSTEM SYSTEM
REG SAVE HKU\.DEFAULT DEFAULT
REG SAVE HKLM\SECURITY SECURITY
REG SAVE HKLM\SAM SAM
Rem go up a folder. aka to .bat location directory
cd ..
Rem move mm-dd-yyyy into Month directory/already exists, delete new, pretend never happened.
move %Today% %monthName% || rmdir /Q /S %Today%
</code></pre>
<p>I added some remarks just to more or less explain whats going on, but I feel like there's an easier way than creating <code>%Today%</code>, filling it, and <em>then</em> moving the whole thing with all its contents, so I was hoping I could get some feedback on any ways I could improve, or just pointing me in the direction would be great. I know windows has a built in backup I could use but that's no fun :p.</p>
<p>(I hope I'm posting properly, I tried to make sure to follow the posting rules, I'm sorry if I messed something up!)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T15:35:15.890",
"Id": "498172",
"Score": "3",
"body": "Oh dear. Why not PowerShell, if you have to go down this route?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T14:39:33.840",
"Id": "252753",
"Score": "3",
"Tags": [
"beginner",
"batch"
],
"Title": "Creating and Organizing Registry Backups"
}
|
252753
|
<p>I've written a little clock implementation in Java Swing. It now seems to work flawlessly after having terrible Swing specific timing problems. Please indicate if this is the way to draw the clock and if the passive / active combination (i.e. drawing from timer and drawing from e.g. <code>paintComponent</code>) has been programmed correctly.</p>
<p>I've left some question marks in the source code comments for things that I'm unsure of. It has been quite some time since my last Swing application, so any other comment is welcome too. Once it has been reviewed I can extend it to an alarm clock...</p>
<p>This is fully runnable code, programmed for Java 13 (it won't compile for Java 8).</p>
<pre><code>package digiclock;
import static digiclock.ClockUtil.convertFromDimensionInMM;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
public class DigiClock extends JFrame {
private static final long serialVersionUID = 1L;
private static final Dimension DIMENSION_IN_MM = new Dimension(60, 20);
private static final Dimension MINIMUM_DIMENSION_IN_MM = new Dimension(40, 20);
/**
* Inner class that allows for dragging and closing the clock frame.
*/
private class ClockMouseAdapter extends MouseAdapter {
private int pointerLocationX;
private int pointerLocationY;
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
DigiClock.this.dispose();
}
}
@Override
public void mousePressed(MouseEvent me) {
pointerLocationX = me.getX();
pointerLocationY = me.getY();
}
@Override
public void mouseDragged(MouseEvent me) {
DigiClock.this.setLocation(DigiClock.this.getLocation().x + me.getX() - pointerLocationX,
DigiClock.this.getLocation().y + me.getY() - pointerLocationY);
}
}
public static void main(String[] args) {
var clock = new DigiClock();
clock.setVisible(true);
}
public DigiClock() {
setTitle("24-hour clock");
// --> resizing hard to implement? setUndecorated(true); <--
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// reduces flickering during resize if set to same color as ClockPanel
setBackground(Color.DARK_GRAY);
setSize(convertFromDimensionInMM(DIMENSION_IN_MM));
setMinimumSize(convertFromDimensionInMM(MINIMUM_DIMENSION_IN_MM));
var clockFont = loadFont();
var clockPanel = new ClockPanel(ClockPrecision.SECOND, Color.GREEN, Color.DARK_GRAY, clockFont);
add(clockPanel);
var clockMouseAdapter = new ClockMouseAdapter();
addMouseListener(clockMouseAdapter);
addMouseMotionListener(clockMouseAdapter);
}
private static Font loadFont() {
Font font;
try {
var is = ClockUtil.class.getResourceAsStream("E1234.ttf");
font = Font.createFont(Font.TRUETYPE_FONT, is);
} catch(@SuppressWarnings("unused") Exception e) {
// choose a default font if the font cannot be loaded for some reason or other
font = new Font("Sans-Serif", Font.BOLD, 20);
}
return font;
}
}
</code></pre>
<p>the one and only panel, the magic happens here.</p>
<pre><code>package digiclock;
import static java.awt.RenderingHints.KEY_TEXT_ANTIALIASING;
import static java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_ON;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.time.Instant;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JPanel;
public class ClockPanel extends JPanel {
private static final long serialVersionUID = 1L;
private static final String MAX_SIZED_TIME_STRING = "00:00:00";
// i.e. 10 percent on both sides
private static final float MARGIN_PART = 0.1F;
public class ClockTimerTask extends TimerTask {
@Override
public void run() {
// --> is this how we should render? <---
ClockPanel.this.drawDigitalClock(ClockPanel.this.getGraphics());
var delay = calculateDelay(precision);
timer.schedule(new ClockTimerTask(), delay);
}
}
public class Repainter implements Runnable {
@Override
public void run() {
ClockPanel.this.drawDigitalClock(getGraphics());
}
}
private final Timer timer;
private final ClockPrecision precision;
private final Color foregroundColor;
private final Font clockFont;
private Font currentClockFont;
private boolean sizeChanged = true;
public ClockPanel(ClockPrecision precision, Color foregroundColor, Color backgroundColor, Font clockFont) {
this.precision = precision;
this.foregroundColor = foregroundColor;
this.clockFont = clockFont;
this.currentClockFont = clockFont;
setBackground(backgroundColor);
addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
sizeChanged = true;
}
});
// note that the Swing timer is so imprecise that it's usefulness is basically reduced to zero
this.timer = new Timer("ClockTimer");
var initialDelay = calculateDelay(precision);
this.timer.schedule(new ClockTimerTask(), initialDelay);
setIgnoreRepaint(true);
}
@Override
public void paintComponent(Graphics graphics) {
drawDigitalClock(graphics);
}
/**
* Draws the digital clock using the font field and given a graphics context.
*
* @param graphics the graphics contents
*/
// --> is synchronized sufficient to prevent deadlock in paintComponent e.g. during resizing? <--
public synchronized void drawDigitalClock(Graphics graphics) {
super.paintComponent(graphics);
var dimension = getSize();
var marginSizeX = dimension.width * MARGIN_PART;
var marginSizeY = dimension.height * MARGIN_PART;
var marginSizeMin = Math.min(marginSizeX, marginSizeY);
if (sizeChanged) {
var innerDimension = new Dimension((int) (dimension.width - 2 * marginSizeMin),
(int) (dimension.height - 2 * marginSizeMin));
currentClockFont = resizeFontForDimension(graphics, clockFont, MAX_SIZED_TIME_STRING, innerDimension);
sizeChanged = false;
}
graphics.setColor(foregroundColor);
// --> would it be a good idea to create my own graphics rendering here? <--
// e.g. var clockGraphics = graphics.create();
if (graphics instanceof Graphics2D) {
((Graphics2D) graphics).setRenderingHint(KEY_TEXT_ANTIALIASING, VALUE_TEXT_ANTIALIAS_ON);
}
graphics.setFont(currentClockFont);
var metrics = graphics.getFontMetrics(currentClockFont);
float xCenter = dimension.width * 0.5F;
float yCenter = dimension.height * 0.5F;
String timeString = getTimeString(precision, LocalTime.now());
int x = (int) (xCenter - metrics.stringWidth(MAX_SIZED_TIME_STRING) / 2.0F);
int y = (int) (yCenter + metrics.getHeight() / 2 - metrics.getDescent() / 2);
graphics.drawString(timeString, x, y);
Toolkit.getDefaultToolkit().sync();
}
private static int calculateDelay(ClockPrecision precission) {
var delayNow = Instant.now();
return precission.getInMilli() - (int) (delayNow.toEpochMilli() % precission.getInMilli());
}
private static String getTimeString(ClockPrecision precision, LocalTime time) {
// TODO take care of precision
// pattern for 24 hrs
var pattern = DateTimeFormatter.ofPattern("HH:mm:ss");
return time.format(pattern);
}
/**
* Calculates the best font size to fit in a certain dimension (in pixels) given a graphics context, a font-type and
* a maximum sized text; then returns the font.
*
* @param graphics the graphics for which to compute the dimensions
* @param font the font for which to compute the dimension
* @param text the (max sized) text to display
* @param forDimension the size in which the text needs to be displayed, excluding margins
* @return the correctly sized font
*/
private static Font resizeFontForDimension(Graphics graphics, Font font, String text, Dimension forDimension) {
// get metrics from the graphics
var metrics = graphics.getFontMetrics(font);
var lineMetrics = metrics.getLineMetrics(MAX_SIZED_TIME_STRING, graphics);
int orgTextWidth = metrics.stringWidth(text);
float ascent = lineMetrics.getAscent();
// calculate font size
float difTextWidth = (float) forDimension.width / (float) orgTextWidth;
float difTextHeigth = (float) forDimension.height / ascent;
float minDif = Math.min(difTextWidth, difTextHeigth);
return font.deriveFont(font.getSize2D() * minDif);
}
}
</code></pre>
<p>a single utility class</p>
<pre><code>package digiclock;
import java.awt.Dimension;
import java.awt.Toolkit;
public final class ClockUtil {
private static final float MM_IN_INCH = 0.0393701F;
private static final int RES = Toolkit.getDefaultToolkit().getScreenResolution();
private ClockUtil() {
// avoid instantiation
}
public static Dimension convertFromDimensionInMM(Dimension dimInMM) {
return new Dimension(mmToPixels(dimInMM.width), mmToPixels(dimInMM.height));
}
public static int mmToPixels(int mm) {
return (int) (mm * MM_IN_INCH * RES);
}
}
</code></pre>
<p>and finally the little enum</p>
<pre><code>package digiclock;
public enum ClockPrecision {
DECISECOND(100), SECOND(1000), MINUTE(60_000);
private int inMS;
private ClockPrecision(int inMS) {
this.inMS = inMS;
}
public int getInMilli() {
return inMS;
}
}
</code></pre>
<p>Things I already know:</p>
<ul>
<li>JavaDoc is incomplete;</li>
<li>Swing <code>Timer</code> / <code>repaint</code> doesn't work.</li>
</ul>
<p>Things I am curious about:</p>
<ul>
<li>the use of <code>Graphics</code> my code;</li>
<li>how to center the text in the Panel (current height calculation is mainly adjusted until it looked right);</li>
<li>possibility of deadlock.</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T16:56:04.510",
"Id": "498181",
"Score": "0",
"body": "Is there a reason you're drawing the time yourself instead of using a (or multiple) labels? Also, I guess you're aware that your mm to pixel conversion only works for certain screens correctly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-28T01:18:23.037",
"Id": "498200",
"Score": "0",
"body": "@Bobby Honestly I've just thought how to draw the time and wanting to add graphical elements later. Those might not be as easily captured in a label. I'm also not planning to use any kind of `LayoutManager` although I guess you could always use a `null` layout... As for the mm, sure I know that, but it is at least more useful than pixels in many cases."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T16:03:57.300",
"Id": "252756",
"Score": "4",
"Tags": [
"java",
"multithreading",
"swing",
"timer"
],
"Title": "Just a digital clock in Swing"
}
|
252756
|
<p>Hey I wrote a struct in C++ trying to represent a Pixel Component of a color
Here it is</p>
<pre><code>template<typename T, T min, T max>
struct PixelComponent {
static constexpr T MIN = min;
static constexpr T MAX = max;
T value;
PixelComponent() = default;
PixelComponent(T value) : value(value) {}
inline bool operator==(const PixelComponent &other) {
return value == other.value;
}
inline bool operator!=(const PixelComponent &other) {
return !(*this == other);
}
inline bool operator>(const PixelComponent &other) {
return value > other.value;
}
inline bool operator<(const PixelComponent &other) {
return !(*this > other) && *this != other;
}
inline bool operator>=(const PixelComponent& other){
return !(*this < other);
}
inline bool operator<=(const PixelComponent& other){
return !(*this > other);
}
inline PixelComponent &operator=(const T &elem) {
if (value == elem) {
return *this;
}
value = elem > MAX ? MAX : elem < MIN ? MIN : elem;
return *this;
}
inline PixelComponent &operator=(const PixelComponent &other) {
if (*this == other) {
return *this;
}
*this = other.value;
return *this;
}
inline PixelComponent &operator++(){
*this = ++value;
return *this;
}
inline PixelComponent &operator--(){
*this = --value;
return *this;
}
inline PixelComponent operator+(const T& elem){
PixelComponent result;
result = value + elem;
return result;
}
inline PixelComponent operator-(const T& elem){
PixelComponent result;
result = value - elem;
return result;
}
inline PixelComponent operator*(const T& elem){
PixelComponent result;
result = value * elem;
return result;
}
inline PixelComponent operator/(const T& elem){
PixelComponent result;
result = value / elem;
return result;
}
inline PixelComponent operator+(const PixelComponent& other){
PixelComponent result;
result = value + other.value;
return result;
}
inline PixelComponent operator-(const PixelComponent& other){
PixelComponent result;
result = value - other.value;
return result;
}
inline PixelComponent operator*(const PixelComponent& other){
PixelComponent result;
result = value * other.value;
return result;
}
inline PixelComponent operator/(const PixelComponent& other){
PixelComponent result;
result = value / other.value;
return result;
}
inline PixelComponent operator+=(const T& elem){
*this = *this + elem;
return *this;
}
inline PixelComponent operator-=(const T& elem){
*this = *this - elem;
return *this;
}
inline PixelComponent operator*=(const T& elem){
*this = *this * elem;
return *this;
}
inline PixelComponent operator/=(const T& elem){
*this = *this / elem;
return *this;
}
inline PixelComponent& operator+=(const PixelComponent& other){
*this = *this + other;
return *this;
}
inline PixelComponent& operator-=(const PixelComponent& other){
*this = *this - other;
return *this;
}
inline PixelComponent& operator*=(const PixelComponent& other){
*this = *this * other;
return *this;
}
inline PixelComponent& operator/=(const PixelComponent& other){
*this = *this / other;
return *this;
}
};
template<typename T, T min, T max>
std::ostream &operator<<(std::ostream &os, const PixelComponent<T, min, max> &component) {
os << component.value;
return os;
}
</code></pre>
<p>Please review this. I will be thankful for any suggestion or typos noticed) Please also review implementation of <code>value</code> always staying in range <code>[MIN,MAX]</code>. I have not added that validation in constructor, is there a nice way to do that?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T19:32:25.197",
"Id": "498191",
"Score": "0",
"body": "The code looks great. No need for `inline` request, code in a class declaration are inlined by default."
}
] |
[
{
"body": "<p><strong>Why?</strong></p>\n<p>I don't see any benefit to using this <code>PixelComponent</code> class over simply using the value type directly, because...</p>\n<hr />\n<p><strong>Clamping</strong></p>\n<p>... clamping to min and max values is less helpful than it appears.</p>\n<p>We might want a color to be clamped to the range <code>0.f</code> to <code>1.f</code> in our output. However, it's very useful to do calculations with colors outside of that range as an intermediate step (e.g. <code>(a + b) * 0.5f</code>). Clamping prevents us from doing that.</p>\n<p>Alternatively, if we were using a <code>std::uint8_t</code> as a color component (range <code>0</code> to <code>255</code>), clamping the value would be meaningless as we're already using the full range of the type (and misleading, since we'd overflow before the clamping occurred).</p>\n<p>So ultimately I'd suggest doing the clamping explicitly, when we need to as part of our color manipulation algorithm, and not in the pixel type itself.</p>\n<p>Note also that we can use <code>std::clamp()</code>, rather than writing our own clamping function.</p>\n<hr />\n<p><strong>Operator overloads</strong></p>\n<pre><code>inline PixelComponent operator+(const PixelComponent& other){\n PixelComponent result;\n result = value + other.value;\n return result;\n}\n\ninline PixelComponent operator+=(const T& elem){\n *this = *this + elem;\n return *this;\n}\n</code></pre>\n<p>The <code>inline</code> keyword isn't necessary if we put the function definition inside the class.</p>\n<p><code>operator+=</code> (and the other math-assignment operators) should return a <code>PixelComponent&</code>, not a copy.</p>\n<p>For a simple POD type, we can pass the parameter by value instead of by reference.</p>\n<p>We'd normally implement <code>operator+=</code> to make the actual changes to the value in-place. And then implement <code>operator+</code> using <code>operator+=</code>. This saves us from making unnecessary copies (although that isn't a big deal with a single POD value).</p>\n<hr />\n<pre><code>inline bool operator<(const PixelComponent &other) {\n return !(*this > other) && *this != other;\n}\n</code></pre>\n<p>Could be written as <code>return (other > *this);</code></p>\n<hr />\n<p><strong>Missing functions:</strong></p>\n<pre><code>inline PixelComponent &operator++() ...\n</code></pre>\n<p>Don't forget to overload the post-increment operator as well: <code>PixelComponent operator++(int)</code></p>\n<p>We're missing modular arithmetic operators: <code>a %= b</code> <code>a % b</code></p>\n<p>We're missing the unary negation (and plus) operators: <code>-a</code> <code>+a</code></p>\n<p>It's reasonable to want to do bitwise operations on integer color values, so maybe we should have those too...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T18:28:01.213",
"Id": "498186",
"Score": "0",
"body": "thank u man, such great advises, I am now struggling with implementing `struct Space` which has all this `PixelComponents` you may be interested https://stackoverflow.com/questions/65041648/c-struct-field-name-and-types-from-variadic-template?noredirect=1#comment114988393_65041648."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T18:28:21.560",
"Id": "498187",
"Score": "0",
"body": "Thx again for reviewing also this is the right answer with priceless advices."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-28T15:54:59.320",
"Id": "498238",
"Score": "0",
"body": "The comparison operator overloads are backwards. Traditionally, they are all implemented in terms of `operator <`; here, OP has them in terms of `operator >`. By defining them in terms of `operator <` they can be used in nearly all the Standard Algorithms in the `<algorithm>` header."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T18:24:23.270",
"Id": "252764",
"ParentId": "252758",
"Score": "5"
}
},
{
"body": "<p>Not sure if you really need an own class definition. Also your code doesn't do anything apart from the automatic clamping.</p>\n<p>I would suggest using something like</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>using PixelT = uint8_t;\n</code></pre>\n<p>somewhere in your code.\nMaybe it would also be interesting to see an example of how your code is used to suggest alternatives. One alternative would surely be to use the <a href=\"https://en.cppreference.com/w/cpp/algorithm/clamp\" rel=\"nofollow noreferrer\"><code>std::clamp</code></a> function. I guess you wouldn't have too many places in your code where you actually would add or multiply pixels. Using <code>std::clamp</code> here - or even your own version of clamp with fixed min/max values would probably work as well.</p>\n<p>Just a few hints about "style":</p>\n<ol>\n<li><p>Prefer direct initialization - or direct returns - over declaring a variable, then initializing it - e.g. writing</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>PixelComponent operator/(const T& elem){\n return PixelComponent(value / elem);\n}\n</code></pre>\n<p>Of course for this to work in your example the constructor that takes a value should also clamp the value - not only the assignment operator. Otherwise your interface will stick to this awkward need to invoke the <code>operator=</code>.</p>\n</li>\n<li><p>Do not use <code>inline</code> when not necessary - this should only be necessary for definitions outside of the class body inside the header. Nowadays the compiler would optimize automatically and would not consider the <code>inline</code> keyword any more.</p>\n</li>\n<li><p>Try to define <code>explicit</code> constructors (when one argument is given) - this inhibits conversion to a different type when that was actually not intended.</p>\n</li>\n</ol>\n<p>See many many other rules in the <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md\" rel=\"nofollow noreferrer\">Cpp Core Guidelines</a> - yes - this language is complicated. But have fun anyway!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-28T14:59:09.120",
"Id": "252787",
"ParentId": "252758",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "252764",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T16:27:57.677",
"Id": "252758",
"Score": "3",
"Tags": [
"c++",
"validation",
"template",
"interval",
"overloading"
],
"Title": "C++ PixelComponent struct"
}
|
252758
|
<p>My express.js application uses a lot of promises for interacting with a variety of services. Instead of including try/catch with each one, I've setup a fail safe factory method for all my express controllers. This should only be called when an unexpected error occurred. For example, 404 when trying a public API. I'm skeptical about how useful this is or if there is a much easier way to do this. Also looking for any other comments on this code or question.</p>
<pre class="lang-javascript prettyprint-override"><code>//index.ts
import * as Express from 'express';
import { Auth } from '../class/Auth';
/**
* Handler for async static functions recognizing that errors
* should always be sent to the error handler. This is where
* our error stone drops. This will eventuall replace go().
* @param callback function to be run
* @return function for express to run
*/
function $(callback:Function):Function {
return async (req:Express.Request, res:Express.Response, next:Express.NextFunction) => {
try {
await callback(req, res, next);
} catch(e) {
console.error("Something strange occurred",e);
res.status(500).render('error', {
error: "An internal error has occurred",
errorCode: 500
});
}
}
}
/**
* Controller to log the user in
* @param req Express Request
* @param res Express Response
*/
function async loginController(req:Express.Request, res:Express.Response) {
// verify parameters
if(!(req.body['username'] && req.body['password'])){
return res.status(400).end("Please include username and password");
}
var user = await Auth.login(req.body['username'], req.body['password']);
if (user) {
var authToken = Auth.generateAuthToken(user);
res.json({
authToken:authToken
});
} else {
return res.status(401).end("Wrong username or password");
}
}
var app = Express();
app.post('/api/login', $(loginController));
app.listen(8080);
</code></pre>
<pre><code>// Auth.ts
import { User } from './User';
/**
* Authentication base class
*/
export class Auth {
/**
* Log user in
* @param email
* @param password
* @returns user logged in. Returns null if user is not found or authentication fails
*/
public static async login(email:string, password:string):Promise<User> {
var response = await fetch("example.com/api/login", {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: email
password: password
})
});
if(response.ok){
return await response.json() as User;
}
// password or username was wrong
if(response.status == 401){
return null;
}
// an unknown error occurred
throw Error(response.status);
}
/**
* Generate AuthToken
* @param user
* @return token
*/
public static generateAuthToken(user:User):string {
return jwt.sign({ userid: user.id }, process.env.SECRET, {
expiresIn: process.env.JWT_EXPIRY
});
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T18:35:12.747",
"Id": "498188",
"Score": "1",
"body": "Personally, I'd prefer just augmenting Express itself to handle rejected promises returned from request handlers as shown here: [Async/await in Express Route Handlers](https://stackoverflow.com/questions/61086833/async-await-in-express-middleware/61087195#61087195)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T19:06:09.290",
"Id": "498190",
"Score": "0",
"body": "I'm not sure what the concern is. Using `.getP()` doesn't ever lead to an unexpected application crash. And, for someone who adds to this project and just uses `.get()` they have exactly the same requirement they do today (they have to catch their own rejections). So, you're just adding an option that, if used, saves you from having to catch all your own rejections. It's purely additive. And, this won't be the first convention or feature you add to your project that anyone maintaining it should know about."
}
] |
[
{
"body": "<p>First of all, by default ExpressJS does not support async routes. To solve that you can use <a href=\"https://www.npmjs.com/package/express-async-errors\" rel=\"nofollow noreferrer\">express-async-errors</a> plugin. Just add the following at the beginning of the file:</p>\n<pre class=\"lang-js prettyprint-override\"><code>import 'express-async-errors'\n</code></pre>\n<p>Now ExpressJS will await promises and handle promise rejections. Then you can create custom errors handler:</p>\n<pre><code>export function handleApiErrors(): (err: unknown, req: Request, resp: Response, next: NextFunction) => unknown {\n return (err, _req, resp, next) => {\n if (err) {\n console.error(String(err))\n return resp.status(500).json({\n error: 'unknown error',\n })\n }\n next(err)\n }\n}\n</code></pre>\n<p>Then include custom error handler just before <code>app.listen</code>:</p>\n<pre><code>app.use(handleApiErrors())\n</code></pre>\n<blockquote>\n<p>Now each route can return a promise and rejected promises will be returned as <code>500</code> response. You can also include <a href=\"https://www.npmjs.com/package/http-errors\" rel=\"nofollow noreferrer\">http-errors</a> to further improve error handling.</p>\n</blockquote>\n<p>You can check the live example on <a href=\"https://github.com/KiraLT/torrent-stream-server/blob/master/src/app.ts\" rel=\"nofollow noreferrer\">torrent-stream-server</a></p>\n<hr />\n<h2>Other observations</h2>\n<h3>null return</h3>\n<p><code>login</code> has <code>Promise<User></code> type, but you return null. If you don't get typescript error, you should consider enabling <a href=\"https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#--strictnullchecks\" rel=\"nofollow noreferrer\">strictNullChecks</a> option.</p>\n<h3>res.end and res.json</h3>\n<p>You mix <code>res.json</code> with <code>res.end</code>. Maybe some middleware handles, that <code>res.end</code> would return JSON. Or maybe you just return plain text response on error? In any case, it's confusing, so you should always use <code>res.json()</code> (you can chain it with end if you like, but I don't see a reason).</p>\n<h3>No spaces</h3>\n<p>I see that you don't like spaces. But it's hard to read with that style. You should at least add spaces after <code>:</code>. You should find a styleguide you like and follow it. Or you can just use <a href=\"https://prettier.io/\" rel=\"nofollow noreferrer\">prettier</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-30T15:55:47.660",
"Id": "498374",
"Score": "0",
"body": "Thanks! I've never noticed the space after the colon. I went back to a the typescript documentation and sure enough, spaces everywhere. As for res.end and res.json, I use res.end to send the plaintext error back. Does it make sense to do this with .json()? I figured it would look odd to write res.json(\"Text error description\")."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-30T16:21:53.187",
"Id": "498376",
"Score": "1",
"body": "You shouldn't mix response types. If you have JSON API, return JSON for errors too. Otherwise is hard to parse your API response correctly."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T13:49:29.953",
"Id": "252824",
"ParentId": "252760",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "252824",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T16:34:21.077",
"Id": "252760",
"Score": "4",
"Tags": [
"javascript",
"node.js",
"typescript",
"async-await",
"express.js"
],
"Title": "Catching Errors in Factory Method with express.js"
}
|
252760
|
<p>I've been tinkering with python for quite a while but have never taken on a challenge like this - I'm trying to write a collectd plugin to scrape metrics from prometheus endpoints.</p>
<p>My goals are to make it as stable as possible - i'd like to put this into production when i am happy with it. There are a couple of items that i haven't figured out yet (summary and histogram familytypes), so if anyone has any suggestions about how to do that, i would be very appreciative. As well as this, i am trying to be a pythonic as possible, but i am 100% self taught, so my code is probably all over the place.</p>
<p>I'm interested in any form of feedback, even if it means i need to go learn/un-learm some more stuff :)</p>
<pre><code>import platform
import collectd
from prometheus_client.parser import text_string_to_metric_families
import requests
def config_func(config):
endpoint_set = False
endpoint_set = False
interval = 60
for node in config.children:
key = node.key.lower()
val = node.values[0]
if key.lower() == 'endpoint':
endpoint = val
endpoint_set = True
elif key.lower() == 'endpoint_name':
endpoint_name = val
endpoint_name_set = True
elif key.lower() == 'interval':
interval = val
else:
collectd.info(f'prometheus_scraper: Unknown config key "{key}"')
if endpoint_set and endpoint_name_set:
collectd.info(f'prometheus_scraper: python version {platform.python_version()}')
collectd.info(f'prometheus_scraper: Using {endpoint} for {endpoint_name} on ')
global ENDPOINT
ENDPOINT = endpoint
global ENDPOINT_NAME
ENDPOINT_NAME = endpoint_name
global INTERVAL
INTERVAL = interval
def parse_func(metrics):
for family in text_string_to_metric_families(metrics):
for sample in family.samples:
if family.type == 'summary':
#print(family.type)
pass
elif family.type == 'histogram':
#print(family.type)
pass
else:
val = collectd.Values()
val.plugin = ENDPOINT_NAME
val.interval = INTERVAL
val.type = family.type
if len(sample.labels) > 0:
joined = ''.join(key + '_' + str(val) for key, val in sample.labels.items())
val.type_instance = sample.name + '.' + joined
else:
val.type_instance = sample.name
#print(f'type_instance: {val.type_instance}')
val.values = [sample.value]
val.dispatch()
def read_func():
try:
metrics = requests.get(url=ENDPOINT)
metrics.raise_for_status()
parse_func(metrics.text)
except requests.exceptions.RequestException as e:
collectd.error(f'failed to retrive metrics: {e}')
collectd.register_config(config_func)
collectd.register_read(read_func, INTERVAL)
</code></pre>
<blockquote>
<p><a href="https://github.com/mark-vandenbos/collectd_prometheus_scraper/" rel="nofollow noreferrer">https://github.com/mark-vandenbos/collectd_prometheus_scraper/</a></p>
</blockquote>
|
[] |
[
{
"body": "<p>I can't test this code, so I will only make a few general remarks for the time being.</p>\n<p>I was curious, since I actually started working on the Prometheus API yesterday, because I was asked to design a monitoring dashboard.</p>\n<hr />\n<p>This code is un-Pythonic:</p>\n<pre><code> global ENDPOINT\n ENDPOINT = endpoint\n global ENDPOINT_NAME\n ENDPOINT_NAME = endpoint_name\n global INTERVAL\n INTERVAL = interval\n</code></pre>\n<p>Assigning a variable to another variable like this: <code>ENDPOINT = endpoint</code> has no added value and is even confusing. All this is redundant.</p>\n<p>Global variables are frowned upon, because they are seldom necessary in fact. There usually is a better way. Just pass the variables along to your functions and retrieve resulting values as necessary.</p>\n<p>If you have <strong>constants</strong>, define them at the top of your code (if you have just one file), or put them in a separate config file.\nI suggest that you create a config.py file, and move all your constants there. Then you import the file:</p>\n<pre><code>import config\n</code></pre>\n<p>And you can refer to your constants like this all across your code:</p>\n<pre><code>config.ENDPOINT\n</code></pre>\n<p><a href=\"https://docs.python.org/3/faq/programming.html#how-do-i-share-global-variables-across-modules\" rel=\"nofollow noreferrer\">Source</a> and there are more useful tips too. This is recommended reading for beginners and more experienced programmers as well.</p>\n<hr />\n<p>You have this code:</p>\n<pre><code> if family.type == 'summary':\n #print(family.type)\n pass\n elif family.type == 'histogram':\n #print(family.type)\n pass\n else:\n</code></pre>\n<p>pass is no operation (NOP). So you have code that does strictly nothing and should be removed. What you want is probably something like this:</p>\n<pre><code>if family.type not in ('summary', 'histogram'):\n</code></pre>\n<hr />\n<p>You have 3 functions: <code>config_func</code>, <code>parse_func</code>, <code>read_func</code>. It's obvious they are functions, so the _func suffix is superfluous. But the names are not descriptive enough. It doesn't tell me what you are reading or parsing. So I think your <strong>naming conventions</strong> should be revisited.</p>\n<p>In a way I think the order of things is logical: configuration, reading results, parsing results. Gotta make it more obvious.</p>\n<hr />\n<p>Something that is lacking badly: <strong>comments</strong>. They are not just for external reviewers but for your benefit too. After a while you will forget stuff and you will have to re-analyze your own code to figure out the flow and what kind of data is returned by a given function. I would recommended that you document each function with a docstring. 2-3 lines will do.</p>\n<p>Document your functions, and describe what kind of data you are manipulating. When you have some ifs and are testing for a specific condition, it does not hurt to explain why in a comment, unless the purpose of the test is very obvious.</p>\n<p>Since you put your code on Github there is an expectation that somebody else might want to download it, use it, possibly fork it. But then it is important to provide enough <strong>documentation</strong>. Lack of documentation can be forgiven for software that works straight out of the box without any configuration, but this is rare.</p>\n<hr />\n<p>Quality control: in config_func (at the top of your code) you have repeated code:</p>\n<pre><code>endpoint_set = False\nendpoint_set = False\n</code></pre>\n<p>A good IDE would help you spot those mistakes and also enforce PEP8 rules. In a job interview this would qualify as lack of attention to detail, just by proof-reading your code carefully you should have noticed :)</p>\n<hr />\n<p>In a Python program it is customary to have a main method and use <code>__main__</code> like this:</p>\n<pre><code>if __name__ == '__main__':\n collectd.register_config(config_func)\n collectd.register_read(read_func, INTERVAL)\n</code></pre>\n<p>Or better yet:</p>\n<pre><code>if __name__ == '__main__':\n main()\n</code></pre>\n<p>And put your launcher code in the main function. The benefit of doing so is that you can import your package (to reuse some functions) without actually launching it.</p>\n<hr />\n<p>Now that I am reading what I wrote so far I realize that it's not very helpful. I only gave you general suggestions but I think they are still useful though. But I am kinda frustrated because you have not described what the finished product does look like. After reading your code I can't really figure it out. I don't have a Prometheus box handy so I can't run your code and pull out some data.</p>\n<p>The code is quite short (< 100 lines) and yet it is obscure to me. I don't think it's only because I am Prometheus newbie. The code does not speak for itself. Comments would help make more sense of the overall approach.</p>\n<p>I am not familiar with collectd so I can't comment much on that. I understand you are scraping metrics but what is the ultimate goal, how will the data be used, that's what is interesting.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-28T18:57:57.937",
"Id": "252792",
"ParentId": "252761",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T16:35:54.743",
"Id": "252761",
"Score": "4",
"Tags": [
"python",
"web-scraping"
],
"Title": "python collectd prometheus scraper"
}
|
252761
|
<p>I'm trying to write a minor lib that would enable me to measure average time measured when using <code>struct timespec</code>. Since C doesn't allow operator overloading, I'm forced to build functions. I am aware that checks like <code>end_time < start_time</code> are not done, but I've left them out to achieve some kind of shortness in the code. The accuracy of the calculations is primary goal.</p>
<pre><code>enum { NS_PER_SECOND = 1000000000L };
enum { MAX_NS = 999999999 };
// t1 --> start time
// t2 --> end time
// set t1 and t2 by:
// clock_gettime(CLOCK_REALTIME, &t1);
struct timespec get_timespec_diff(const struct timespec t1, const struct timespec t2)
{
struct timespec t;
t.tv_nsec = t2.tv_nsec - t1.tv_nsec;
t.tv_sec = t2.tv_sec - t1.tv_sec;
if (t.tv_sec > 0 && t.tv_nsec < 0) {
t.tv_nsec += NS_PER_SECOND;
t.tv_sec--;
} else if (t.tv_sec < 0 && t.tv_nsec > 0) {
t.tv_nsec -= NS_PER_SECOND;
t.tv_sec++;
}
return t;
}
struct timespec timespec_add(const struct timespec t1, const struct timespec t2) {
unsigned int total_ns = t1.tv_nsec + t2.tv_nsec;
unsigned int total_s = t1.tv_sec + t2.tv_sec;
while(total_ns > MAX_NS) {
total_ns -= (unsigned)(MAX_NS + 1);
total_s++;
}
struct timespec ret;
ret.tv_sec = total_s;
ret.tv_nsec = total_ns;
return ret;
}
struct timespec timespec_avg(const struct timespec t, const unsigned n) {
struct timespec ret;
ret.tv_sec = 0;
ret.tv_nsec = 0;
unsigned int total_ns = t.tv_nsec + (t.tv_sec * (MAX_NS+1));
unsigned int avg_ns = total_ns/n;
while(avg_ns > MAX_NS) {
ret.tv_sec++;
avg_ns /= 10;
}
ret.tv_nsec = avg_ns;
return ret;
}
</code></pre>
|
[] |
[
{
"body": "<p>You need to <code>#include <time.h></code> for <code>struct timespec</code> to be defined.</p>\n<hr />\n<p>Why are <code>NS_PER_SECOND</code> and <code>MAX_NS</code> enum members? There's no advantage compared to plain old <code>const long</code>. I'm not sure why we need two constants anyway; the code that uses <code>MAX_NS</code> is simplified if we use <code>NS_PER_SECOND</code> instead:</p>\n<pre><code>long total_ns = t1.tv_nsec + t2.tv_nsec;\ntime_t total_s = t1.tv_sec + t2.tv_sec;\n\nwhile (total_ns >= NS_PER_SECOND) {\n total_ns -= NS_PER_SECOND;\n ++total_s;\n}\n</code></pre>\n<p>(Note the use of the correct types in this version).</p>\n<hr />\n<p>I think this logic is wrong:</p>\n<pre><code>if (t.tv_sec > 0 && t.tv_nsec < 0) {\n t.tv_nsec += NS_PER_SECOND;\n t.tv_sec--;\n} else if (t.tv_sec < 0 && t.tv_nsec > 0) {\n t.tv_nsec -= NS_PER_SECOND;\n t.tv_sec++;\n}\n</code></pre>\n<p>I'm reasonably sure that <code>tv_nsec</code> should always be positive, even when <code>tv_sec</code> is negative. So we can simplify that to just:</p>\n<pre><code>if (t.tv_nsec < 0) {\n t.tv_nsec += NS_PER_SECOND;\n t.tv_sec--;\n}\n</code></pre>\n<p>Note that the logic in <code>timespec_add()</code> already assumes positive <code>tv_nsec</code>.</p>\n<hr />\n<p>This is highly susceptible to overflow:</p>\n<pre><code>unsigned int total_ns = t.tv_nsec + (t.tv_sec * (MAX_NS+1));\n</code></pre>\n<p>The whole reason we have <code>struct timespec</code> is that we might need to represent values outside the range of the integer types. Probably better to use <code>divmod</code> to divide <code>tv_nsec</code> by <code>n</code>, and add the remainder to <code>nsec</code> before dividing - we need to be very careful here to avoid overflow. Again, an unsigned type is inconsistent with other code.</p>\n<h1>Modified code</h1>\n<p>Here's my version of these functions:</p>\n<pre><code>#include <time.h>\n\nconst long NS_PER_SECOND = 1000000000L;\n\nstruct timespec timespec_sub(const struct timespec t1, const struct timespec t2)\n{\n struct timespec t;\n\n t.tv_nsec = t2.tv_nsec - t1.tv_nsec;\n t.tv_sec = t2.tv_sec - t1.tv_sec;\n\n if (t.tv_nsec < 0) {\n t.tv_nsec += NS_PER_SECOND;\n t.tv_sec--;\n }\n return t;\n}\n\nstruct timespec timespec_add(const struct timespec t1, const struct timespec t2)\n{\n struct timespec t = { t1.tv_sec + t2.tv_sec, t1.tv_nsec + t2.tv_nsec };\n if (t.tv_nsec >= NS_PER_SECOND) {\n t.tv_nsec -= NS_PER_SECOND;\n t.tv_sec++;\n }\n return t;\n}\n\nstruct timespec timespec_divide(struct timespec t, const int n)\n{\n time_t remainder_secs = t.tv_sec % n;\n t.tv_sec /= n;\n t.tv_nsec /= n;\n t.tv_nsec +=\n remainder_secs * (NS_PER_SECOND / n) +\n remainder_secs * (NS_PER_SECOND % n) / n;\n\n while (t.tv_nsec >= NS_PER_SECOND) {\n t.tv_nsec -= NS_PER_SECOND;\n t.tv_sec++;\n }\n return t;\n}\n</code></pre>\n<p>And a primitive unit-test:</p>\n<pre><code>int main(void)\n{\n const struct timespec a = { 1, 905234817 };\n struct timespec a_2 = timespec_add(a, a);\n struct timespec a_4 = timespec_add(a_2, a_2);\n struct timespec a_5 = timespec_add(a_4, a);\n struct timespec z = timespec_sub(a, timespec_divide(a_5, 5));\n return z.tv_sec || z.tv_nsec;\n}\n</code></pre>\n<p>You should expand on the testing, to prove correctness for the tricky cases where overflow could happen.</p>\n<hr />\n<h1>Further simplification</h1>\n<p>We can separate out the code to normalise out-of-range nanoseconds into its own function:</p>\n<pre><code>struct timespec timespec_normalise(struct timespec t)\n{\n t.tv_sec += t.tv_nsec / NS_PER_SECOND;\n if ((t.tv_nsec %= NS_PER_SECOND) < 0) {\n /* division rounds towards zero, since C99 */\n t.tv_nsec += NS_PER_SECOND;\n --t.tv_sec;\n }\n return t;\n}\n</code></pre>\n<p>Then the functions can use that, to make them shorter and simpler:</p>\n<pre><code>struct timespec timespec_sub(const struct timespec t1, const struct timespec t2)\n{\n struct timespec t = { t2.tv_nsec - t1.tv_nsec, t2.tv_sec - t1.tv_sec };\n return timespec_normalise(t);\n}\n\nstruct timespec timespec_add(const struct timespec t1, const struct timespec t2)\n{\n struct timespec t = { t1.tv_sec + t2.tv_sec, t1.tv_nsec + t2.tv_nsec };\n return timespec_normalise(t);\n}\n\nstruct timespec timespec_divide(struct timespec t, const int n)\n{\n time_t remainder_secs = t.tv_sec % n;\n t.tv_sec /= n;\n t.tv_nsec /= n;\n t.tv_nsec +=\n remainder_secs * (NS_PER_SECOND / n) +\n remainder_secs * (NS_PER_SECOND % n) / n;\n return timespec_normalise(t);\n}\n</code></pre>\n<p>Because we have the unit tests, we have high confidence that we haven't affected the functionality here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T13:07:02.500",
"Id": "498294",
"Score": "1",
"body": "`timespec_divide()` has problems. `time_t` may be floating point so `t.tv_sec % n` does not certainly compile. `remainder_secs * (NS_PER_SECOND % n)` subject to integer overflow when `n > LONG_MAX/n`. When `n < 0`, additional issues."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T22:35:01.560",
"Id": "498335",
"Score": "0",
"body": "I had thought that `time_t` needed to be integer; forgotten that wasn't required. Yes, the divide still has problems; thanks for showing that. Unfortunately no time to fix that now (it's good to show how tricky this stuff can be!)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-30T11:03:37.830",
"Id": "498365",
"Score": "0",
"body": "The problems with larger `n` could probably help inform some additional unit tests..."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T19:23:20.957",
"Id": "252768",
"ParentId": "252762",
"Score": "4"
}
},
{
"body": "<p><strong><code>time_t</code> assumptions, not specifications</strong></p>\n<p>OP's code assumes 1) <code>time_t</code> is an integer type. It could be floating point. 2) <code>unsigned/int</code> are not 16-bit - they could be.</p>\n<p>Writing portable time code is difficult due to #1. Rest of answer will assume #1.</p>\n<p><strong><em>normal range</em></strong></p>\n<p>The normal ranges are <code>.tv_sec >= 0</code> and <code>0 <= .tv_nsec <= 999999999</code>. Useful is code does not rely on that too much.</p>\n<p><strong>Overflow risk</strong></p>\n<p>In <code>timespec_add()</code>, <code>t1.tv_sec + t2.tv_sec</code> risks overflow and thus <em>undefined behavior</em>.</p>\n<p><code>unsigned int total_ns = t1.tv_nsec + t2.tv_nsec;</code> can readily fail to provide correct results when <code>unsigned</code> is 16-bit - best to use <code>long</code>.</p>\n<hr />\n<p><strong>Strange name</strong></p>\n<p><code>timespec_avg(const struct timespec t, const unsigned n)</code> looks more like a divide than an average of time.</p>\n<p>Alternate suggestion:</p>\n<pre><code>#include <time.h>\n#define NS_PER_SECOND 1000000000\n\n// Averaging without overflow, even if `t1,t2` outside normal range\nstruct timespec timespec_avg(struct timespec t1, struct timespec t2) {\n struct timespec avg;\n int remainder = t1.tv_sec % 2 + t2.tv_sec % 2;\n avg.tv_sec = t1.tv_sec / 2 + t1.tv_sec / 2;\n avg.tv_nsec = t1.tv_nsec / 2 + t1.tv_nsec / 2 + (t1.tv_nsec % 2 + t1.tv_nsec % 2) / 2;\n avg.tv_sec += avg.tv_nsec / NS_PER_SECOND;\n avg.tv_nsec = avg.tv_nsec % NS_PER_SECOND + (NS_PER_SECOND / 2 * remainder);\n if (avg.tv_nsec >= NS_PER_SECOND) {\n avg.tv_nsec -= NS_PER_SECOND;\n avg.tv_sec++;\n } else if (avg.tv_nsec < 0) {\n avg.tv_nsec += NS_PER_SECOND;\n avg.tv_sec--;\n }\n return avg;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T16:00:14.063",
"Id": "252828",
"ParentId": "252762",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T17:07:04.947",
"Id": "252762",
"Score": "3",
"Tags": [
"c",
"overloading"
],
"Title": "C: struct timespec library"
}
|
252762
|
<p>I created a JS script for a friend's website to allow the visitors to choose the date and time of their delivery.</p>
<p>I'm new in web-development and I will appreciate a feedback from professionals like you.</p>
<p>The script doesn't have an UI at the moment ,so for settings just need to change the <code>shippingDateTime</code>.</p>
<p>The script automatically add to an html form the elements needed so I think should be usable on every project</p>
<p>I will post the code below , for a live demo you can see <a href="https://shipping-helper.netlify.app/" rel="nofollow noreferrer">here</a> or a <a href="https://github.com/cristiangiro/shipping-helper" rel="nofollow noreferrer">Github</a> for a full code</p>
<p>Thanks</p>
<pre><code>"use strict";
const container = document.querySelector(".cart");
const checkoutButton = document.querySelector(".btn.cart__checkout");
const defaultOption = "-Choose an option-";
const disableCheckoutButton = true;
const daysOffRisp = "No delivery this date";
const shippingDateTime = [
[
"Delivery",
{
delayD: 0,
timeSlots: [
[12, 13],
[13, 15],
[18.15, 19],
[22, 23],
[23, 24],
],
lastOrder: 19,
daysOff: ["2020-12-31"],
delayH: 1,
},
],
[
"Pick-up",
{
delayD: 0,
delayH: 1,
timeSlots: 3,
startTime: 12.0,
endTime: 23.0,
lastOrder: 22,
daysOff: [2, 3],
},
],
];
//////// End settings
let dateValid = undefined;
let timeValid = undefined;
let deliveryMetValid = undefined;
let deliveryMethods = "";
checkoutButton.insertAdjacentHTML(
"beforebegin",
`<div class="btn newbutton" style="display:none">${checkoutButton.innerHTML}</div>`
);
const newButton = document.querySelector(".newbutton");
//if disableCheckoutButton is set to true
function f_disabledCheckout() {
function sostituteButton(b) {
if (b === "newB") {
newButton.style.display = "inline-block";
checkoutButton.style.display = "none";
} else if (b === "oldB") {
newButton.style.display = "none";
checkoutButton.style.display = "inline-block";
}
}
if (!disableCheckoutButton) {
return;
} else if (disableCheckoutButton && dateValid && timeValid) {
sostituteButton("oldB");
} else {
sostituteButton("newB");
newButton.addEventListener("click", function () {
function animate(element) {
element.classList.add("attention");
element.addEventListener("animationend", (e) =>
e.target.classList.remove("attention")
);
}
if (dateValid != true) animate(datePicker);
if (timeValid != true) animate(input);
if (deliveryMetValid != true) animate(instancesDeliveryMethods);
});
}
}
f_disabledCheckout();
//generate one shipping button foreach shipping method available
for (const methods of shippingDateTime)
deliveryMethods += `<label class="radiobutton deliverymethods" for="${methods[0]}">
<input class="radio" type="radio" id="${methods[0]}" name="Method" value="${methods[0]}">${methods[0]}</label>`;
//attach all the elements to the main div
container.insertAdjacentHTML(
"afterbegin",
` <div class="ext">
<label class="caption">Delivery method</label>
<div class="container_deliverymethods">
${deliveryMethods}
</div>
</div>
<div class="ext ext-datepicker" style="visibility:hidden">
<label class="caption">Delivery date</label>
<div><input type="date" class="datepicker-btn" min="" required ><span class="validate"></span></div>
<input type="text" class="converteddate" name="Date" style="display:none">
</div>
<div class="ext ext-input" style="visibility:hidden">
<label class="caption">Delivery time</label>
<input list="" id="input-datalist" autocomplete="off" name="Time" value="${defaultOption}">
</div>
<datalist id="datalist">
</datalist>
`
);
//reset hidden elemnts
function f_reset(el) {
if (el === "datepick") {
extInput.style.visibility = "hidden";
validator.className = "validate";
datePicker.value = "";
dateValid = false;
f_disabledCheckout();
}
if (el === "datepick" || el === "timeslot") {
extInput.style.visibility = "hidden";
timeValid = false;
f_disabledCheckout();
}
if (el === "datepick" || el === "timeslot" || el === "datalist") {
datalist.style.display = "none";
f_disabledCheckout();
}
}
// convert in ms
function f_ms(d = 0, h = 0, m = 0) {
h += Number((d % 1).toFixed(4).substring(2));
m += Number((h % 1).toFixed(4).substring(2));
const result = d * 24 * 60 * 60 * 1000 + h * 60 * 60 * 1000 + m * 60 * 1000;
return result;
}
//listen for click on delivery methos
const instancesDeliveryMethods = document.querySelector(
".container_deliverymethods"
);
const validator = document.querySelector(".validate");
let choosenDeliveryM = "";
function checkDeliveryMethods(e) {
validator.className = "validate";
deliveryMetValid = true;
choosenDeliveryM = e.target.value;
f_reset("datepick");
showDatePicker(e.target.value);
}
instancesDeliveryMethods.addEventListener("change", checkDeliveryMethods);
//calculate first availabe date
let addNDay = 0;
function showDatePicker(deliveryvalue) {
addNDay = 0;
for (const dv of shippingDateTime) {
if (dv[0] === deliveryvalue) {
const deliveryOptions = dv[1];
const timeslot = deliveryOptions.timeSlots;
const delayH = f_ms(0, deliveryOptions.delayH);
if (
typeof timeslot == "number" &&
f_ms(0, deliveryOptions.endTime) < now + delayH + f_ms(0, timeslot)
) {
addNDay = 1;
}
if (
typeof timeslot == "object" &&
f_ms(0, timeslot[timeslot.length - 1][0]) < now + delayH
) {
addNDay = 1;
}
now > f_ms(0, deliveryOptions.lastOrder) ? (addNDay = 2) : "";
deliveryOptions.delayD ? (addNDay = deliveryOptions.delayD) : "";
dateMin(addNDay);
return;
}
}
}
const datePicker = document.querySelector(".datepicker-btn");
const extDatePicker = document.querySelector(".ext-datepicker");
const day = new Date();
day.setHours(0, 0, 0, 0);
const today = day.getTime();
console.log(today);
const nowraw = new Date();
const hours = nowraw.getHours();
const minutes = nowraw.getMinutes();
const now = f_ms(0, hours) + f_ms(0, 0, minutes);
//set min value of the datePicker
let min = new Date();
function dateMin(minDelay) {
f_reset("datepick");
min.setTime(today + f_ms(minDelay));
if (jqui === true) {
$(".datepicker-btn").datepicker("option", "minDate", minDelay);
} else {
datePicker.min = min.toISOString().slice(0, 10);
}
extDatePicker.style.visibility = "visible";
}
// listen for change in date picker
function setDeliverSlots() {
const dateFromDPraw = new Date(datePicker.value);
dateFromDPraw.setHours(0, 0, 0, 0);
const dateFromDP = dateFromDPraw.getTime();
let optiontimeSlotsValues = [];
input.value = defaultOption;
if (dateFromDP >= min) {
validator.className = "validate y";
document.querySelector(".converteddate").value =
dateFromDPraw.getDate() +
"-" +
(dateFromDPraw.getMonth() + 1) +
"-" +
dateFromDPraw.getFullYear();
dateValid = true;
for (const deliveryMetAv of shippingDateTime) {
const deliveryMetName = deliveryMetAv[0];
const deliveryMetSlots = deliveryMetAv[1].timeSlots;
const delayD = f_ms(deliveryMetAv[1].delayD);
const delayH = f_ms(0, deliveryMetAv[1].delayH);
const daysOff = deliveryMetAv[1].daysOff;
const deliveryMetEndTime = f_ms(0, deliveryMetAv[1].endTime);
const deliveryMetStartTime = f_ms(0, deliveryMetAv[1].startTime);
if (deliveryMetName === choosenDeliveryM) {
if (daysOff.includes(7)) {
daysOff.splice(daysOff.indexOf(7), 1, 0);
}
if (
daysOff.includes(dateFromDPraw.getDay()) ||
daysOff.includes(datePicker.value)
) {
input.value = daysOffRisp;
extInput.style.visibility = "visible";
dateValid = false;
datalist.innerHTML = "";
validator.className = "validate n";
f_disabledCheckout();
return;
}
if (
typeof deliveryMetSlots == "object" //if timeslot is an array
) {
for (const slot of deliveryMetSlots) {
const startS = f_ms(0, slot[0]);
const endS = f_ms(0, slot[1]);
if (
(dateFromDP >= min && dateFromDP != today) ||
(dateFromDP == today && now < endS + delayH)
) {
optiontimeSlotsValues.push(slot);
}
}
} else if (
typeof deliveryMetSlots == "number" //if timeslot is a number
) {
const slotDuration = f_ms(0, deliveryMetAv[1].timeSlots);
let currentSlot = deliveryMetStartTime;
while (deliveryMetEndTime >= currentSlot + delayH) {
if (dateFromDP == today && currentSlot >= now + delayH) {
optiontimeSlotsValues.push([
currentSlot / 60 / 60 / 1000,
(currentSlot + slotDuration) / 60 / 60 / 1000,
]);
} else if (dateFromDP !== today && dateFromDP >= min) {
optiontimeSlotsValues.push([
currentSlot / 60 / 60 / 1000,
(currentSlot + slotDuration) / 60 / 60 / 1000,
]);
}
currentSlot += slotDuration;
}
}
}
if (optiontimeSlotsValues != "") {
let optionstimeSlots = ``;
optiontimeSlotsValues.forEach(function (element) {
let [el1, el2] = [...element];
function convert(el) {
el = el.toString();
if (el.includes(".")) {
el = el.replace(".", ":").padEnd(5, "0");
} else {
el += ":00";
}
return el;
}
element = convert(el1) + "-" + convert(el2);
optionstimeSlots += `<option class="btn datalist-options" value="${element}">${element}</option>`;
});
datalist.innerHTML = optionstimeSlots;
extInput.style.visibility = "visible";
}
}
} else {
validator.className = "validate n";
dateValid = false;
f_reset("timeslot");
}
f_disabledCheckout();
}
datePicker.addEventListener("input", setDeliverSlots);
//datalist
const input = document.querySelector("#input-datalist");
const extInput = document.querySelector(".ext-input");
const datalist = document.querySelector("#datalist");
input.addEventListener("focus", () => (datalist.style.display = "block"));
datalist.addEventListener("click", function (e) {
input.value = e.target.value;
f_reset("datalist");
checkTime();
});
datalist.style.width = input.offsetWidth + "px";
datalist.style.left = input.offsetLeft + "px";
datalist.style.top = input.offsetTop + input.offsetHeight + "px";
// validate time
function checkTime() {
timeValid = false;
const datalistOptions = document.querySelectorAll(".datalist-options");
datalistOptions.forEach((element) => {
if (element.value === input.value && element.value != "") {
timeValid = true;
}
});
f_disabledCheckout();
}
input.addEventListener("change", checkTime);
//close datalist if clicked somewhere outside the datalist
document.querySelector("body").addEventListener("click", (e) => {
if (e.target != input && e.target.className != "datalist-options")
f_reset("datalist");
});
//if browser not support input date load jquery data picker
let jqui;
if (datePicker.type === "text") {
jqui = true;
const jq = document.createElement("script");
jq.src = "https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.5.1.min.js";
const jui = document.createElement("script");
jui.src = "https://ajax.aspnetcdn.com/ajax/jquery.ui/1.10.4/jquery-ui.min.js";
const css = document.createElement("link");
css.href =
"https://ajax.aspnetcdn.com/ajax/jquery.ui/1.10.4/themes/ui-lightness/jquery-ui.css";
css.type = "text/css";
css.rel = "stylesheet";
const head = document.head || document.getElementsByTagName("head")[0];
head.appendChild(jq);
jq.addEventListener("load", function () {
head.appendChild(jui);
jui.addEventListener("load", function () {
head.appendChild(css);
css.addEventListener("load", function () {
if (window.jQuery) {
$(".datepicker-btn").datepicker({
altField: ".converteddate",
altFormat: "dd-mm-yy",
});
$(".datepicker-btn").on("change", setDeliverSlots);
} else {
alert(
"Something went wrong ,please try reloading the browser or try with a different one "
);
}
});
});
});
}
//collect the data (optional)
const datalog = document.querySelector(".datalog");
checkoutButton.addEventListener("click", (e) => {
// e.preventDefault();
let selectedValue;
function check() {
const rbs = document.querySelectorAll('input[name="Method"]');
for (const rb of rbs) {
if (rb.checked) {
selectedValue = rb.value;
break;
}
}
}
check();
datalog.value = `Method:${selectedValue} | Date${
document.querySelector(".converteddate").value
} | Time${input.value}`;
f_reset("datepick");
});
</code></pre>
|
[] |
[
{
"body": "<p>You can Shorten the script a fair bit by creating a few helper functions at the begining of the file, shortening a few variable names & removing unecessary redeclarations of var, let and const.. Javascript allows you to chain these as long as they have a comma after each one and the last one still has a semi-colon i've edited the script you provided and included it below.\nthe idea of the helper functions is basically anywhere where your writing out <code>document.getElementById or querySelector()</code> on multiple lines you can just replace this with the shortened function name<br />\nsuch as <code>qS(), qSAll(), getId(), getTag(), getClass() or createElem();</code>\nalso shortened input to just inp & the animation function name to anime().</p>\n<pre><code>"use strict";\n let UN = undefined;\n let qS=(s)=>{\n return document.querySelector(s)\n },\n getTag=(tg)=>{\n return document.getElementsByTagName(tg)\n },\n createElem=(elem)=>{\n return document.createElement(elem)\n };\n\nconst container = qS(".cart"),\n checkoutButton = qS(".btn.cart__checkout"),\n defaultOption = "-Choose an option-",\n disableCheckoutButton = true,\n daysOffRisp = "No delivery this date",\n shippingDateTime = [\n [\n "Delivery",\n {\n delayD: 0,\n timeSlots: [\n [12, 13],\n [13, 15],\n [18.15, 19],\n [22, 23],\n [23, 24],\n ],\n lastOrder: 19,\n daysOff: ["2020-12-31"],\n delayH: 1,\n },\n ],\n [\n "Pick-up",\n {\n delayD: 0,\n delayH: 1,\n timeSlots: 3,\n startTime: 12.0,\n endTime: 23.0,\n lastOrder: 22,\n daysOff: [2, 3],\n },\n ],\n];\n\n//////// End settings\n\nlet dateValid = UN,\n timeValid = UN,\n deliveryMetValid = UN,\n deliveryMethods = "";\ncheckoutButton.insertAdjacentHTML(\n "beforebegin",\n `<div class="btn newbutton" style="display:none">${checkoutButton.innerHTML}</div>`\n);\nconst newButton = qS(".newbutton");\n\n//if disableCheckoutButton is set to true\nfunction f_disabledCheckout() {\n function sostituteButton(b) {\n if (b === "newB") {\n newButton.style.display = "inline-block";\n checkoutButton.style.display = "none";\n } else if (b === "oldB") {\n newButton.style.display = "none";\n checkoutButton.style.display = "inline-block";\n }\n }\n\n if (!disableCheckoutButton) {\n return;\n } else if (disableCheckoutButton && dateValid && timeValid) {\n sostituteButton("oldB");\n } else {\n sostituteButton("newB");\n\n newButton.addEventListener("click", function () {\n function anime(el) {\n el.classList.add("attention");\n el.addEventListener("animationend", (e) =>\n e.target.classList.remove("attention")\n );\n }\n\n if (dateValid != true) anime(datePicker);\n if (timeValid != true) anime(inp);\n if (deliveryMetValid != true) anime(instancesDeliveryMethods);\n });\n }\n}\nf_disabledCheckout();\n\n//generate one shipping button foreach shipping method available\nfor (const methods of shippingDateTime)\n deliveryMethods += `<label class="radiobutton deliverymethods" for="${methods[0]}">\n <input class="radio" type="radio" id="${methods[0]}" name="Method" value="${methods[0]}">${methods[0]}</label>`;\n\n//attach all the elements to the main div\ncontainer.insertAdjacentHTML(\n "afterbegin",\n ` <div class="ext">\n <label class="caption">Delivery method</label>\n <div class="container_deliverymethods">\n ${deliveryMethods}\n </div>\n </div>\n <div class="ext ext-datepicker" style="visibility:hidden">\n <label class="caption">Delivery date</label>\n <div><input type="date" class="datepicker-btn" min="" required ><span class="validate"></span></div>\n <input type="text" class="converteddate" name="Date" style="display:none">\n </div>\n <div class="ext ext-input" style="visibility:hidden">\n <label class="caption">Delivery time</label>\n <input list="" id="input-datalist" autocomplete="off" name="Time" value="${defaultOption}">\n </div>\n <datalist id="datalist">\n </datalist>\n `\n);\n\n//reset hidden elemnts\nfunction f_reset(el) {\n if (el === "datepick") {\n extInput.style.visibility = "hidden";\n validator.className = "validate";\n datePicker.value = "";\n dateValid = false;\n f_disabledCheckout();\n }\n if (el === "datepick" || el === "timeslot") {\n extInput.style.visibility = "hidden";\n timeValid = false;\n f_disabledCheckout();\n }\n if (el === "datepick" || el === "timeslot" || el === "datalist") {\n datalist.style.display = "none";\n f_disabledCheckout();\n }\n}\n\n// convert in ms\nfunction f_ms(d = 0, h = 0, m = 0) {\n h += Number((d % 1).toFixed(4).substring(2));\n m += Number((h % 1).toFixed(4).substring(2));\n\n const result = d * 24 * 60 * 60 * 1000 + h * 60 * 60 * 1000 + m * 60 * 1000;\n\n return result;\n}\n\n//listen for click on delivery methos\nconst instancesDeliveryMethods = qS(\n ".container_deliverymethods"\n);\nconst validator = qS(".validate");\nlet choosenDeliveryM = "";\n\nfunction checkDeliveryMethods(e) {\n validator.className = "validate";\n deliveryMetValid = true;\n choosenDeliveryM = e.target.value;\n f_reset("datepick");\n showDatePicker(e.target.value);\n}\ninstancesDeliveryMethods.addEventListener("change", checkDeliveryMethods);\n\n//calculate first availabe date\nlet addNDay = 0;\n\nfunction showDatePicker(deliveryvalue) {\n addNDay = 0;\n for (const dv of shippingDateTime) {\n if (dv[0] === deliveryvalue) {\n const deliveryOptions = dv[1],\n timeslot = deliveryOptions.timeSlots,\n delayH = f_ms(0, deliveryOptions.delayH);\n\n if (\n typeof timeslot == "number" &&\n f_ms(0, deliveryOptions.endTime) < now + delayH + f_ms(0, timeslot)\n ) {\n addNDay = 1;\n }\n if (\n typeof timeslot == "object" &&\n f_ms(0, timeslot[timeslot.length - 1][0]) < now + delayH\n ) {\n addNDay = 1;\n }\n\n now > f_ms(0, deliveryOptions.lastOrder) ? (addNDay = 2) : "";\n\n deliveryOptions.delayD ? (addNDay = deliveryOptions.delayD) : "";\n\n dateMin(addNDay);\n return;\n }\n }\n}\nconst datePicker = qS(".datepicker-btn"),\n extDatePicker = qS(".ext-datepicker"),\n day = new Date();\nday.setHours(0, 0, 0, 0);\nconst today = day.getTime();\n\nconsole.log(today);\n\nconst nowraw = new Date(),\n hours = nowraw.getHours();\n minutes = nowraw.getMinutes();\n now = f_ms(0, hours) + f_ms(0, 0, minutes);\n // ^^ These should really be declared as lets as they will likely change.\n//set min value of the datePicker\nlet min = new Date();\nfunction dateMin(minDelay) {\n f_reset("datepick");\n\n min.setTime(today + f_ms(minDelay));\n\n if (jqui === true) {\n $(".datepicker-btn").datepicker("option", "minDate", minDelay);\n } else {\n datePicker.min = min.toISOString().slice(0, 10);\n }\n\n extDatePicker.style.visibility = "visible";\n}\n\n// listen for change in date picker\nfunction setDeliverSlots() {\n const dateFromDPraw = new Date(datePicker.value);\n dateFromDPraw.setHours(0, 0, 0, 0);\n const dateFromDP = dateFromDPraw.getTime();\n\n let optiontimeSlotsValues = [];\n inp.value = defaultOption;\n\n if (dateFromDP >= min) {\n validator.className = "validate y";\n qS(".converteddate").value =\n dateFromDPraw.getDate() +\n "-" +\n (dateFromDPraw.getMonth() + 1) +\n "-" +\n dateFromDPraw.getFullYear();\n dateValid = true;\n\n for (const deliveryMetAv of shippingDateTime) {\n const deliveryMetName = deliveryMetAv[0],\n deliveryMetSlots = deliveryMetAv[1].timeSlots,\n delayD = f_ms(deliveryMetAv[1].delayD),\n delayH = f_ms(0, deliveryMetAv[1].delayH),\n daysOff = deliveryMetAv[1].daysOff,\n deliveryMetEndTime = f_ms(0, deliveryMetAv[1].endTime),\n deliveryMetStartTime = f_ms(0, deliveryMetAv[1].startTime);\n\n if (deliveryMetName === choosenDeliveryM) {\n if (daysOff.includes(7)) {\n daysOff.splice(daysOff.indexOf(7), 1, 0);\n }\n\n if (\n daysOff.includes(dateFromDPraw.getDay()) ||\n daysOff.includes(datePicker.value)\n ) {\n input.value = daysOffRisp;\n extInput.style.visibility = "visible";\n dateValid = false;\n datalist.innerHTML = "";\n validator.className = "validate n";\n f_disabledCheckout();\n return;\n }\n\n if (\n typeof deliveryMetSlots == "object" //if timeslot is an array\n ) {\n for (const slot of deliveryMetSlots) {\n const startS = f_ms(0, slot[0]),\n endS = f_ms(0, slot[1]);\n\n if (\n (dateFromDP >= min && dateFromDP != today) ||\n (dateFromDP == today && now < endS + delayH)\n ) {\n optiontimeSlotsValues.push(slot);\n }\n }\n } else if (\n typeof deliveryMetSlots == "number" //if timeslot is a number\n ) {\n const slotDuration = f_ms(0, deliveryMetAv[1].timeSlots);\n let currentSlot = deliveryMetStartTime;\n\n while (deliveryMetEndTime >= currentSlot + delayH) {\n if (dateFromDP == today && currentSlot >= now + delayH) {\n optiontimeSlotsValues.push([\n currentSlot / 60 / 60 / 1000,\n (currentSlot + slotDuration) / 60 / 60 / 1000,\n ]);\n } else if (dateFromDP !== today && dateFromDP >= min) {\n optiontimeSlotsValues.push([\n currentSlot / 60 / 60 / 1000,\n (currentSlot + slotDuration) / 60 / 60 / 1000,\n ]);\n }\n currentSlot += slotDuration;\n }\n }\n }\n\n if (optiontimeSlotsValues != "") {\n let optionstimeSlots = ``;\n\n optiontimeSlotsValues.forEach(function (elems) {\n let [el1, el2] = [...elems];\n function convert(el) {\n el = el.toString();\n if (el.includes(".")) {\n el = el.replace(".", ":").padEnd(5, "0");\n } else {\n el += ":00";\n }\n return el;\n }\n\n elems = convert(el1) + "-" + convert(el2);\n\n optionstimeSlots += `<option class="btn datalist-options" value="${elems}">${elems}</option>`;\n });\n\n datalist.innerHTML = optionstimeSlots;\n extInput.style.visibility = "visible";\n }\n }\n } else {\n validator.className = "validate n";\n dateValid = false;\n f_reset("timeslot");\n }\n f_disabledCheckout();\n}\ndatePicker.addEventListener("inp", setDeliverSlots);\n\n//datalist\nconst inp = qS("#input-datalist"),\n extInput = qS(".ext-input"),\n datalist = qS("#datalist");\ninp.addEventListener("focus", () => (datalist.style.display = "block"));\n\ndatalist.addEventListener("click", function (e) {\n inp.value = e.target.value;\n f_reset("datalist");\n checkTime();\n});\n\ndatalist.style.width = inp.offsetWidth + "px";\ndatalist.style.left = inp.offsetLeft + "px";\ndatalist.style.top = inp.offsetTop + inp.offsetHeight + "px";\n\n// validate time\nfunction checkTime() {\n timeValid = false;\n const datalistOptions = qS(".datalist-options");\n datalistOptions.forEach((element) => {\n if (element.value === inp.value && element.value != "") {\n timeValid = true;\n }\n });\n f_disabledCheckout();\n}\ninp.addEventListener("change", checkTime);\n\n//close datalist if clicked somewhere outside the datalist\nqS("body").addEventListener("click", (e) => {\n if (e.target != inp && e.target.className != "datalist-options")\n f_reset("datalist");\n});\n\n//if browser not support input date load jquery data picker\nlet jqui;\nif (datePicker.type === "text") {\n jqui = true;\n\n const jq = createElem("script");\n jq.src = "https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.5.1.min.js";\n const jui = createElem("script");\n jui.src = "https://ajax.aspnetcdn.com/ajax/jquery.ui/1.10.4/jquery-ui.min.js";\n const css = createElem("link");\n css.href =\n "https://ajax.aspnetcdn.com/ajax/jquery.ui/1.10.4/themes/ui-lightness/jquery-ui.css";\n css.type = "text/css";\n css.rel = "stylesheet";\n const head = document.head || getTag("head")[0];\n\n head.appendChild(jq);\n jq.addEventListener("load", function () {\n head.appendChild(jui);\n jui.addEventListener("load", function () {\n head.appendChild(css);\n css.addEventListener("load", function () {\n if (window.jQuery) {\n $(".datepicker-btn").datepicker({\n altField: ".converteddate",\n altFormat: "dd-mm-yy",\n });\n $(".datepicker-btn").on("change", setDeliverSlots);\n } else {\n alert(\n "Something went wrong ,please try reloading the browser or try with a different one "\n );\n }\n });\n });\n });\n}\n\n//collect the data (optional)\nconst datalog = qS(".datalog");\ncheckoutButton.addEventListener("click", (e) => {\n // e.preventDefault();\n let selectedValue;\n function check() {\n const rbs = qS('inp[name="Method"]');\n for (const rb of rbs) {\n if (rb.checked) {\n selectedValue = rb.value;\n break;\n }\n }\n }\n check();\n datalog.value = `Method:${selectedValue} | Date${\n qS(".converteddate").value\n } | Time${inp.value}`;\n f_reset("datepick");\n});\n</code></pre>\n<p>You could also shorten it a bit further by using bitly URL shortener, for the pre-built script librarys that your importing and maybe creating another helper function for addEventListener & appendChild functions.\nif the animate() function was part of your JQuery then you might need to put these back to the full name.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-28T11:53:27.783",
"Id": "498225",
"Score": "0",
"body": "I'm sorry, but this is bad advice. Shorter code is not better code. Your suggestions hurt readability, which is the top priority for good code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-28T02:13:02.517",
"Id": "252777",
"ParentId": "252766",
"Score": "-1"
}
},
{
"body": "<h1>User friendly</h1>\n<p>Some points on user friendly forms</p>\n<h2>Ambiguity</h2>\n<p>When selecting <em>"Pick-up"</em> the date and time field labels show <em>"Delivery date"</em> and <em>"Delivery time"</em> respectively. This will confuse most users and the service provider will get a pile of emails concerning the ambiguity.</p>\n<p>Ensure that all labels and information is as clear as possible and there should be absolutely no ambiguity.</p>\n<h2>Conformation</h2>\n<p>When the checkout is clicked there is no confirmation asking the user if the details for pickup or delivery are correct. Users can often click the wrong button you must always give them a way to back out of a mistake.</p>\n<h2>Remember</h2>\n<p>After selecting a date and time a user may change their mind in regard to pickup or delivery. If the shipping type is changed the existing fields are reset, this will frustrate some users. Best to keep entered data rather than delete it.</p>\n<h2>Vetting</h2>\n<p>Ensure you vet all dates and times.</p>\n<p>I was able to set a delivery and pickup time to earlier than my systems clock. eg Checkout text <em>"Method:Delivery | Date29-11-2020 | Time12:00-13:00"</em> even though my clock was set to 2pm 29-11-2020.</p>\n<p>The date's year field allows up to 6 numbers, so I do hope that my delivery is not late in the year 275760. <em>"Method:Delivery | Date31-3-275760 | Time12:00-13:00"</em></p>\n<h2>Be informative</h2>\n<p>Be as verbose as you can in regards to displaying selected options.</p>\n<p>The date picker has day names when selecting the date, however that is lost once the date has been selected. Show the day and month names next to the selected date.</p>\n<p>Use 12 hour time, eg 13:00 is 1pm</p>\n<p>What does 12:00-13:00 mean, yes most will know, but some may take it to mean 12:00 or 13:00. The delivery is <strong>between</strong> 12:00 and 13:00. Is that local time?</p>\n<h2>Don't be sloppy</h2>\n<p>The checkout report is sloppy with no spaces after <em>"Method:"</em>, <em>"Date"</em> and <em>"Time"</em> and no separator <em>":"</em> after <em>"Date"</em> and <em>"time"</em>. Use commas <em>","</em>, never use <em>"|"</em></p>\n<p>The checkout report</p>\n<p><em>"Method:Delivery | Date30-11-2020 | Time12:00-13:00"</em></p>\n<p>could be</p>\n<p><em>"Method: Delivery, Date: Monday 30th November 2020, Time: Between 1pm and 3pm local time"</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-30T21:45:38.067",
"Id": "498425",
"Score": "0",
"body": "Thank you very much for the opinion , I wasn't expecting such detailed feedback. I really appreciate it . I suppose you are based in America . I'm based in uk and i developed this code for a small local shop . I didn't think about use outside uk . And the output was basically just demonstrative as the data are suppose to be processed with the method defined by your form . But anyway I see your points and I will update the code . Thanks"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-28T23:32:49.243",
"Id": "252801",
"ParentId": "252766",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T18:38:09.843",
"Id": "252766",
"Score": "5",
"Tags": [
"javascript",
"html"
],
"Title": "Feedback on date and time selector script"
}
|
252766
|
<p>I am designing a Stock Currency application and for that, I created a database.
I searched for my question <a href="https://stackoverflow.com/questions/38926043/join-on-date-in-sqlalchemy-considering-only-date-and-not-time-of-the-day/38936276?noredirect=1#comment114982105_38936276">here</a> first but the answerer told me to ask the same question here.</p>
<pre><code>flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Stock_Data(db.Model):
__tablename__ = 'stock_datas'
# Column names start with capital letter for convention to use data easier (for now)
id = db.Column(db.Integer(), primary_key=True)
Date = db.Column(db.DateTime, nullable=False)
Open = db.Column(db.Float(), nullable=False)
High = db.Column(db.Float(), nullable=False)
Low = db.Column(db.Float(), nullable=False)
Currency_Close = db.Column(db.Float(), nullable=False)
Volume = db.Column(db.Integer(), nullable=False)
# Foreign Key
stock_id = db.Column(db.Integer, db.ForeignKey('stocks.id'))
# Foreign Attribute To Reach
stock = db.relationship('Stock', backref='Stock_Data', primaryjoin='Stock_Data.stock_id==Stock.id', lazy=True)
class Stock(db.Model):
__tablename__ = 'stocks'
id = db.Column(db.Integer(), primary_key=True)
symbol = db.Column(db.String(10), unique=True)
name = db.Column(db.String(50), unique=True)
sector = db.Column(db.String(10), nullable=True)
currency = db.Column(db.String(3), nullable=False)
class Parity_Data(db.Model):
__tablename__ = 'parity_datas'
id = db.Column(db.Integer(), primary_key=True)
Parity_Close = db.Column(db.Float())
Date = db.Column(db.DateTime, nullable=False)
# Foreign Key
parity_id = db.Column(db.Integer, db.ForeignKey('parities.id'))
# Foreign Attribute To Reach
parity = db.relationship('Parity', backref='Parity_Data', primaryjoin='Parity_Data.parity_id==Parity.id', lazy=True)
class Parity(db.Model):
__tablename__ = 'parities'
id = db.Column(db.Integer(), primary_key=True)
parity_name = db.Column(db.String(8), unique=True)
</code></pre>
<p>I created this database design all classes are in separate files. Sotck is related to Stock_Data (1-N) and Parity is related to Parity_Data (1-N) as seen.</p>
<p>I am creating a connection between Stock and Parity by</p>
<pre><code>string_stock = 'APPL'
stock = session.query(Stock).filter(Stock.symbol == str(string_stock).upper()).first()
stock_data = session.query(Stock_Data).filter(Stock_Data.stock_id == stock.id).all()
parity = session.query(Parity).filter(Parity.parity_name.endswith(stock.currency)).first()
parity_data = session.query(Parity_Data).filter(Parity_Data.parity_id==parity.id).all()
</code></pre>
<p>By this method, I can fetch all stock_data and parity_data separately. However, when I try to merge stock_data and parity_data I get two lists and cannot be merged.
After that, I tried</p>
<pre><code>data_joined_on_time = session.query(Stock_Data).join(Parity_Data, Stock_Data.Date == Parity_Data.Date).all()
dir(session.query(Stock_Data).join(Parity_Data, Stock_Data.Date == Parity_Data.Date).all()[0])
</code></pre>
<p>This method joins data but the attributes:
['Currency_Close',
'Date',
'High',
'Low',
'Open',
'Volume',
'<strong>class</strong>',
'<strong>delattr</strong>',
'<strong>dict</strong>',
'<strong>dir</strong>',
'<strong>doc</strong>',
'<strong>eq</strong>',
'<strong>format</strong>',
'<strong>ge</strong>',
'<strong>getattribute</strong>',
'<strong>gt</strong>',
'<strong>hash</strong>',
'<strong>init</strong>',
'<strong>init_subclass</strong>',
'<strong>le</strong>',
'<strong>lt</strong>',
'<strong>mapper</strong>',
'<strong>module</strong>',
'<strong>ne</strong>',
'<strong>new</strong>',
'<strong>reduce</strong>',
'<strong>reduce_ex</strong>',
'<strong>repr</strong>',
'<strong>setattr</strong>',
'<strong>sizeof</strong>',
'<strong>str</strong>',
'<strong>subclasshook</strong>',
'<strong>table</strong>',
'<strong>tablename</strong>',
'<strong>weakref</strong>',
'_decl_class_registry',
'_sa_class_manager',
'_sa_instance_state',
'id',
'metadata',
'query',
'query_class',
'stock',
'stock_id']</p>
<p>There is nothing about Parity_Data part.</p>
<p>My question consists of two parts:</p>
<ol>
<li>I could not think of another way for my database design.Is my database design incorrect?</li>
<li>Is there a way to merge those two (stock_data and parity_data) by SQLAlchemy? I would like to filter first and join after it.<br />
If there is no way I will merge them on pandas dataframe but firstly I want to try it on SQLAlchemy.</li>
</ol>
|
[] |
[
{
"body": "<p>At the end of the day I used pandas.</p>\n<pre><code>df = pandas.read_sql_query("""My join query""")\n</code></pre>\n<p>This all just solved my problem.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-27T20:47:08.820",
"Id": "261311",
"ParentId": "252767",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "261311",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T19:15:17.410",
"Id": "252767",
"Score": "3",
"Tags": [
"python",
"flask",
"join",
"sqlalchemy",
"orm"
],
"Title": "Flask Database Design with ORM"
}
|
252767
|
<p>Module: <a href="https://amueller.github.io/word_cloud/" rel="nofollow noreferrer">https://amueller.github.io/word_cloud/</a></p>
<p>I really enjoyed the python WordCloud module, so I wanted to give it a GUI so I could share it with family and friends. I also wanted a platform where one could generate their own WordClouds within their own pictures, without word limitations (like many of the online wordcloud programs).</p>
<p>The GUI provides a number of options to modify the WordCloud, and instructions are presented via a tooltip. I've also added some additional advanced options (things I think might be a bit less intuitive, but are still there if the user wants to modify them).</p>
<p>I'm basically looking for feedback on my code structure, and specifically how I implement modifications of the various arguments. This is my first time making a window within a window in Tkinter, and I had to use various globals to try and get it to work properly (which I know is a big no no).</p>
<pre><code>#main.py
import tkinter as tk
import numpy as np
import matplotlib.pyplot as plt
import os
from wordcloud import WordCloud,STOPWORDS
from collections import Counter
from PIL import Image as img
from tkinter import filedialog
from tkinter import *
from collections import Counter
import traceback
root = tk.Tk()
root.title('Word Cloud Generator')
root.geometry('600x600')
class CreateToolTip(object):
"""
create a tooltip for a given widget
"""
def __init__(self, widget, text='widget info'):
self.waittime = 100 #miliseconds
self.wraplength = 280 #pixels
self.widget = widget
self.text = text
self.widget.bind("<Enter>", self.enter)
self.widget.bind("<Leave>", self.leave)
self.widget.bind("<ButtonPress>", self.leave)
self.id = None
self.tw = None
def enter(self, event=None):
self.schedule()
def leave(self, event=None):
self.unschedule()
self.hidetip()
def schedule(self):
self.unschedule()
self.id = self.widget.after(self.waittime, self.showtip)
def unschedule(self):
id = self.id
self.id = None
if id:
self.widget.after_cancel(id)
def showtip(self, event=None):
x = y = 0
x, y, cx, cy = self.widget.bbox("insert")
x += self.widget.winfo_rootx() + 25
y += self.widget.winfo_rooty() + 20
# creates a toplevel window
self.tw = tk.Toplevel(self.widget)
# Leaves only the label and removes the app window
self.tw.wm_overrideredirect(True)
self.tw.wm_geometry("+%d+%d" % (x, y))
label = tk.Label(self.tw, text=self.text, justify='left',
background="#ffffff", relief='solid', borderwidth=1,
wraplength = self.wraplength)
label.pack(ipadx=1)
def hidetip(self):
tw = self.tw
self.tw= None
if tw:
tw.destroy()
label0=tk.Label(root, text="Hover over line for instructions")
label0.grid(row=0)
label1=tk.Label(root, text="Load File")
label1.grid(row=1)
label1_tooltip=CreateToolTip(label1,'Load a text file containing your words')
label2=tk.Label(root, text="Words")
label2.grid(row=2)
label2_tooltip=CreateToolTip(label2,'Type in the words you want in your wordcloud, the more words, the better the word cloud will look. \n Words are case-sensitive (i.e. The is different form the)\n Separate words with space')
label3=tk.Label(root, text="Frequency of word")
label3.grid(row=3)
label3=CreateToolTip(label3,'This signifies the size of the above words. The more frequent a word, the larger it will be.\n Type in a number that represents the size of the word \n'
'The larger the number, the larger the word. I.E. Family Love Health in order of size, would be 200 100 50')
label4=tk.Label(root, text="Background Color")
label4.grid(row=4)
label4=CreateToolTip(label4,'Background Color of the Word Cloud, Default is white')
label5=tk.Label(root, text="Wordcloud Width")
label5.grid(row=5)
label5=CreateToolTip(label5,'The higher this number, the better the resolution of the words within your word cloud. Default is 400')
label6=tk.Label(root, text="Wordcloud Height")
label6.grid(row=6)
label6=CreateToolTip(label6,'Same as the width. Default is 400')
label7=tk.Label(root, text="Window Width")
label7.grid(row=7)
label7=CreateToolTip(label7,'Size of the WordCloud picture. \nThe higher the number, the larger the figure. Default is 5')
label8=tk.Label(root, text="Window Height")
label8.grid(row=8)
label8=CreateToolTip(label8,'Same as width. Default is 5')
label9=tk.Label(root, text="Words not to use")
label9.grid(row=9)
label9=CreateToolTip(label9,'A list of words to ignore. \nSeparate multiple words with space. I.E. Hello Goodbye.\nWords are case-sensitive (i.e. The is different form the)')
tk.Label(root, text="Image Options").grid(row=10)
label10=tk.Label(root, text="Load Image")
label10.grid(row=11)
label10=CreateToolTip(label10,'Image to insert the wordcloud into. \n Use photos that have a white background, and black filling where you want the words to be in.')
label11=tk.Label(root, text="Image Outline Thickness")
label11.grid(row=12)
label11=CreateToolTip(label11,'This defines the outline of the image. Default is 3')
label12=tk.Label(root, text="Image Outline Color")
label12.grid(row=13)
label12=CreateToolTip(label12,'The color of the outline. Default is black')
load_file=tk.Entry(root)
load_file.grid(row=1, column=1,sticky=W)
word_list=tk.Entry(root)
word_list.grid(row=2, column=1,ipadx=100,sticky=W+E)
multiplyer=tk.Entry(root)
multiplyer.grid(row=3, column=1,ipadx=100,sticky=W+E)
background_color_input=tk.Entry(root)
background_color_input.grid(row=4,column=1,sticky=W)
width_input=tk.Entry(root)
width_input.grid(row=5,column=1,sticky=W)
height_input=tk.Entry(root)
height_input.grid(row=6,column=1,sticky=W)
window_width_input=tk.Entry(root)
window_width_input.grid(row=7,column=1,sticky=W)
window_height_input=tk.Entry(root)
window_height_input.grid(row=8,column=1,sticky=W)
stopwords_input=tk.Entry(root)
stopwords_input.grid(row=9,column=1,sticky=W)
image_input=tk.Entry(root)
image_input.grid(row=11,column=1,sticky=W)
contour_width_input=tk.Entry(root)
contour_width_input.grid(row=12,column=1,sticky=W)
contour_color_input=tk.Entry(root)
contour_color_input.grid(row=13,column=1,sticky=W)
text=()
text_directory=()
image=()
image_directory=()
def input_file():
fullpath = filedialog.askopenfilename(parent=root, title='Choose a file')
global text_directory
global text
text_directory=os.path.dirname(fullpath)
text= os.path.basename(fullpath)
label2=Label(root,text=fullpath).grid(row=1,column=1,sticky=W)
def image_file():
fullpath = filedialog.askopenfilename(parent=root, title='Choose a file')
global image
global image_directory
image_directory=os.path.dirname(fullpath)
image= os.path.basename(fullpath)
label2=Label(root,text=fullpath).grid(row=11,column=1,sticky=W)
new_top_flag=False
new_top=None
def run():
print('Program is Running')
try:
global new_top
stopwords = set(STOPWORDS)
width_value,height_value,background_colors,contour_color,contour_width,stopwords,window_width,window_height = defaults(stopwords)
if new_top_flag != False:
max_words,min_font_size,max_font_size,mode,relative_scaling=new_top.values()
else:
max_words,min_font_size,max_font_size,mode,relative_scaling=200,4,None,'RGB','auto'
if word_list.get() != '':
inputed_words=[]
words_typed=word_list.get()
multiplyer_value=multiplyer.get()
for words,number in zip(words_typed.split(),multiplyer_value.split()):
inputed_words+=((words+',')*int(number)).split(',')
word_could_dict=Counter(inputed_words)
if image == ():
wc= WordCloud(width=width_value, height=height_value,background_color=background_colors,stopwords=stopwords,max_words=max_words,min_font_size=min_font_size,max_font_size=max_font_size,mode=mode,relative_scaling=relative_scaling).generate_from_frequencies(word_could_dict)
else:
os.chdir(image_directory)
new_mask=np.array(img.open(image))
wc= WordCloud(width=width_value, height=height_value,background_color=background_colors,stopwords=stopwords,mask=new_mask,contour_color=contour_color,contour_width=contour_width,max_words=max_words,min_font_size=min_font_size,max_font_size=max_font_size,mode=mode,relative_scaling=relative_scaling).generate_from_frequencies(word_could_dict)
wc.to_file('savefile.png')
plt.figure(figsize = (window_width,window_height))
plt.imshow(wc, interpolation="bilinear")
plt.tight_layout(pad=0)
plt.axis("off")
plt.show()
else:
os.chdir(text_directory)
text_file = (open(text,encoding="utf8" ).read()).lower()
if image ==():
wc= WordCloud(width=width_value, height=height_value,background_color=background_colors,stopwords=stopwords,max_words=max_words,min_font_size=min_font_size,max_font_size=max_font_size,mode=mode,relative_scaling=relative_scaling).generate(text_file)
else:
os.chdir(image_directory)
new_mask=np.array(img.open(image))
wc= WordCloud(width=width_value, height=height_value,background_color=background_colors,stopwords=stopwords,mask=new_mask,contour_color=contour_color,contour_width=contour_width,max_words=max_words,min_font_size=min_font_size,max_font_size=max_font_size,mode=mode,relative_scaling=relative_scaling).generate(text_file)
wc.to_file('savefile.png')
plt.figure(figsize = (window_width,window_height))
plt.imshow(wc, interpolation="bilinear")
plt.tight_layout(pad=0)
plt.axis("off")
plt.show()
new_top=None
except:
print('Error Running Program. Report below error report\n')
traceback.print_exc()
def defaults(stopwords):
if width_input.get() == '':
width_value=400
else:
width_value=int(width_input.get())
if height_input.get() == '':
height_value=400
else:
height_value=int(height_input.get())
if stopwords_input.get() != '':
for values in (stopwords_input.get()).split():
stopwords.add(values)
if background_color_input.get() == '':
background_colors='white'
else:
background_colors=background_color_input.get()
if contour_color_input.get() == '':
contour_color='black'
else:
contour_color=contour_color_input.get()
if contour_width_input.get() == '':
contour_width=3
else:
contour_width=int(contour_width_input.get())
if window_width_input.get() == '':
window_width = 5
else:
window_width=int(window_width_input.get())
if window_height_input.get() == '':
window_height=5
else:
window_height=int(window_height_input.get())
return width_value,height_value,background_colors,contour_color,contour_width,stopwords,window_width,window_height
def new_window():
global new_top
global new_top_flag
from advanced import newTopLevel
new_top = newTopLevel(root)
new_top_flag=True
newWindow = new_top.newWindow
tk.Button(root,text='browse',command=input_file).grid(row=1,column=2)
tk.Button(root,text='browse',command=image_file).grid(row=11,column=2)
tk.Button(root,text='Advanced Settings',command=new_window).grid(row=34,column=1)
tk.Button(root,text='run',command=run).grid(row=14,column=1,sticky=W)
root.mainloop()
</code></pre>
<pre><code>#advanced.py
from tkinter import *
import tkinter as tk
class CreateToolTip(object):
"""
create a tooltip for a given widget
"""
def __init__(self, widget, text='widget info'):
self.waittime = 100 #miliseconds
self.wraplength = 280 #pixels
self.widget = widget
self.text = text
self.widget.bind("<Enter>", self.enter)
self.widget.bind("<Leave>", self.leave)
self.widget.bind("<ButtonPress>", self.leave)
self.id = None
self.tw = None
def enter(self, event=None):
self.schedule()
def leave(self, event=None):
self.unschedule()
self.hidetip()
def schedule(self):
self.unschedule()
self.id = self.widget.after(self.waittime, self.showtip)
def unschedule(self):
id = self.id
self.id = None
if id:
self.widget.after_cancel(id)
def showtip(self, event=None):
x = y = 0
x, y, cx, cy = self.widget.bbox("insert")
x += self.widget.winfo_rootx() + 25
y += self.widget.winfo_rooty() + 20
# creates a toplevel window
self.tw = tk.Toplevel(self.widget)
# Leaves only the label and removes the app window
self.tw.wm_overrideredirect(True)
self.tw.wm_geometry("+%d+%d" % (x, y))
label = tk.Label(self.tw, text=self.text, justify='left',
background="#ffffff", relief='solid', borderwidth=1,
wraplength = self.wraplength)
label.pack(ipadx=1)
def hidetip(self):
tw = self.tw
self.tw= None
if tw:
tw.destroy()
max_words=0
min_font_size=0
max_font_size=0
mode=0
relative_scaling=0
class newTopLevel(object):
def __init__(self, root):
self.newWindow = Toplevel(root)
self.newWindow.title("Advanced")
self.newWindow.geometry("400x400")
label1=tk.Label(self.newWindow, text="Max words")
label1.grid(row=0)
label1_tooltip=CreateToolTip(label1,'The maximum number of words. Default is 200')
label2=tk.Label(self.newWindow, text="Min Font Size")
label2.grid(row=1)
label2_tooltip=CreateToolTip(label2,'The smallest font size to use. Word Cloud will not generate any words smaller than this \n Default is 4')
label3=tk.Label(self.newWindow, text="Max Font Size")
label3.grid(row=2)
label3_tooltip=CreateToolTip(label3,'The maximum font size for the largest word')
label4=tk.Label(self.newWindow, text="Mode")
label4.grid(row=3)
label4_tooltip=CreateToolTip(label4,'If a transparent background is desired, type in RGBA, and change the background to None')
label5=tk.Label(self.newWindow, text="Relative Scaling")
label5.grid(row=4)
label5_tooltip=CreateToolTip(label5,'A scale of 0, only word ranks are considered. A scale of 1,the more frequent word will be 2x the size as before.\n A scale of 0.5 uses word frequencies and rank. Defaulse is 0.5')
self.max_word_input=tk.Entry(self.newWindow)
self.max_word_input.grid(row=0,column=1)
self.min_font_input=tk.Entry(self.newWindow)
self.min_font_input.grid(row=1,column=1)
self.max_font_input=tk.Entry(self.newWindow)
self.max_font_input.grid(row=2,column=1)
self.mode_input=tk.Entry(self.newWindow)
self.mode_input.grid(row=3,column=1)
self.scaling_input=tk.Entry(self.newWindow)
self.scaling_input.grid(row=4,column=1)
tk.Button(self.newWindow,text='Apply Settings',command=self.input_values).grid(row=7,column=1)
tk.Button(self.newWindow,text='Restore Default',command=self.input_values).grid(row=7,column=2)
def input_values(self):
global max_words
global min_font_size
global max_font_size
global mode
global relative_scaling
if self.max_word_input.get() == '':
max_words=200
else:
max_words=int(self.max_word_input.get())
if self.min_font_input.get() == '':
min_font_size=4
else:
min_font_size=int(self.min_font_input.get())
if self.max_font_input.get() == '':
max_font_size=None
else:
max_font_size=int(self.max_font_input.get())
if self.mode_input.get() == '':
mode='RGB'
else:
mode=self.mode_input.get()
if self.scaling_input.get() == '':
relative_scaling='auto'
else:
relative_scaling=float(self.scaling_input.get())
def values(self):
return max_words,min_font_size,max_font_size,mode,relative_scaling
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T20:42:13.817",
"Id": "252770",
"Score": "4",
"Tags": [
"python",
"tkinter"
],
"Title": "Python WordCloud GUI"
}
|
252770
|
<p>This is my working template file which I manually edit to create new properly formatted webpages for my personal website.</p>
<p>I am interested in what advantages if any could be realized by placing the CSS in this file into an external file before modifying this file to work as a Django template.</p>
<p>Should I just leave it the way it is before I add Django template tags to this file?</p>
<p>Here is my present template code below:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<style>
div.in_page_menu {
background: radial-gradient (#f69d3c,#ffeeaa);
opacity: 0.6;
margin: 50px;
font-size: 14px;
border-width: 25px;
border-top-style: none;
border-right-style: none;
border-bottom-style: none;
border-left-style: solid;
border-color: hsl(0, 0%, 73%);
box-shadow: 0 9px 9px -5px #666;
}
</style>
<style>
div.contentbox {
background: #ffeeaa;
opacity: 0.7;
margin: 50px;
font-size: 28px;
border-width: 25px;
border-top-style: none;
border-right-style: none;
border-bottom-style: none;
border-left-style: solid;
border-color: hsl(0, 0%, 73%);
}
</style>
<style>
div.body_div {
background-image: url("butterflies_faded.png");
background-repeat: no-repeat;
background-attachment: fixed;
}
</style>
<script src="autoScrollTo.js"></script>
<link rel="icon" href="favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="style/style.css">
</head>
<body>
<?php include_once("php_includes/template_pageTop.php"); ?>
<div class="body_div">
<h2 id="myheading">Resource Links</h2>
<div class="in_page_menu">
<a href="#" onclick="return false;" onmousedown="autoScrollTo('div1');">
text link1</a><br />
<a href="#" onclick="return false;" onmousedown="autoScrollTo('div2');">
text link 2</a><br />
<a href="#" onclick="return false;" onmousedown="autoScrollTo('div3');">
text link 3</a><br />
<a href="#" onclick="return false;" onmousedown="autoScrollTo('div4');">
text link 4</a><br />
<a href="#" onclick="return false;" onmousedown="autoScrollTo('div5');">
text link 5</a><br />
<a href="#" onclick="return false;" onmousedown="autoScrollTo('div6');">
text link 6</a><br />
<a href="#" onclick="return false;" onmousedown="autoScrollTo('div7');">
text link 7</a><br />
<a href="#" onclick="return false;" onmousedown="autoScrollTo('div8');">
text link 8</a><br />
<a href="#" onclick="return false;" onmousedown="autoScrollTo('div9');">
text link 9</a><br />
<a href="#" onclick="return false;" onmousedown="autoScrollTo('div10');">
text link 10</a><br />
</div>
<div id="div1" class="contentbox">
<h3>content 1 heading</h3>
<p>
paragraph content 1
</p>
<ul>
<li>content 1 list item
</ul>
<a href="#" onclick="return false;" onmousedown="resetScroller('myheading');">
go back to top</a>
<br>
<br>
<div id="div2" class="contentbox">
<h3>content 2 heading</h3>
<p>
paragraph content 2
</p>
<ul>
<li>content2 list item
</ul>
</div>
<a href="#" onclick="return false;" onmousedown="resetScroller('myheading');">
go back to top</a>
<div id="div3" class="contentbox">
<h3>content 3 heading</h3>
<p>
paragraph content 3
</p>
<ul>
<li>content 3 list item
</ul>
</div>
<a href="#" onclick="return false;" onmousedown="resetScroller('myheading');">
go back to top</a>
<div id="div4" class="contentbox">
<h3>content 4 heading</h3>
<p>
paragraph content 4
</p>
<ul>
<li>content 4 list item
</ul>
</div>
<a href="#" onclick="return false;" onmousedown="resetScroller('myheading');">
go back to top</a>
<div id="div5" class="contentbox">
<h3>content 5 heading</h3>
<p>
paragraph content 5
</p>
<ul>
<li>content 5 list item
</ul>
</div>
<a href="#" onclick="return false;" onmousedown="resetScroller('myheading');">
go back to top</a>
<div id="div6" class="contentbox">
<h3>content 6 heading</h3>
<p>
paragraph content 6
</p>
<ul>
<li>content 6 list item
</ul>
</div>
<a href="#" onclick="return false;" onmousedown="resetScroller('myheading');">
go back to top</a>
<div id="div7" class="contentbox">
<h3>content 7 heading</h3>
<p>
paragraph content 7
</p>
<ul>
<li>content 7 list item
</ul>
</div>
<a href="#" onclick="return false;" onmousedown="resetScroller('myheading');">
go back to top</a>
<div id="div8" class="contentbox">
<h3>content 8 heading</h3>
<p>
paragraph content 8
</p>
<ul>
<li>content 8 list item
</ul>
</div>
<a href="#" onclick="return false;" onmousedown="resetScroller('myheading');">
go back to top</a>
<div id="div9" class="contentbox">
<h3>content 9 heading</h3>
<p>
paragraph content 9
</p>
<ul>
<li>content 9 list item
</ul>
</div>
<a href="#" onclick="return false;" onmousedown="resetScroller('myheading');">
go back to top</a>
<div id="div10" class="contentbox">
<h3>content 10 heading</h3>
<p>
paragraph content 10
</p>
<ul>
<li>content 10 list item
</ul>
</div>
<a href="#" onclick="return false;" onmousedown="resetScroller('myheading');">
go back to top</a>
</div>
</body>
</html>
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n<p>I am interested in what advantages if any could be realized by placing the css in this file into an external file</p>\n</blockquote>\n<p>A tradeoff is involved:</p>\n<ul>\n<li>If you put CSS in a separate file, browsers will be able to cache it easily (if your server is set up correctly). In contrast, if you serve the CSS inline, it'll be sent over the wire every time the page is loaded. But...</li>\n<li>If you put the CSS in a separate file, the first time the client visits the site, they'll have to make <em>two</em> requests for the page to display properly: one for the HTML, and one for the CSS. (This same exact reasoning applies to <code><script></code>s)</li>\n</ul>\n<p>For professional sites, the usual recommendation is to put CSS that's critical to initial display inline, and to put secondary CSS in a separate file. Here, since your CSS rules are applying to elements immediately visible on the page, inline rules are probably a good choice.</p>\n<hr />\n<h2>Review</h2>\n<p><strong>Combine common CSS rules when possible</strong> - <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a> code is more elegant and easier to understand, usually. Here, since the <code>margin</code> and all the <code>border-</code> styles are the same for the <code>.in_page_menu</code> and the <code>.contentbox</code>, consider giving them both the same class with those rules, rather than repeating the rules twice. You could also do this via CSS preprocessing, like with SASS.</p>\n<p><strong>Combine tags</strong> - unless there's a good reason for separate <code><style></code> tags, since they all refer to the same document, it'd make more sense to have just a single tag, not two or three.</p>\n<p><strong>Don't block loading with scripts</strong> - the <code><script src="autoScrollTo.js"></script></code> in the <code><head></code> is <em>blocking</em>; the page won't render until that script is downloaded, which could be a problem on bad connections who haven't visited the site before. If <code>autoScrollTo</code> runs anything that <em>needs</em> to run ASAP on pageload, consider putting that content inline into another script tag in the HTML. Allow the browser to continue processing the document while not-immediately-essential scripts are being downloaded by giving those scripts the <code>defer</code> attribute.</p>\n<p><strong>Numerically indexed IDs are <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">WET</a> and inelegant</strong> - IDs should be reserved for elements that are going to be <em>absolutely unique</em> in a document, such as the <code>#myheading</code>. Items that are part of a collection without something special distinguishing one from the rest probably shouldn't have IDs.</p>\n<p><strong>Avoid inline handlers</strong>, they're\n<a href=\"https://stackoverflow.com/a/59539045\">terrible</a> given their scoping rules and quote escaping. Nowadays, there isn't really any reason to use them - attach event listeners properly using Javascript with <code>addEventListener</code> instead.</p>\n<p>Change:</p>\n<pre><code><a href="#" onclick="return false;" onmousedown="autoScrollTo('div1');">\n text link1</a><br />\n<a href="#" onclick="return false;" onmousedown="autoScrollTo('div2');">\n text link 2</a><br />\n....\n</code></pre>\n<p>to:</p>\n<pre><code>const contents = document.querySelectorAll('.contentbox');\ndocument.querySelectorAll('.in_page_menu a').forEach((a, i) => {\n a.addEventListener('mousedown', () => {\n autoScrollTo(contents[i]);\n });\n});\n</code></pre>\n<p>(changing <code>autoScrollTo</code> as needed to take a reference to the element instead of an ID string)</p>\n<p>You could also consider styling the <code><a></code>s as blocks to remove the need for the <code><br /></code>s between them.</p>\n<p>You can also change all of the:</p>\n<pre><code><a href="#" onclick="return false;" onmousedown="resetScroller('myheading');">\n...\n</code></pre>\n<p>to</p>\n<pre><code>for (const a of document.querySelectorAll('.contentbox a')) {\n a.addEventListener('click', () => {\n // maybe change this to a direct reference to `#myheading instead of a string\n resetScroller('myheading');\n });\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T22:07:26.090",
"Id": "498194",
"Score": "0",
"body": "I don't know how to implement the improved \"DRY\" javascript you have given. I don't see how to feed in the correct number of links. Also where is the html link for the user to select autoScrollTo?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T22:10:16.640",
"Id": "498195",
"Score": "0",
"body": "To implement it, just remove your inline handlers and run the JavaScript in the answer instead, to add the event listeners. Since the `n`th link is meant to link to the `n`th `.contentbox` element, use the index of the `a` being iterated over to identify the corresponding `.contentbox` to go to - the second parameter of `forEach` is the index being iterated over."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T21:15:43.667",
"Id": "252772",
"ParentId": "252771",
"Score": "3"
}
},
{
"body": "<p>Separating styles and templates really matters when you have large templates and many of them. As soon as your site starts to grow, it becomes increasingly unmaintainable to have both mixed up.</p>\n<p>One minor reason is that your templates become larger than required. If you want to make a quick change in a template you have to scroll past all the noise at the top of the file first.</p>\n<p>But the main drawback is that you cannot reuse styles across templates. You have to define certain parts of your styles over and over again. This duplicates make the style much harder to change because you have to make sure you consistently make the changes at all the places.</p>\n<p>I see hardly any reason why you would combine css and html in one file. It doesn't hurt at all to separate the right from the beginning.</p>\n<p>By the way, you don't have to start a new <code><style></code> tag for each CSS selector. One opening <code><style></code> at the top and a closing <code></style></code> at the bottom of your CSS is enough.</p>\n<p><strong>Update:</strong> Having read @CertainPerformance's answer I think it's important to point out that there may be (performance) reasons to place your CSS inside the HTML for the browser but it doesn't mean you shouldn't organize your source files properly and separate templates and styles. If required, you can use tools such as <em>webpack</em> to bundle everything together and send just one file to the client.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T21:20:54.013",
"Id": "252773",
"ParentId": "252771",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-27T20:46:08.660",
"Id": "252771",
"Score": "0",
"Tags": [
"javascript",
"php",
"html",
"css",
"django"
],
"Title": "Template file for creating formatted webpages"
}
|
252771
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.