body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>This is partially inspired by this <a href="https://codereview.stackexchange.com/questions/269755/bigbytelist-with-a-managed-wrapper">question</a></p> <p>I have started creating an example to show how to keep certain parts of the array on disk and came up with the following:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;fstream&gt; #include &lt;iostream&gt; #include &lt;vector&gt; #ifdef _WIN32 std::string createTempFileName() { char buf[800]; tmpnam_s(buf, sizeof(buf)); return buf; } #else std::string createTempFileName() { char filename[] = &quot;/tmp/mytemp.XXXXXX&quot;; // template for our file. int fd = mkstemp(filename); return filename; } #endif template &lt;class T, std::size_t blockSize&gt; class Block { public: explicit Block(std::size_t blockIndex) { inRAM = true; index = blockIndex; offset = 0; data.resize(blockSize); used = 0; } void write(std::fstream&amp; file) { file.seekg(offset, std::ios::beg); file.write((char*)data.data(), sizeof(T) * blockSize); data.resize(0); inRAM = false; } void read(std::fstream&amp; file) { file.seekg(offset, std::ios::beg); data.resize(blockSize); file.read((char*)data.data(), sizeof(T) * blockSize); inRAM = true; } public: bool inRAM; std::size_t used; std::size_t index; std::size_t offset; std::vector&lt;T&gt; data; }; template &lt;class T, std::size_t blockSize, std::size_t maxBlocksInRAM&gt; class BigList { public: BigList() { offset = 0; temp.open(createTempFileName(), std::ios_base::out | std::ios_base::in | std::ios_base::trunc | std::ios_base::binary); blocks.emplace_back(blocks.size()); blocksInRAM.push_back(blocks.back().index); } void add(const T value) { // check if block is in memory and have space available if (blocks.back().inRAM == false &amp;&amp; blocks.back().used &lt; blockSize) { flushBlockIfNeeded(); blocks.back().read(temp); blocksInRAM.push_back(blocks.back().index); } // check if block have space available if (blocks.back().used == blockSize) { flushBlockIfNeeded(); blocks.emplace_back(blocks.size()); blocksInRAM.push_back(blocks.back().index); } // add value to block blocks.back().data[blocks.back().used++] = value; } const T&amp; get(std::uint64_t index) { std::size_t blockIndex = index / blockSize; std::size_t itemIndex = index % blockSize; auto&amp; block = blocks.at(blockIndex); if (block.inRAM == false) { flushBlockIfNeeded(); block.read(temp); blocksInRAM.push_back(blockIndex); } return block.data.at(itemIndex); } private: void flushBlockIfNeeded() { if (blocksInRAM.size() == maxBlocksInRAM) { auto&amp; block = blocks[blocksInRAM[0]]; if (block.offset == 0) { block.offset = offset; offset += sizeof(T) * blockSize; } block.write(temp); blocksInRAM.erase(blocksInRAM.begin()); } } std::size_t offset; std::vector&lt;Block&lt;T, blockSize&gt;&gt; blocks; std::vector&lt;std::size_t&gt; blocksInRAM; std::fstream temp; }; int main() { BigList&lt;int, 16, 4&gt; list; for (int i = 0; i &lt; 254; i++) list.add(i * 10); for (int i = 0; i &lt; 128; i++) std::cout &lt;&lt; list.get(i) &lt;&lt; '\n'; list.add(2550); list.add(2560); for (int i = 0; i &lt; 256; i++) std::cout &lt;&lt; list.get(i) &lt;&lt; '\n'; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T20:35:34.187", "Id": "532662", "Score": "0", "body": "Why not use `MapViewOfFile` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T20:41:01.527", "Id": "532663", "Score": "0", "body": "@JDługosz, isn't `MapViewOfFile` a Win32-specific thing? I wanted to create something that is at least partially portable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T20:43:51.823", "Id": "532664", "Score": "0", "body": "Yes, for Posix use `mmap`. I saw you had Win32-specific code so just used that name." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T21:38:06.950", "Id": "532670", "Score": "0", "body": "@JDługosz, thanks, it looks interesting." } ]
[ { "body": "<h1>Safely creating a temporary file</h1>\n<p>Creating a temporary file safely is harder than you think. The way you do it is unfortunately not safe. For the Linux version, you are ignoring the return value of <code>mkstemp()</code>, this leaks the filedescriptor. Another process might replace the temporary file you just created with <code>mkstemp()</code> with a symlink to another file before your process gets around to opening the <code>std::fstream</code>. It's even more unfortunate that there is no safe way to do this in standard C++.</p>\n<p>Of course this does not affect <code>class BigList</code> itself.</p>\n<h1>Make <code>maxBlocksInRAM</code> a regular member variable</h1>\n<p>There is little reason to make <code>maxBlocksInRAM</code> a template parameter. It is not improving type safety, nor making the code more efficient.</p>\n<h1>Provide defaults for <code>blockSize</code> and <code>maxBlocksInRAM</code></h1>\n<p>As a user of a <code>BigList</code>, I don't want to worry about how to efficiently load and save blocks. Ideally, it just should use the optimal block size and the number of resident blocks automatically. A simple way to do this is to provide default values for these (template) parameters:</p>\n<pre><code>template &lt;class T, std::size_t blockSize = 1024&gt;\nclass BigList {\n ...\n};\n</code></pre>\n<h1>Think about lifetimes of references</h1>\n<p>The member function <code>get()</code> returns a reference to a <code>T</code>. However, you don't know how long the caller of <code>get()</code> is going to keep this reference around. Ideally, you want to ensure that the <code>Block</code> it came from stays in RAM for however long the reference is still used. One way to do this is to return something similar to a <a href=\"https://en.cppreference.com/w/cpp/memory/shared_ptr\" rel=\"nofollow noreferrer\"><code>std::shared_ptr</code></a>. You can add a reference counter to <code>Block</code>, and have <code>get()</code> return a RAII object that increases the refcount of the owning <code>Block</code> in its constructor, and decreases it in its destructor. Also, the logic of <code>flushBlockIfNeeded()</code> should be changed to never flush a block that has a non-zero reference count.</p>\n<h1>Consider the overhead of a <code>Block</code></h1>\n<p>You only ever add <code>Block</code>s to the vector <code>blocks</code>, you never remove them. A <code>Block</code> that has <code>inRAM == false</code> is still using some memory. On my machine, it is using 56 bytes of memory per <code>Block</code>. If you only store 16 <code>int</code>s per Block, that is a lot of overhead.</p>\n<p>You can of course easily increase <code>blockSize</code> and reduce the overhead, but it is still non-zero, and grows the more <code>Block</code>s there are in the <code>BigList</code>. Instead of keeping empty <code>Block</code>s around, consider removing them entirely. A possible way is to avoid having both <code>blocks</code> and <code>blocksInRAM</code>, and just have a <code>std::set&lt;Block&gt; blocks</code>, and overload <code>Block::operator&lt;()</code> so the <code>Block</code>s are ordered by their <code>index</code>. Then in <code>get()</code> you do:</p>\n<pre><code>std::size_t blockIndex = index / blockSize;\nauto it = blocks.find(blockIndex);\nif (it == blocks.end()) {\n // It's not in RAM, read it in\n} else {\n // It's in RAM\n auto &amp;block = *it;\n ...\n}\n</code></pre>\n<p>If course, this is more expensive. There are better data structures than <code>std::set</code>, but they are not in the STL.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T22:43:49.347", "Id": "269893", "ParentId": "269884", "Score": "5" } }, { "body": "<p>So this is meant to get and store single values of type <code>T</code>. It doesn't return a durable pointer that you can use for the block of values for a while after fetching it, right?</p>\n<p>So what does this do that the normal disk caching doesn't handle? You're not doing anything to turn off the normal caching from ostreams or the operating system. So, you're just re-copying values that are still in memory anyway.</p>\n<p>That is, when you call <em>get</em>, your code first looks in your list of loaded blocks. If it's not present, it reads from the <code>fstream</code> which probably buffers a single region only, so it will be found for the same or neighboring block; that's probably a waste of memory and overhead since it will only hold things that are already in your loaded blocks. Then it calls the file system in the OS, which will remember individual sectors (or 64K groups of consecutive sectors) of the file, pretty much in the identical way that your code is implementing. Being a MRU system, it probably holds the same stuff that you are!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T15:42:58.850", "Id": "532704", "Score": "0", "body": "The point of this is creating a list that would not fit in the address space. Consider running [this example](https://bit.ly/3D3XvnQ) in 32-bit mode." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T15:45:54.717", "Id": "532706", "Score": "0", "body": "@upkajdt yes, but reading the desired value from the file in the _get_ function, without adding your own layer of cacheing, should work just as well. Try it and see if there's a performance difference." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T16:13:58.900", "Id": "532712", "Score": "0", "body": "Using the [following test](https://bit.ly/3F31ZeG) it appears that running on Windows 10, using `BigList` is at least 10 x faster than simply writing the data to a file." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T16:41:04.290", "Id": "532716", "Score": "0", "body": "[Here](https://bit.ly/3ocLsOF) I have modified the benchmark to only measure the reading time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T16:56:54.783", "Id": "532717", "Score": "0", "body": "@upkajdt So, you are saving the overhead of the system call for the read. Skip the `fstream` and use Windows API directly, and specify flags for no buffering, and set your blocksize to a multiple of 64K and read aligned blocks from the file (that will let you completely eliminate the buffering inside the OS, and do DMA direct to your buffer)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T17:31:43.263", "Id": "532719", "Score": "0", "body": "[This quick test](https://bit.ly/3D2L63d) with the Windows API appears to be even slower than using `fstream`. I'm don't know how to set the `blocksize` and google isn't helping." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T14:35:09.220", "Id": "269916", "ParentId": "269884", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T16:39:54.213", "Id": "269884", "Score": "3", "Tags": [ "c++" ], "Title": "Creating large arrays using limited amount of RAM" }
269884
<p>I wrote the following code to read out a bill from a file and then putting it into a bills-list.</p> <p>The bill contains: &quot;company&quot;, &quot;customer&quot;, Year, Month, Day, Amount, &quot;credit/debit&quot;</p> <p>Is there a nicer way using list comprehension to make this code look better?</p> <pre><code>def read_bills(file = &quot;bills.csv&quot;): &quot;&quot;&quot;Read bills from the file system 'bills.csv'&quot;&quot;&quot; # Create a list in which each bill is entered. bills = [] for line in open(file): bill = line.strip().split(',') for i in range(len(bill)): if i &gt; 1 and i &lt; 5: bill[i] = int(bill[i].strip()) elif i == 5: bill[i] = float(bill[i].strip()) else: bill[i] = bill[i].strip() bills.append(bill) return bills </code></pre> <p><a href="https://i.stack.imgur.com/RcYg5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RcYg5.png" alt="enter image description here" /></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T17:18:20.897", "Id": "532646", "Score": "0", "body": "Use Pandas? That will make this one line." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T17:27:55.467", "Id": "532647", "Score": "0", "body": "Can't use panadas unfortunately" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T17:28:53.927", "Id": "532648", "Score": "1", "body": "And why would that be? Is this for school?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T17:29:57.873", "Id": "532649", "Score": "2", "body": "Also: it's good that you've told us your columns, but can you show us the first few lines of a file?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T17:42:02.330", "Id": "532650", "Score": "0", "body": "Yes, and I added a screenshot of the first few lines of a file." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T18:01:52.770", "Id": "532652", "Score": "7", "body": "Screenshots are useless; please post a few lines of a file **as text**, including header line…." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T23:45:26.133", "Id": "532675", "Score": "1", "body": "Pandas may be a bit heavy for this but why not use the built-in Python [CSV module](https://docs.python.org/3/library/csv.html) ? It appears that you are parsing a simple CSV file so there is no need for a fancy line parsing routine. Plus, using a [DictReader](https://docs.python.org/3/library/csv.html#csv.DictReader) you could use column names. This would be so much more straightforward." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T15:52:06.247", "Id": "532708", "Score": "1", "body": "When you try to parse CSV by splitting, you are doing it wrong. Try the implementation on [this CSV](https://en.wikipedia.org/wiki/Comma-separated_values#Example)." } ]
[ { "body": "<p>The least appealing, most tedious part of the current code is the conditional\nlogic to handle data conversion. Since you're dealing with a limited number of\ncolumns, you can use a data structure to eliminate the conditionals. (In my\nexperience, smarter or more convenient/suitable data structures are often the\nmost powerful devices to simplify algorithmic logic.) For example, to parse a\nsingle line, one could write something like this:</p>\n<pre><code>def parse_line(line):\n types = (str, str, int, int, int, float, str)\n raw_vals = [val.strip() for val in line.strip().split(',')]\n return [f(val) for val, f in zip(raw_vals, types)]\n</code></pre>\n<p>And if that line-parsing function existed, the overall bill-parsing\nfunction would be pretty trivial:</p>\n<pre><code>def read_bills(file_path):\n with open(file_path) as fh:\n return [parse_line(line) for line in fh]\n</code></pre>\n<p>Don't overlook the implicit suggestion here: separate the detailed logic (line\nparsing) from larger orchestration (opening a file and processing it line by\nline). The latter can usually be quite simple, hardly worth testing or worrying\nabout too much, while the former often requires more effort to ensure\ncorrectness. Reducing the footprint of the code requiring in-depth testing\nis usually a good move to make.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T17:15:35.827", "Id": "532718", "Score": "0", "body": "I don't believe you need the `.strip()` in `line.strip().split(',')` as each value is stripped after the split." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T18:23:41.463", "Id": "532722", "Score": "0", "body": "@benh Only the no-argument form of `str.split()` includes the auto-magical behavior of also removing whitespace surrounding the delimiter. For example, do some experimenting with this: `'Foo Bar, Blah, 123'.split(',')`. Alas, further stripping is required. One could do it all in a single split by using `re.split()`, but I probably wouldn't take that route -- extra complexity with little benefit." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T18:42:35.893", "Id": "269887", "ParentId": "269885", "Score": "6" } }, { "body": "<p>Overlapping somewhat with @FMc:</p>\n<ul>\n<li>Probably should avoid making a <code>bills</code> list; just use a generator</li>\n<li>Use the built-in <code>csv</code> and <code>dataclass</code> modules to make your life easier</li>\n<li>Prefer a deserialization routine that uses column names instead of column indices.</li>\n<li>I see that you're using <code>float</code> for your billed amount but this is not appropriate. For monetary numerics use <code>Decimal</code> unless you have a very good reason.</li>\n<li>Make an actual date object out of your date fields.</li>\n</ul>\n<h2>Suggested</h2>\n<pre class=\"lang-py prettyprint-override\"><code>from csv import DictReader\nfrom dataclasses import dataclass\nfrom datetime import date\nfrom decimal import Decimal\nfrom typing import Any, TextIO, Iterator\n\n\n@dataclass\nclass BillLine:\n company: str\n customer: str\n when: date\n amount: Decimal\n\n @classmethod\n def from_dict(cls, data: dict[str, Any]) -&gt; 'BillLine':\n when = date(\n int(data['Year']),\n int(data['Month']),\n int(data['Day']),\n )\n\n amount = Decimal(data['Amount'])\n if amount &lt; 0:\n raise ValueError('Negative amount disallowed; use &quot;debit&quot;')\n\n credit = data['credit/debit']\n if credit == 'debit':\n amount = -amount\n elif credit != 'credit':\n raise ValueError(f'&quot;{credit}&quot; is an unrecognized credit state')\n\n return cls(\n company=data['company'],\n customer=data['customer'],\n when=when, amount=amount,\n )\n\n @classmethod\n def from_csv(cls, file: TextIO) -&gt; Iterator['BillLine']:\n csv = DictReader(file)\n for record in csv:\n yield cls.from_dict(record)\n\n\ndef test() -&gt; None:\n with open('bills.csv', newline='') as file:\n records = tuple(BillLine.from_csv(file))\n\n\nif __name__ == '__main__':\n test()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T00:25:00.940", "Id": "269896", "ParentId": "269885", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T16:59:48.020", "Id": "269885", "Score": "4", "Tags": [ "python", "homework" ], "Title": "Read bills from a bills.csv file" }
269885
<p>Have you ever written proxy objects, instead of using a setter and a getter method? In that case, I'm interested in your opinion on the following design for a templated proxy.</p> <p>This is a second version, after addressing comments from a <a href="https://codereview.stackexchange.com/q/245747/64513">previous review</a>; it is intended to work with C++11 or newer. Issues which have been addressed + changes:</p> <ul> <li>Support for <code>const</code> proxies.</li> <li>Move constructor.</li> <li>The getter possibly returning a reference, or some other funny type.</li> <li><code>noexcept()</code> decoration</li> <li><code>constexpr</code> decoration</li> </ul> <pre><code>#include &lt;type_traits&gt; #include &lt;utility&gt; #if __cplusplus &gt;= 201402L #define CONSTEXPR_SINCE_CPP14 constexpr #else #define CONSTEXPR_SINCE_CPP14 #endif template &lt;typename Handle, typename Getter, typename Setter&gt; class proxy { public: using getter_return_type = decltype(std::declval&lt;Getter&gt;()(std::declval&lt;Handle&gt;()) ); // Note: We assume the getter does not allow modifying the value. If it does - you don't // need the proxy in the first place. But _asserting_ this is difficult. For example, suppose // the getter returns an int*. Is the &quot;actual&quot; value an int, or an int*? We can't know that // without introducing yet another type parameter. using value_type = typename std::remove_reference&lt;typename std::remove_cv&lt;getter_return_type&gt;::type&gt;::type; CONSTEXPR_SINCE_CPP14 operator getter_return_type() const noexcept(noexcept(getter_)) { return getter_(handle_); } CONSTEXPR_SINCE_CPP14 proxy&amp; operator=(const value_type&amp; x) noexcept(noexcept(setter_)) { setter_(handle_, x); return *this; } CONSTEXPR_SINCE_CPP14 proxy&amp; operator=(value_type&amp;&amp; x) noexcept(noexcept(setter_)) { setter_(handle_, std::move(x)); return *this; } CONSTEXPR_SINCE_CPP14 proxy(Handle handle, const Getter&amp; getter, const Setter&amp; setter) noexcept : handle_(handle), getter_(getter), setter_(setter) { } protected: const Handle handle_; // Note: The handle is constant, not the referred-to element. So, _don't_ use a `T&amp;` as your Handle, or // you'll be in trouble const Getter&amp; getter_; const Setter&amp; setter_; // Note: Attempts to use just plain Getter and Setter as the types here don't work when Getter/Setter // are function types }; // Allows for template argument deduction during &quot;construction&quot; - before C++17 template &lt;typename Handle, typename Getter, typename Setter&gt; CONSTEXPR_SINCE_CPP14 proxy&lt;Handle, Getter, Setter&gt; make_proxy(const Handle&amp; handle, const Getter&amp; getter, const Setter&amp; setter) noexcept { return proxy&lt;Handle, Getter, Setter&gt;(handle, getter, setter); } </code></pre> <p>And here are a couple of examples:</p> <pre><code> template &lt;class T&gt; constexpr typename std::remove_const&lt;T&gt;::type&amp; as_non_const(T&amp; t) noexcept { return const_cast&lt;typename std::remove_const&lt;T&gt;::type&amp;&gt;(t); } // This exists in C++14, but this example is compiled with C++11 template &lt;class T&gt; constexpr typename std::add_const&lt;T&gt;::type&amp; as_const(T&amp; t) noexcept { return t; } const int&amp; my_getter(int *x) { return *x; } void my_setter(int *x, int val ) { *x = val; } class foo { public: using proxy_type = proxy&lt;int*, decltype(my_getter), decltype(my_setter)&gt;; proxy_type datum() { return make_proxy(&amp;x, my_getter, my_setter); } const proxy_type datum() const { return make_proxy(&amp;as_non_const(x), my_getter, my_setter); } protected: int x { 123 }; }; int example1() { foo my_foo; my_foo.datum() = 456; return as_const(my_foo).datum(); } double example2() { double x=1; double coef=2.; auto pr = make_proxy(&amp;x, [coef](double*x){return *x*coef;}, [coef](double*x, double nx){*x = nx/coef;}); pr = 8.; return as_const(pr); } </code></pre> <p>See it all on <kbd><a href="https://godbolt.org/z/6GG9G817h" rel="nofollow noreferrer">GodBolt</a></kbd>.</p> <p>Other than general comments, I'd appreciate help with:</p> <ul> <li>What do you think of my constexpr'ization? Is it reasonably executed? Should I even bother with it?</li> <li>Ditto regarding the use of <code>noexcept()</code>.</li> <li>Can I, and should I, make the <code>getter_</code> and <code>setter_</code> members into possibly-non-reference types?</li> <li>Is there any use to accepting the value type as an explicit template parameter?</li> <li>What if someone wants to use a <code>T&amp;</code> as the handle? i.e. use <code>x</code> as the handle in the examples rather than <code>&amp;x</code>, with appropriate getter and setter?</li> <li>What are your thoughts on comparison operators?</li> </ul>
[]
[ { "body": "<h2>std::ref to the rescue</h2>\n<p>I believe that most of the places where references are used could be replaced with value type in the class and the user could just <code>std::ref()</code> their objects/callables (in this specific case, not in general). <code>std::reference_wrapper</code> provides implicit conversion to reference type (one of the main use cases include passing references to callables for <code>std::thread</code> and <code>std::bind</code>, as it decay copies by default). The other useful part of the wrapper is call operator, e.g. <code>operator()(...args)</code>. It takes whatever arguments are passed to it and simply forwards to the wrapped object.</p>\n<p>At first glance it seems like there is undefined behavior in the example, as <code>make_proxy</code> is called with rvalues whose lifetime expires at the end of the expression, but they are still used afterwards.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T12:52:25.997", "Id": "532695", "Score": "0", "body": "1. The user should not need to know about `std::ref()` or `std::reference_wrapper()` - I don't want to complicate their life. If relevant, I would need to take care of it within the class ctor and make_proxy." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T17:52:37.913", "Id": "532720", "Score": "0", "body": "@einpoklum it a decision users have to make conscious choice about. Trying to handle it in the class will probably lead to a tag type being required to differentiate between them or providing a different overload. The class just cannot make the decision without users help. If there is anything I am missing, perhaps you could provide slightly more specific example?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T18:33:00.670", "Id": "532724", "Score": "0", "body": "\" undefined behavior in the example, as make_proxy is called with rvalues...\" <- Won't the lifetime be extended by the const-references?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T18:36:36.490", "Id": "532726", "Score": "0", "body": "\"it a decision users have to make conscious choice about. \" <- disagree. Library users don't make conscious decisions about most of what you offer them... think of std::variant for example. There are lots of architectural choices in there which users are kept in the dark about. And that's fine. For this kind of a proxy class to have general appeal, it has to be simple and straightforward to use; and I won't shy away from a tag type for differentiating different setter and getter types, if it helps make the proxy easier to use from the outside." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T18:39:45.167", "Id": "532728", "Score": "0", "body": "@einpoklum about lifetime and const reference: think of it as NRVO/RVO. If you can apply RVO, then it will be extended. When the direction is inside the function the lifetime will be equal to expression containing the function call." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T18:44:08.687", "Id": "532731", "Score": "0", "body": "@einpoklum, about usage, perhaps I’m not understanding the context of usage, that is why I asked for a more concrete example. I am of the attitude of not doing excessive hand holding and trusting the user. I will definitely try my best to protect them from mistakes where possible, but I don’t want to write an abstraction that turns into a footgun. It is very hard to create an abstraction that doesn’t leak implementation details onto the user." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T20:03:26.967", "Id": "532733", "Score": "0", "body": "Well, I'm thinking both of using this in a [project of mine](https://github.com/eyalroz/cuda-api-wrappers/) ([here](https://github.com/eyalroz/cuda-api-wrappers/blob/master/src/cuda/api/device.hpp) you can see a few get_XXX and set_XXX methods). But I'm also thinking of making it into a small library and offering it to people whose code I come to have a look at: \"What, you have a setter and getter? Don't work this way, add a proxy! It's easy!\"" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T11:13:17.060", "Id": "269906", "ParentId": "269889", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T22:00:28.077", "Id": "269889", "Score": "2", "Tags": [ "c++", "c++11", "design-patterns", "template", "proxy" ], "Title": "A proxy class as a generic replacement for getters and setters v2" }
269889
<p>I've implemented this rotate_ algorithm mimicking STL's : The algorithm left-shifts all the elements n times where n is the distance between the first element and the axis (middle):</p> <pre><code>template &lt;typename InIt&gt; InIt rotate_(InIt first, InIt Rit, InIt last){ if(first == last) return last; if(Rit == first) return first; auto tmp = Rit; while( Rit != first ){ auto it = first; while( std::next(it) != last ){ iter_swap_(it, std::next(it) ); ++it; } Rit = std::prev(Rit); } return first + distance(tmp, last); } int main(){ vector&lt;int&gt; v1{1, 2, 3, 4, 5, 6, 7, 8}; vector&lt;int&gt; v2(v1); int index = 3; auto it1 = rotate(v1.begin(), v1.begin() + index, v1.end()); auto it2 = rotate_(v2.begin(), v2.begin() + index, v2.end()); if(it1 != v1.cend()) cout &lt;&lt; *it1 &lt;&lt; &quot; : &quot; &lt;&lt; it1 - v1.cbegin() &lt;&lt; '\n'; if(it2 != v2.cend()) cout &lt;&lt; *it2 &lt;&lt; &quot; : &quot; &lt;&lt; it2 - v2.cbegin() &lt;&lt; '\n'; for(int i : v1) cout &lt;&lt; i &lt;&lt; &quot;, &quot;; cout &lt;&lt; '\n'; for(int i : v2) cout &lt;&lt; i &lt;&lt; &quot;, &quot;; cout &lt;&lt; '\n'; } </code></pre> <p>The output:</p> <pre><code>1 : 5 1 : 5 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, </code></pre> <p>The output is identical but I want to know whether there's a better implementation or some bugs in my code?</p>
[]
[ { "body": "<ul>\n<li><p><code>distance</code> is missing the <code>std::</code> qualifier.</p>\n</li>\n<li><p><code>first + ...</code> assumes a random access iterator. It is an unnecessary requirement. A bulk of the code requires bidirectional iterators only. Try to stay with them.</p>\n</li>\n<li><p>Performance-wise the algorithm has <span class=\"math-container\">\\$O(nk)\\$</span> time complexity (<span class=\"math-container\">\\$n\\$</span> being the size of the range, and <span class=\"math-container\">\\$k\\$</span> a shift amount). The worst case is of course quadratic. Meanwhile, there are linear algorithms.</p>\n</li>\n</ul>\n<p>PS: what is <code>iter_swap_</code> (with the trailing underscore)?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T09:13:34.100", "Id": "532687", "Score": "0", "body": "In fact in my code I am using 'using namespace std;' that is why i don't qualify names. `iter_swap_` is my version of `std::iter_swap` because I am implementing my STL-like library for practice purpose only. Thank you." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T00:13:18.163", "Id": "269895", "ParentId": "269890", "Score": "3" } } ]
{ "AcceptedAnswerId": "269895", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T22:09:04.547", "Id": "269890", "Score": "1", "Tags": [ "c++", "algorithm" ], "Title": "A possible implementation of std::rotate" }
269890
<p>I have been working on recreating the WP columns block using server-side rendered blocks.</p> <p>For the base creation of the block structure, I have used <code>@wordpress/create-block --template es5</code>. I believe I have got the overall operation working correctly but I am looking for input on how to improve the handling of conditionals and assigning variables, particularly in PHP.</p> <h3>An explanation of some of the block's controls in index.js</h3> <h5>Column Select</h5> <p>Fairly self-explanatory here but this will control the number of columns, as well as determine when other controls are available.</p> <h5>Margin Select</h5> <p>A radio control that assigns set margin values via a modifier class. What is selected here determines if the double margins toggle is visible.</p> <h5>Double Margins</h5> <p>A toggle/boolean that is only visible when <code>marginSelect</code> is not equal to <code>margins__none</code> or <code>margins__inContent</code>. If this value is set to true it will add a modifier class.</p> <h5>Narrow Content</h5> <p>A simple toggle/boolean that will assign a modifier to make the content narrow. Visible in all states</p> <h6>Reverse Order on Mobile</h6> <p>Another toggle that will add a modifier called <code>columns__reverse</code> if true. Available in all states.</p> <h6>Offset Columns</h6> <p>Radio controls that add a modifier class depending on its selection. Only visible when <code>columnSelect</code> value is equal to 2.</p> <pre class="lang-js prettyprint-override"><code>//index.js ( function( wp ) { var registerBlockType = wp.blocks.registerBlockType; var el = wp.element.createElement; var __ = wp.i18n.__; const { useSelect } = wp.data; const { RangeControl, RadioControl, ToggleControl, PanelBody } = wp.components; const { useBlockProps, InnerBlocks, InspectorControls } = wp.blockEditor; const allowedBlocks = [ 'wpboiler-core/column' ]; registerBlockType( 'wpboiler-core/columns', { apiVersion: 2, title: __( 'Columns', 'columns' ), description: __( 'Displays content in columns', 'columns' ), category: 'design', icon: 'schedule', supports: { html: false, }, attributes: { columnselect: { type: 'number', default: 2, }, marginSelect: { type: 'string', default: 'margins__inContent', }, marginDouble: { type: 'boolean', default: false, }, narrowContent: { type: 'boolean', default: false, }, reverseOrder: { type: 'boolean', default: false, }, columnOffset: { type: 'string', default: 'columns__offset--none' }, }, edit: function(props) { const { attributes, setAttributes, clientId } = props; const { columnselect, marginSelect, marginDouble, narrowContent, reverseOrder, columnOffset } = attributes; const onChangeColumnSelect = value =&gt; setAttributes({ columnselect: value }); const onChangeMarginSelect = value =&gt; setAttributes({ marginSelect: value }); const onChangeMarginDoubleSelect = () =&gt; setAttributes({ marginDouble: marginDouble ? false : true }); const onChangeNarrowContentSelect = () =&gt; setAttributes({ narrowContent: narrowContent ? false : true }); const onChangeReverseOrderSelect = () =&gt; setAttributes({ reverseOrder: reverseOrder ? false : true }); const onChangeOffsetSelect = value =&gt; setAttributes({ columnOffset: value }); return el( 'section', useBlockProps(attributes), __( 'Add columns by pressing the + icon. Maximum 4 columns', 'columns' ), // INSPECTOR CONTROLS BEGINS el( InspectorControls, null, el( PanelBody, { title: 'Columns Select', }, el( RangeControl, { min: 2, max: 4, value: columnselect, onChange: onChangeColumnSelect } ), ), el( PanelBody, { title: 'Margin Select' }, el( RadioControl, { selected: marginSelect, options: [ { label: 'No Margins', value: 'margins__none' }, { label: 'Basic / In-content Margins', value: 'margins__inContent' }, { label: 'Margins Top &amp; Bottom', value: 'margins__topBottom' }, { label: 'Top Margin Only', value: 'margins__top' }, { label: 'Bottom Margin Only', value: 'margins__bottom' }, ], onChange: onChangeMarginSelect } ), (marginSelect !== 'margins__none' ? (marginSelect !== 'margins__inContent' ? el( ToggleControl, { label: 'Double Margins?', checked: marginDouble, onChange: onChangeMarginDoubleSelect } ) : null) : null), ), el( PanelBody, { title: 'Styling Controls' }, el( ToggleControl, { label: 'Narrow content?', help: 'Sets the column width to match narrow text content.', checked: narrowContent, onChange: onChangeNarrowContentSelect } ), el( ToggleControl, { label: 'Reverse order on mobile?', help: 'When on mobile devices the order of stacked items will be reversed.', checked: reverseOrder, onChange: onChangeReverseOrderSelect } ), (columnselect === 2 ? el( RadioControl, { label: 'Offset columns?', help: 'For a design choice, the columns can be offset. This option is only available for 2 column layouts.', selected: columnOffset, options: [ { label: 'No offset', value: 'columns__offset--none', }, { label: '60 / 40', value: 'columns__offset--6040', }, { label: '40 / 60', value: 'columns__offset--4060', }, ], onChange: onChangeOffsetSelect } ) : null), ), ), // INSPECTOR CONTROLS END // PREVIEW AREA BEGIN el( 'div', { className: 'columns__container' }, el( InnerBlocks, { allowedBlocks: allowedBlocks, } ) ), // PREVIEW AREA END ); }, save: function() { return el(InnerBlocks.Content, {}); }, } ); }( window.wp ) ); </code></pre> <h3>An explanation of columns.php</h3> <p>I am assigning variables based on attributes passed from <code>index.php</code>. These variables are being pushed to an array called <code>$classes</code> and then echoed in the markup. Some of these have default values, and others are only assigned if certain conditions are met - to prevent unused classes/modifiers being added to the markup. I think it is here where I would look for some input and how this can be improved.</p> <pre class="lang-php prettyprint-override"><code>// columns.php function wpboiler_columns_block_init() { $dir = get_template_directory() . '/gutenberg'; $index_js = 'columns/index.js'; wp_register_script( 'wpboiler-columns-block-editor', get_template_directory_uri() . &quot;/gutenberg/$index_js&quot;, array( 'wp-block-editor', 'wp-blocks', 'wp-i18n', 'wp-element', ), filemtime( &quot;$dir/$index_js&quot; ) ); wp_set_script_translations( 'wpboiler-columns-block-editor', 'columns' ); $editor_css = 'columns/editor.css'; wp_register_style( 'wpboiler-columns-block-editor', get_template_directory_uri() . &quot;/gutenberg/$editor_css&quot;, array(), filemtime( &quot;$dir/$editor_css&quot; ) ); $style_css = 'columns/style.css'; wp_register_style( 'wpboiler-columns-block', get_template_directory_uri() . &quot;/gutenberg/$style_css&quot;, array(), filemtime( &quot;$dir/$style_css&quot; ) ); register_block_type( 'wpboiler/columns', array( 'editor_script' =&gt; 'wpboiler-columns-block-editor', 'editor_style' =&gt; 'wpboiler-columns-block-editor', 'style' =&gt; 'wpboiler-columns-block', 'render_callback' =&gt; 'wpboiler_core_columns_render' ) ); } add_action( 'init', 'wpboiler_columns_block_init' ); function wpboiler_core_columns_render( $attr, $content ) { $html = ''; $classes = array(); $classes[] = $colCount = (isset($attr['columnselect']) ? 'columns__count--' . $attr['columnselect'] : 'columns__count--2'); $classes[] = $margins = (isset($attr['marginSelect']) ? $attr['marginSelect'] : 'margins__inContent'); $classes[] = $narrowContent = (isset($attr['narrowContent']) ? 'content__narrow' : ''); $classes[] = $reverseOrder = (isset($attr['reverseOrder']) ? 'columns__reverse' : ''); if($margins != 'margins__inContent' &amp;&amp; $margins != 'margins__none' &amp;&amp; isset($attr['marginDouble'])) { $marginDouble = 'margins__double'; $classes[] = $marginDouble; } if($colCount == 'columns__count--2' &amp;&amp; isset($attr['columnOffset'])) { $columnOffset = $attr['columnOffset']; $classes[] = $columnOffset; } $html = '&lt;section class=&quot;columns ' . implode(&quot; &quot;, $classes) . '&quot;&gt; &lt;div class=&quot;columns__container&quot;&gt; ' . $content . ' &lt;/div&gt; &lt;/section&gt;'; return $html; } </code></pre> <h3>What help am I looking for?</h3> <p>I think in general some guidance on improving handling of conditional rendering, both in PHP and JS, as well as handling boolean values.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T00:07:20.120", "Id": "532677", "Score": "0", "body": "Do you know which version of PHP is running on the server(s)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T08:09:42.283", "Id": "532685", "Score": "0", "body": "At the moment it's a local development running 7.3.5. I have been using this in work environments that are defaulted as low as 7 (Seeing that information has made me think that probably needs to be changed)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T22:09:07.110", "Id": "269891", "Score": "0", "Tags": [ "javascript", "php", "wordpress" ], "Title": "Recreating WP Columns Block - Columns Container Only" }
269891
<p>Brief Background: I just started learning Android Development recently. I have some experience with programming and understand the basics of OOP but am not confident that I am using principles of OOP properly.</p> <p>In the App that I am working on, I am using a Nested RecyclerView. Since posting the code from the Actual App where this Nested RecyclerView is actually used would introduce a lot of irrelevant code, I created a sample App that addresses all the concepts that I wanted this Code Review to address without introducing other unnecessary things into the picture. I originally posted this as a question/request for recommendations on Stackoverflow but after 5 days, it has only gotten 21 view and no answers/comments, so I thought it might be more appropriate for this site.</p> <h3>What I hoped to Accomplish/The Problem</h3> <p>I needed to implement a Nested RecyclerView with onClick functionality. After reading through a lot of Stackoverflow posts with questions similar to what I was trying to do and trying out their suggestions and trying ideas from various tutorials that I found online, I was not able to find a solution that addressed all the points I needed addressed but was able to combine the ideas from different sources with my ideas to attain the functionality I needed but feel like, even though, my solution does what I need it to do, it probably is not the best solution. It feels more like a work around than something which is likely to be a best practice.</p> <p>The image below shows a <b>Parent RecyclerView(Blue)</b> which displays a list of objects. Each Object(Pink) in this list has the following properties: Seller Name, A List of Products sold by this Seller, and Subtotal(sum of (cost of product X quantity of product) for all products sold by this seller). The <b>Child RecyclerView(Yellow)</b> shows the list of Product objects. Each Product object(Aqua Blue) has properties: Name, Price, and Quantity.</p> <p>I wanted to know when a user clicks on any View used in the Nested RecyclerView. For example, if the user clicks on the text &quot;Seller 1&quot;, I want to know that they clicked on the TextView representing Seller Name in the 0th index of the List of Objects used for the Parent RecyclerView. Or if they clicked on &quot;Oranges&quot; by &quot;Seller 2&quot;, then I want to know that they Clicked on the 1st Index of the List of Objects used for the Parent RecyclerView and 0th Index of the List of Products used for Child Recycler View and the View that they clicked was the TextView which is used to display the Products name(&quot;Oranges&quot;).</p> <p>The part I was having difficulty with was, for example, when a User clicked on say Oranges by Seller 1. I would know that they clicked on the Second Item in a Child RecyclerView list, but I wouldn't know which Parent RecyclerView item this Child corresponds to. I need to know both things, the index in the Parent RecyclerView list and index in Child RecyclerView list(if the clicked View is part of the Child RecyclerView) and which View specifically was clicked.</p> <p><a href="https://i.stack.imgur.com/YodVU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YodVU.png" alt="Screenshot of the Example I made" /></a></p> <h3>The solution I came up with but am hoping you guys can help refine:</h3> <p>I implemented the View.OnClickListener interface in my ViewHolder class for both the ParentRecyclerViewAdapter and ChildRecyclerViewAdapter. I also created an abstract class called ClickReporter that is instantiated as an object expression in the Activity needing this ClickReporter and ClickReporters abstract function is provided an implementation here which basically just Logs the position clicked in Parent RecyclerView, position in child RecyclerView and the specific View in the layout that was clicked. This instance of ClickReporter is passed as a parameter to ParentRecyclerAdapter and ChildRecyclerAdapter. The parent and child RecyclerAdapter class implement the View.OnClickListener interface whose function onClick then calls a function in the instance of the ClickReporter that was passed to the parent/child RecyclerAdapter. If the View that was clicked is a View from the Parent RecyclerView adapter, then the ClickReporter class has enough information about what view was clicked, but if the View that was clicked is a View in the Child RecyclerView, then the ClickReporter class doesn't have enough information as it still needs to know which item index from the Parent RecyclerView this Child belongs to. For this, I found help from a post by someone who created a class called RecyclerItemClickListener that calls a function onItemClicked() that reports the index of the Parent RecyclerView in which the Child item was clicked. This way ClickReporter is able to know the index in the Parent RecyclerView from the onItemClicked() function call, and know the the index of which item was clicked in the Child RecyclerView and which View specifically was clicked by the onClick() function from the interface View.OnClickListener implemented by the ViewHolder class in the ChildRecyclerAdapter.</p> <p>Once ClickReporter has the information, it calls its abstract function onResult, passing in the parameters for parentPosition, childPosition, and specific view clicked. This function is implemented in the Activity/fragment that instantiated ClickReporter.</p> <p>I am not sure if creating ClickReporter as an abstract class was the best solution. Would it have been better to maybe create an interface to accomplish what I was trying to do. I wasn't able to think of a way of accomplishing what I was trying to do using an interface. I would appreciate your insight as what would be the best way to accomplish what I was trying to do and any other input you may have.</p> <p>The output of the relevant Log statements is below. I/NOTE:MA#onItemClick stands for onItemClick() that is called in MainActivity. I/NOTE:PRA#onClick stands for the onClick function that is called in<br /> ParentRecyclerAdapter. I/NOTE:CRA#onClick stands for onClick function that is called in ChildRecyclerAdapter. I/MainActivity is when ClickReporters onResult function is called giving the result I was seeking.</p> <p>The first three log statements are Logged when I clicked on &quot;Seller1&quot; in the screenshot of the App shown above. And last 3 Log statements are Logged when I click on &quot;Oranges&quot; which are being sold by Seller1.</p> <pre><code>I/NOTE:MA#onItemClick: In onItemClick w/ section pos=0, view=androidx.appcompat.widget.LinearLayoutCompat{...} I/NOTE:PRA#onClick: In PRA's VH#onClick w/ pos=0, clickedView=androidx.appcompat.widget.AppCompatTextView{...app:id/section_row_seller_name} I/MainActivity: Parent Position: 0, Child Position: -1, viewClicked: androidx.appcompat.widget.AppCompatTextView{...app:id/section_row_seller_name} I/NOTE:MA#onItemClick: In onItemClick w/ section pos=0, view=androidx.appcompat.widget.LinearLayoutCompat{...} I/NOTE:CRA:onClick: in CRA's VH#onClick w/ pos=1, clickedView=androidx.appcompat.widget.AppCompatTextView{...app:id/item_row_product_name} I/MainActivity: Parent Position: 0, Child Position: 1, viewClicked: androidx.appcompat.widget.AppCompatTextView{...app:id/item_row_product_name} </code></pre> <p>I will post the code next into the body of this CodeReview request and will also post a link so you can download the project instead of having to copy and paste the code given below: <a href="https://www.icloud.com/iclouddrive/0vadjMcAk5dQQmv8YV4NXMDcg#NestedRecyclerView" rel="nofollow noreferrer">code on iCloud</a></p> <h2>The Code</h2> <pre><code>class Order( val sellerName: String = &quot;&quot;, val productsInOrder: List&lt;Product&gt; = listOf(), val subTotal: Int = 0 ) { override fun toString(): String { return &quot;Seller:$sellerName, Products:$productsInOrder, SubTotal:$subTotal&quot; } } </code></pre> <pre><code>class Product(val titleOfProduct: String = &quot;&quot;, val priceOfProduct: Int = 0, val quantityOfProduct: Int = 0) { override fun toString(): String { return &quot;Product Name:$titleOfProduct, Price:$priceOfProduct, Quantity:$quantityOfProduct&quot; } } </code></pre> <pre><code> class MainActivity : AppCompatActivity() { lateinit var listOfOrders: List&lt;Order&gt; lateinit var clickReporter: ClickReporter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Setup Click Reporter clickReporter = object: ClickReporter() { override fun onResult(parentPos: Int, childPos: Int, viewClicked: View?) { Log.i(&quot;MainActivity&quot;,&quot;Parent Position: $parentPos, Child Position: $childPos, viewClicked: $viewClicked&quot;) } } val binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) // Set Touch Listeners for each Section in Parent RecyclerView: binding.rvParentInMainActivityLayout.addOnItemTouchListener( RecyclerItemClickListener( this, object : RecyclerItemClickListener.OnItemClickListener { override fun onItemClick(v: View?, position: Int) { Log.i(&quot;NOTE:MA#onItemClick&quot;,&quot;In onItemClick w/ section pos=$position, view=$v&quot;) clickReporter.onNestedRvItemClick(position) } } ) ) // Generate listOfOrders to use for testing RecyclerView listOfOrders = generateDataforRecyclerViewTest() // Get main Recycler View val parentRecyclerView = binding.rvParentInMainActivityLayout // Create instance on ParentRecyclerAdapter val parentRecyclerAdapter: ParentRecyclerAdapter = ParentRecyclerAdapter(listOfOrders,clickReporter) // Set the adapter to mainRecyclerView parentRecyclerView.adapter = parentRecyclerAdapter // Last Step, we need to attach a LayoutManager. Done in layout file. // Add Grand Total val grandTotalTextView: TextView = binding.tvGrandTotalInMainActivityLayout val grandTotal: Int = listOfOrders.map { it.subTotal }.sum() grandTotalTextView.setText(&quot;Grand Total: $${grandTotal}&quot;) } // Generate a List of Order objects for use in testing Nested RecyclerView fun generateDataforRecyclerViewTest(): List&lt;Order&gt; { Log.i(&quot;NOTE:MA#gdfrvt&quot;,&quot;In generateDataforRecyclerViewTest&quot;) // Create 3 instances of Product object to use in Order object val apples = Product(&quot;Apples&quot;, 3, 2) val oranges = Product(&quot;Oranges&quot;, 4, 3) val pears = Product(&quot;Pears&quot;, 4, 5) // Generate 2 Object instances using these Product instances. val applesSubtotal = apples.priceOfProduct * apples.quantityOfProduct val orangesSubtotal = oranges.priceOfProduct * oranges.quantityOfProduct val pearsSubtotal = pears.priceOfProduct * pears.quantityOfProduct val order1 = Order(&quot;Seller #1&quot;, listOf(apples, oranges), applesSubtotal + orangesSubtotal) val order2 = Order(&quot;Seller #2&quot;, listOf(oranges, pears), orangesSubtotal + pearsSubtotal) return listOf(order1,order2) } } </code></pre> <pre><code>import android.view.View abstract class ClickReporter { var childPosition:Int = -1 var parentPosition: Int = -1 var view: View? = null // The user calls this function if any view is Clicked(in parent or child RecyclerView). // If it is called from the Parent RecyclerView adapter, then fun onNestedRvClick(typeOfAdapter: String, position: Int, clickedView: View?) { if (typeOfAdapter == &quot;Parent&quot;) { view = clickedView parentPosition = position onResult(parentPosition, childPosition, clickedView) childPosition = -1 parentPosition = -1 view = null } else if (typeOfAdapter == &quot;Child&quot;) { view = clickedView childPosition = position onResult(parentPosition, childPosition, clickedView) childPosition = -1 parentPosition = -1 view = null } } // This function is called from the onItemClick() function in the Activity/Fragment that uses // an instance of this class(ClickReporter). It gets called irrespective if the user clicked on // a view in Parent RecyclerView or Child RecyclerView. // But we only need the information from the call to this function if the // user clicked on a View in the Child RecyclerView as it tells us which position in the Parent // RecyclerView was clicked. fun onNestedRvItemClick(position: Int) { parentPosition = position } // This is the function the user has to over ride in their Activity/Fragment where they will // be using ClickReporter. It lets them know which position in the Parent RecyclerView was clicked, // position in Child RecyclerView and specific view in the layout that was clicked. // If the clicked View is only present in the Parent RecyclerView then childPos will be -1. abstract fun onResult(parentPos: Int, childPos: Int, viewClicked: View?) } </code></pre> <pre><code>class RecyclerItemClickListener(context: Context?, private val mListener: OnItemClickListener?) : OnItemTouchListener { interface OnItemClickListener { fun onItemClick(view: View?, position: Int) } var mGestureDetector: GestureDetector override fun onInterceptTouchEvent(view: RecyclerView, e: MotionEvent): Boolean { val childView = view.findChildViewUnder(e.x, e.y) if (childView != null &amp;&amp; mListener != null &amp;&amp; mGestureDetector.onTouchEvent(e)) { mListener.onItemClick(childView, view.getChildAdapterPosition(childView)) } return false } override fun onTouchEvent(view: RecyclerView, motionEvent: MotionEvent) {} override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {} init { mGestureDetector = GestureDetector(context, object : SimpleOnGestureListener() { override fun onSingleTapUp(e: MotionEvent): Boolean { return true } }) } } </code></pre> <pre><code>class ChildRecyclerAdapter(val products: List&lt;Product&gt;, val clickReporter: ClickReporter): RecyclerView.Adapter&lt;ChildRecyclerAdapter.ViewHolder&gt;() { inner class ViewHolder(val itemView: View): RecyclerView.ViewHolder(itemView), View.OnClickListener { val singleItemProductNameTextView: TextView = itemView.findViewById(R.id.item_row_product_name) val singleItemProductPriceTextView: TextView = itemView.findViewById(R.id.item_row_product_price) val singleItemProductQuantityTextView: TextView = itemView.findViewById(R.id.item_row_product_quantity) val singleItemUpdateQuantityButton: Button = itemView.findViewById(R.id.btn_update_quantity) init { singleItemUpdateQuantityButton.setOnClickListener { view -&gt; onClick(view) } singleItemProductNameTextView.setOnClickListener { view -&gt; onClick(view) } singleItemProductPriceTextView.setOnClickListener { view -&gt; onClick(view) } singleItemProductQuantityTextView.setOnClickListener { view -&gt; onClick(view) } itemView.setOnClickListener(this) } override fun onClick(clickedView: View?) { Log.i(&quot;NOTE:CRA:onClick&quot;,&quot;in CRA's VH#onClick w/ pos=$adapterPosition, clickedView=$clickedView&quot;) clickReporter.onNestedRvClick(&quot;Child&quot;, adapterPosition, clickedView) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { // To create view holder, we need to inflate our item_row val layoutInflater: LayoutInflater = LayoutInflater.from(parent.context) val view: View = layoutInflater.inflate(R.layout.item_row, parent, false) val updateBtn: Button = view.findViewById(R.id.btn_update_quantity) val quantityEditTextView: TextView = view.findViewById(R.id.item_row_product_quantity) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { // First get the CartListItem at position &quot;position val productItem: Product = products[position] // Second, set all the appropriate Views in item_row holder.singleItemProductNameTextView.text = productItem.titleOfProduct holder.singleItemProductPriceTextView.text = productItem.priceOfProduct.toString() holder.singleItemProductQuantityTextView.text = productItem.quantityOfProduct.toString() } override fun getItemCount(): Int { return products.size } } </code></pre> <pre><code>class ParentRecyclerAdapter(var orderList: List&lt;Order&gt;, var clickReporter: ClickReporter): RecyclerView.Adapter&lt;ParentRecyclerAdapter.ViewHolder&gt;() { inner class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView), View.OnClickListener { val sectionSellerNameTextView: TextView = itemView.findViewById(R.id.section_row_seller_name) val sectionSubtotal: TextView = itemView.findViewById(R.id.section_row_subtotal) val childRecyclerViewContainer: RecyclerView = itemView.findViewById(R.id.rv_child_item_row) init { childRecyclerViewContainer.setOnClickListener(this) sectionSellerNameTextView.setOnClickListener { view -&gt; onClick(view) } sectionSubtotal.setOnClickListener { view -&gt; onClick(view) } itemView.setOnClickListener(this) } override fun onClick(p0: View?) { Log.i(&quot;NOTE:PRA#onClick&quot;,&quot;In PRA's VH#onClick w/ pos=${adapterPosition}, clickedView=$p0&quot;) clickReporter.onNestedRvClick(&quot;Parent&quot;, adapterPosition, p0) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { // This function should inflate the section_row layout // Get layout inflater and inflate the section_row layout val layoutInflater: LayoutInflater = LayoutInflater.from(parent.context) val view: View = layoutInflater.inflate(R.layout.section_row, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { // We want to get a section from the sectionList based on position val order: Order = orderList[position] val sectionRowSellerName: String = order.sellerName val products: List&lt;Product&gt; = order.productsInOrder val sectionRowSubtotal = order.subTotal // Next set text in the Holder for orderSellerName and orderSubtotal holder.sectionSellerNameTextView.text = sectionRowSellerName holder.sectionSubtotal.text = sectionRowSubtotal.toString() // Create a ChildRecyclerAdapter val childRecyclerAdapter: ChildRecyclerAdapter = ChildRecyclerAdapter(products, clickReporter) // Set adapter: holder.childRecyclerViewContainer.adapter = childRecyclerAdapter } override fun getItemCount(): Int { return orderList.size } } </code></pre> <h2>Layout Files:</h2> <h3>activity_main.xml:</h3> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;layout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot; xmlns:tools=&quot;http://schemas.android.com/tools&quot; tools:context=&quot;.MainActivity&quot;&gt; &lt;ScrollView android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;wrap_content&quot;&gt; &lt;LinearLayout android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;wrap_content&quot; android:orientation=&quot;vertical&quot;&gt; &lt;androidx.recyclerview.widget.RecyclerView android:id=&quot;@+id/rv_parent_in_main_activity_layout&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;wrap_content&quot; android:padding=&quot;7dp&quot; android:background=&quot;#03A9F4&quot; app:layoutManager=&quot;androidx.recyclerview.widget.LinearLayoutManager&quot; android:divider=&quot;@android:color/darker_gray&quot; android:dividerHeight=&quot;1px&quot; android:layout_marginBottom=&quot;15dp&quot; android:visibility=&quot;visible&quot;/&gt; &lt;TextView android:id=&quot;@+id/tv_grand_total_in_main_activity_layout&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:text=&quot;Grand Total $Original&quot;/&gt; &lt;/LinearLayout&gt; &lt;/ScrollView&gt; &lt;/layout&gt; </code></pre> <h3>item_row.xml:</h3> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;androidx.appcompat.widget.LinearLayoutCompat xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; xmlns:tools=&quot;http://schemas.android.com/tools&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;wrap_content&quot; android:layout_marginTop=&quot;15dp&quot; android:orientation=&quot;vertical&quot; android:background=&quot;@color/teal_200&quot;&gt; &lt;androidx.appcompat.widget.LinearLayoutCompat android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;35dp&quot; android:orientation=&quot;horizontal&quot;&gt; &lt;androidx.appcompat.widget.AppCompatTextView android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:textSize=&quot;24sp&quot; android:text=&quot;Product Name: &quot;/&gt; &lt;androidx.appcompat.widget.AppCompatTextView android:id=&quot;@+id/item_row_product_name&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:textSize=&quot;24sp&quot; tools:text=&quot;Apples&quot;/&gt; &lt;/androidx.appcompat.widget.LinearLayoutCompat&gt; &lt;androidx.appcompat.widget.LinearLayoutCompat android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;35dp&quot; android:orientation=&quot;horizontal&quot;&gt; &lt;androidx.appcompat.widget.AppCompatTextView android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:textSize=&quot;24sp&quot; android:text=&quot;Product Price: &quot;/&gt; &lt;androidx.appcompat.widget.AppCompatTextView android:id=&quot;@+id/item_row_product_price&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:textSize=&quot;24sp&quot; tools:text=&quot;5&quot;/&gt; &lt;/androidx.appcompat.widget.LinearLayoutCompat&gt; &lt;androidx.appcompat.widget.LinearLayoutCompat android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;35dp&quot; android:orientation=&quot;horizontal&quot;&gt; &lt;androidx.appcompat.widget.AppCompatTextView android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:layout_gravity=&quot;center_vertical&quot; android:textSize=&quot;24sp&quot; android:text=&quot;Product Quantity: &quot;/&gt; &lt;androidx.appcompat.widget.AppCompatTextView android:id=&quot;@+id/item_row_product_quantity&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:layout_gravity=&quot;center_vertical&quot; android:textSize=&quot;24sp&quot; tools:text=&quot;1&quot;/&gt; &lt;androidx.appcompat.widget.AppCompatButton android:id=&quot;@+id/btn_update_quantity&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;34dp&quot; android:layout_gravity=&quot;center_vertical&quot; android:text=&quot;Update&quot;/&gt; &lt;/androidx.appcompat.widget.LinearLayoutCompat&gt; &lt;/androidx.appcompat.widget.LinearLayoutCompat&gt; </code></pre> <h3>section_row.xml:</h3> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;androidx.appcompat.widget.LinearLayoutCompat xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; xmlns:tools=&quot;http://schemas.android.com/tools&quot; xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;wrap_content&quot; android:layout_marginTop=&quot;30dp&quot; android:background=&quot;@color/purple_200&quot; android:orientation=&quot;vertical&quot;&gt; &lt;androidx.appcompat.widget.LinearLayoutCompat android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;wrap_content&quot; android:orientation=&quot;horizontal&quot;&gt; &lt;androidx.appcompat.widget.AppCompatTextView android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:textSize=&quot;24sp&quot; android:text=&quot;Seller Name: &quot;/&gt; &lt;androidx.appcompat.widget.AppCompatTextView android:id=&quot;@+id/section_row_seller_name&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:textSize=&quot;24sp&quot; tools:text=&quot;John Doe&quot;/&gt; &lt;/androidx.appcompat.widget.LinearLayoutCompat&gt; &lt;androidx.recyclerview.widget.RecyclerView android:id=&quot;@+id/rv_child_item_row&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;wrap_content&quot; android:padding=&quot;7dp&quot; android:background=&quot;#FFEB3B&quot; app:layoutManager=&quot;androidx.recyclerview.widget.LinearLayoutManager&quot; android:divider=&quot;@android:color/darker_gray&quot; android:dividerHeight=&quot;1px&quot;/&gt; &lt;androidx.appcompat.widget.LinearLayoutCompat android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;wrap_content&quot; android:orientation=&quot;horizontal&quot;&gt; &lt;androidx.appcompat.widget.AppCompatTextView android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:text=&quot;Subtotal: $ &quot; android:textSize=&quot;24sp&quot;/&gt; &lt;androidx.appcompat.widget.AppCompatTextView android:id=&quot;@+id/section_row_subtotal&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:textSize=&quot;24sp&quot; tools:text=&quot;100&quot;/&gt; &lt;/androidx.appcompat.widget.LinearLayoutCompat&gt; &lt;/androidx.appcompat.widget.LinearLayoutCompat&gt; </code></pre> <p>I look forward to your suggestions/recommendations regarding my use of OOP principles, any design patterns that I could have implemented, best practices or overall anything you thought of.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T22:11:56.473", "Id": "269892", "Score": "1", "Tags": [ "object-oriented", "design-patterns", "android", "classes", "nested" ], "Title": "Android Kotlin: Main Concept: Nested RecyclerView Handling Clicks; Secondary Concept: Appropriate use of OOP concepts" }
269892
<p>This is a Python 3 module that generates random pronounceable word-like strings based on Markov Chains. It has many modes, each mode conforms to the structures of dictionary words to a degree, the two highest conforming modes use Markov Chain trees, with the output of THE highest conforming mode practically indistinguishable from real words (except the fact the result is very likely not found in dictionaries, but sometimes it does return real words...).</p> <p>Disclaimer: The Markov Chain trees are very time and memory consuming to generate, and practically impossible to generate without memoization, therefore they need to be serialized and of course they are pregenerated and serialized for later use.</p> <p>Now I have tested a bunch of serialization libraries and in short I determined that <code>pickle</code> suits the module best, because I need a pure Python (binary code) serialization format that isn't a data interchange serialization format therefore it doesn't need to worry about cross-language compatibility and doesn't need to convert the data types at all. I need the deserialized object exactly as is when it was serialized. Also I have tested the performances of all those serialization libraries I have found rigorously, and determined that <code>pickle</code> is by far the fastest.</p> <p>But pickle has a bad reputation about security and compatibility, so if you don't trust me don't unpickle the pickles, just run <code>preprocess.py</code> to regenerate the objects (and repickle them). I assure you I have not a single idea on how to manipulate pickle bytecode, I can't even read them. And the objects are pickled using Python 3.9.7 in case that's important.</p> <p>You will need this folder: <a href="https://drive.google.com/file/d/1FjIXGtbsjzf1OhsJsnLO-Ry2Sy29bn2T/view?usp=sharing" rel="nofollow noreferrer">Google Drive</a>, the script to generate pseudowords is <code>letterbased_generator.py</code>.</p> <p>The module is feature incomplete, many features aren't implemented yet, for example the chunks modes aren't implemented, and I planned add argparse to it to make it a fully functional command line utility, and add an infinite while loop to make it a shell, and add a GUI to it...</p> <p>But those currently implemented are fully functional.</p> <p>In this module there are three conditions, alternate, singlecon and letter, in alternate condition, a vowel can only be followed by a consonant, and a consonant can only be followed by a vowel, but because the specialness of the letter y, I observed it being used both as a consonant and a vowel, I consider it a semi-vowel and therefore it can be followed by any letter except itself.</p> <p>In singlecon condition, a vowel can be followed by all letters, but a consonant can only be followed by a vowel, singlecon here means in every three letters there must be exactly two vowels and a single consonant, every consonant letter must be separated from another consonant by one or two vowel letters. Y can be followed by all other 25 letters.</p> <p>In letter condition, letter y cannot follow itself. And there can't be four consecutive vowels or consonants.</p> <p>The first two conditions ensure the string cannot be unpronounceable, basically it can be completely syllabified without leaving anything behind. I have observed a bunch of syllable structures, and I have chosen the easiest definitions. A syllable in the first two conditions must contain exactly one vowel and at most two consonants, the vowel can have two letters (diphthongs) and the consonants must not be next to each other, in other words, a syllable can be V, VC, CV, and CVC.</p> <p>The first two conditions ensure the balance between consonants and vowels, the last one is less strict and allows the string to have more English resembleness.</p> <p>I have currently written three functions: <code>random_alternate</code>, <code>random_singlecon</code> and <code>weighted_pseudoword</code>.</p> <p>All functions have a bunch of default parameters, all functions allows you to specify an exact <code>length</code> (pass an int between 4 and 18), or randomly choose a length from a narrow range (pass a <code>LENGTH</code> Enum), or randomly choose from all available length.</p> <p><code>control_length</code> parameter determines, if no exact length is given, whether or not the random sampling of the length is weighted or uniform, the <code>biased_length</code> parameter determines whether the length sampling is biased towards the lower end or not.</p> <p>All three functions allows you to specify a starting string to be the beginning of the generated word. The start must be 1 to 3 letters long and meet the respective conditions.</p> <p>The first two functions generates pseudowords without using Markov chains, that is, a letter's probability of being chosen is not determined by the preceding letter, other than what the condition dictates. The letters are choosing completely at random, you can set <code>biased_first</code> to <code>True</code> to make the starting letter distribution follow that of English words (if start isn't specified). The outputs of these functions are highly random and bear little resembleness to English words. The longer they are the more gibberish they become, but the shorter ones somehow do seem like valid words in an unknown natural language.</p> <p>The third function do use Markov chains, and there are three levels, which level is used is determined by two booleans: <code>control_state</code> and <code>high_conformity</code>.</p> <p>To get the lowest level, both must be <code>False</code> The second level is reached by setting the first to <code>True</code>. The third (highest) level is reached by setting both to <code>True</code>.</p> <p>The first level keeps track of only letter preceding letter and a letter's probability is only affected by one letter before it. The second level keeps track of three letters and a letter's probability is determined by two letters before it.</p> <p>The third level is similar to the second level, the difference is that in the second level the next state doesn't actually have to occur in dictionary words after the previous state. In the third level they have to.</p> <p>The third level outputs are very English like.</p> <h2>Code</h2> <h2>tools.py</h2> <pre class="lang-py prettyprint-override"><code>import random from bisect import bisect from itertools import accumulate from typing import Any cache = dict() def weighted_choice(dic: dict) -&gt; Any: marker = id(dic) if marker not in cache: if not isinstance(dic, dict): raise TypeError('The argument of the function should be a dictionary') choices, weights = zip(*dic.items()) if set(map(type, weights)) != {int}: raise TypeError('The values of the argument must be integers') if 0 in weights: raise ValueError('The values of the argument shouldn\'t contain 0') accreted = list(accumulate(weights)) cache[marker] = (choices, accreted) else: choices, accreted = cache[marker] chosen = random.random() * accreted[-1] return choices[bisect(accreted, chosen)] traversed = dict() def traverse_tree(tree: dict, length: int, initial_tree: dict, start=None) -&gt; Any: def walker(tree: dict, chosen=list()) -&gt; Any: marker = id(tree) if marker not in traversed: if not isinstance(tree, dict): raise TypeError('The argument of the function should be a dictionary') choices = list(tree) weights = [b for a, b in choices] if set(map(type, weights)) != {int}: raise TypeError('The values of the argument must be integers') if 0 in weights: raise ValueError('The values of the argument shouldn\'t contain 0') accreted = list(accumulate(weights)) traversed[marker] = (choices, accreted) else: choices, accreted = traversed[marker] selected = random.random() * accreted[-1] key = choices[bisect(accreted, selected)] next_branch = tree[key] chosen = chosen + [key] if next_branch != 0: return walker(next_branch, chosen) else: return chosen[0][0] + ''.join(i[0][2:] for i in chosen[1:]) if start: origin = initial_tree[length] if start not in origin: raise LookupError('The initial state cannot be found in the corresponding initial state tree') obj = origin[start] if isinstance(obj, dict): start = weighted_choice(obj) key = (start, obj[start]) else: key = (start, obj) chosen = [key] return walker(tree[length][key], chosen) return walker(tree[length]) </code></pre> <h2>conditions.py</h2> <pre class="lang-py prettyprint-override"><code>from pathlib import Path import json INCLUDIR = Path(__file__).parent / 'include' IS_VOWEL = json.loads((INCLUDIR / 'is_vowel.json').read_text()) IS_CONSONANT = json.loads((INCLUDIR / 'is_consonant.json').read_text()) def alternate(x, y): return IS_VOWEL[x] != IS_VOWEL[y] def singlecon(x, y): return IS_CONSONANT[x] + IS_CONSONANT[y] &lt; 2 alternate_triplets = { (0, 0.5, 0), (0, 0.5, 1), (0, 1, 0), (0, 1, 0.5), (0.5, 0, 0.5), (0.5, 0, 1), (0.5, 1, 0), (0.5, 1, 0.5), (1, 0, 0.5), (1, 0, 1), (1, 0.5, 0), (1, 0.5, 1) } singlecon_triplets = {(0, 0, 0), (0, 0, 1), (0, 1, 0), (1, 0, 0), (1, 0, 1)} def alternate_triplet(tri): return tuple(IS_VOWEL[i] for i in tri) in alternate_triplets def singlecon_triplet(tri): return tuple(IS_CONSONANT[i] for i in tri) in singlecon_triplets def alternate_start(s): if not isinstance(s, str): raise TypeError('Argument should be a str') if len(s) not in range(1, 4): raise ValueError('Argument should have a length between one to three') l = len(s) if l == 1: return True elif l == 2: return alternate(s[0], s[1]) elif l == 3: return alternate_triplet(s) def singlecon_start(s): if not isinstance(s, str): raise TypeError('Argument should be a str') if len(s) not in range(1, 4): raise ValueError('Argument should have a length between one to three') l = len(s) if l == 1: return True elif l == 2: return singlecon(s[0], s[1]) elif l == 3: return singlecon_triplet(s) def letter_start(s): if not isinstance(s, str): raise TypeError('Argument should be a str') if len(s) not in range(1, 4): raise ValueError('Argument should have a length between one to three') return True </code></pre> <h2>letterbased_generator.py</h2> <pre class="lang-py prettyprint-override"><code>import json import pickle import random from ast import literal_eval from collections import deque, namedtuple from conditions import * from enum import Enum from math import pow from pathlib import Path from tools import weighted_choice, traverse_tree DIRECTORY = Path(__file__).parent DATADIR = DIRECTORY / 'data' def load_dict(path): text = (DATADIR / path).read_text() if path.endswith('.json'): return json.loads(text) elif path.endswith('.repr'): return literal_eval(text) def load_pickle(pkl): return pickle.loads(Path(DATADIR / pkl).read_bytes()) LETTER_FREQUENCY = load_dict('letter_frequency.json') VOWELS = 'aeiouy' CONSONANTS = 'bcdfghjklmnpqrstvwxyz' VOWEL_FREQUENCY = {k: v for k, v in LETTER_FREQUENCY.items() if k in VOWELS} CONSONANT_FREQUENCY = {k: v for k, v in LETTER_FREQUENCY.items() if k in CONSONANTS} LETTER_FIRST = load_dict('letter_first.json') ALTERNATE_INITIAL_LOW = load_pickle('alternate_tree_low_initial_states.pickle') ALTERNATE_INITIAL_HIGH = load_pickle( 'alternate_tree_high_initial_states.pickle') ALTERNATE_SECOND = load_dict('alternate_second.json') ALTERNATE_SEQUENCE = load_dict('alternate_sequence.json') ALTERNATE_TERMINAL = load_dict('alternate_terminal.json') ALTERNATE_TREE_HIGH = load_pickle('alternate_tree_high.pickle') ALTERNATE_TREE_LOW = load_pickle('alternate_tree_low.pickle') ALTERNATE_PREEND = set(ALTERNATE_SEQUENCE) - set(ALTERNATE_TERMINAL) SINGLECON_INITIAL_LOW = load_pickle('singlecon_tree_low_initial_states.pickle') SINGLECON_INITIAL_HIGH = load_pickle( 'singlecon_tree_high_initial_states.pickle') SINGLECON_SECOND = load_dict('singlecon_second.json') SINGLECON_SEQUENCE = load_dict('singlecon_sequence.json') SINGLECON_TERMINAL = load_dict('singlecon_terminal.json') SINGLECON_TREE_HIGH = load_pickle('singlecon_tree_high.pickle') SINGLECON_TREE_LOW = load_pickle('singlecon_tree_low.pickle') SINGLECON_PREEND = set(SINGLECON_SEQUENCE) - set(SINGLECON_TERMINAL) LETTER_INITIAL_LOW = load_pickle('letter_tree_low_initial_states.pickle') LETTER_INITIAL_HIGH = load_pickle('letter_tree_high_initial_states.pickle') LETTER_SECOND = load_dict('letter_second.json') LETTER_SEQUENCE = load_dict('letter_sequence.json') LETTER_TERMINAL = load_dict('letter_terminal.json') LETTER_TREE_HIGH = load_pickle('letter_tree_high.pickle') LETTER_TREE_LOW = load_pickle('letter_tree_low.pickle') LETTER_PREEND = set(LETTER_SEQUENCE) - set(LETTER_TERMINAL) Structure = namedtuple('Structure', ['Initial_Low', 'Initial_High', 'Second', 'Sequence', 'Terminal', 'Tree_High', 'Tree_Low', 'Pre_End', 'Condition']) class Mode(Enum): Alternate = Structure(ALTERNATE_INITIAL_LOW, ALTERNATE_INITIAL_HIGH, ALTERNATE_SECOND, ALTERNATE_SEQUENCE, ALTERNATE_TERMINAL, ALTERNATE_TREE_HIGH, ALTERNATE_TREE_LOW, ALTERNATE_PREEND, alternate_start) Letter = Structure(LETTER_INITIAL_LOW, LETTER_INITIAL_HIGH, LETTER_SECOND, LETTER_SEQUENCE, LETTER_TERMINAL, LETTER_TREE_HIGH, LETTER_TREE_LOW, LETTER_PREEND, letter_start) SingleCon = Structure(SINGLECON_INITIAL_LOW, SINGLECON_INITIAL_HIGH, SINGLECON_SECOND, SINGLECON_SEQUENCE, SINGLECON_TERMINAL, SINGLECON_TREE_HIGH, SINGLECON_TREE_LOW, SINGLECON_PREEND, singlecon_start) WORD_LENGTH = load_dict('word_length.repr') LENGTH_RANGE = sorted(WORD_LENGTH.keys()) TOTAL = sum(WORD_LENGTH.values()) LENGTH_DISTRIBUTION = {k: 1 - (1 - v / TOTAL) for k, v in WORD_LENGTH.items()} LMIN = LENGTH_RANGE[0] LMAX = LENGTH_RANGE[-1] LDIFF = LMAX - LMIN LNUM = LDIFF + 1 LSTEP = int(LNUM / 5) VERYSHORT, SHORT, MEDIUM, LONG, VERYLONG = ({k: v for k, v in WORD_LENGTH.items( ) if k in range(LMIN+i*LSTEP, LMIN+(i+1)*LSTEP)} for i in range(5)) def random_vowel(): return random.choice(VOWELS) def random_consonant(): return random.choice(CONSONANTS) def weighted_vowel(): return weighted_choice(VOWEL_FREQUENCY) def weighted_consonant(): return weighted_choice(CONSONANT_FREQUENCY) class RANDOM(Enum): Random = [random_vowel, random_consonant] Weighted = [weighted_vowel, weighted_consonant] class LENGTH(Enum): VeryShort = VERYSHORT Short = SHORT Medium = MEDIUM Long = LONG VeryLong = VERYLONG LALL = set(LENGTH_RANGE) | {None, *LENGTH.__members__.values()} def get_length(length, weighted_length, biased_length): if length not in LALL: raise ValueError( f'Argument `length` should be an `int` between {LMIN} and {LMAX} or `None` or `LENGTH`') if isinstance(length, LENGTH): if weighted_length: length = weighted_choice(length.value) else: length = random.choice(list(length.value)) if not length: if weighted_length: length = weighted_choice(WORD_LENGTH) if length &gt; 10 and biased_length: chance = random.random() if chance &gt;= LENGTH_DISTRIBUTION[length]: length = int(LMIN + LDIFF * pow(random.random(), 4)) else: length = random.choice(LENGTH_RANGE) if length &gt; 10 and biased_length: length = int(LMIN + LDIFF * pow(random.random(), 4)) return length def random_alternate(length=None, mode: RANDOM = RANDOM.Weighted, weighted_length=True, biased_first=False, biased_length=True, start=None) -&gt; str: length = get_length(length, weighted_length, biased_length) m = mode.value if not start: if biased_first: word = weighted_choice(LETTER_FIRST) swing = word in CONSONANTS else: swing = random.randrange(2) word = m[swing]() current_length = 1 else: if not alternate_start(start): raise ValueError('Specified string is not valid in this mode') word = start current_length = len(word) swing = IS_CONSONANT[word[-1]] while current_length &lt; length: swing = 1 - swing letter = m[swing]() if word[-1] == 'y': while letter == 'y': letter = m[swing]() word += letter current_length += 1 return word def random_singlecon(length=None, mode: RANDOM = RANDOM.Weighted, weighted_length=True, biased_first=False, biased_length=True, start=None) -&gt; str: length = get_length(length, weighted_length, biased_length) m = mode.value if not start: state = deque(maxlen=2) if biased_first: word = weighted_choice(LETTER_FIRST) else: word = m[random.randrange(2)]() state.append(IS_VOWEL[word]) current_length = 1 else: if not singlecon_start(start): raise ValueError('Specified string is not a valid starting string in this mode') word = start current_length = len(word) state = deque([IS_VOWEL[i] for i in word[-2:]], maxlen=2) two_vowels = deque([1, 1]) while current_length &lt; length: if state == two_vowels: letter = m[1]() elif state[-1] == 0: letter = m[0]() else: letter = m[random.randrange(2)]() if state[-1] == 0.5: while letter == 'y': letter = m[random.randrange(2)]() word += letter state.append(IS_VOWEL[letter]) current_length += 1 return word def weighted_pseudoword(mode: Mode, length=None, weighted_length=True, biased_length=False, control_terminal=True, control_states=False, high_conformity=False, start=None): length = get_length(length, weighted_length, biased_length) initial_low, initial_high, second, sequence, terminal, treehigh, treelow, preend, condition = mode.value three_vowels = deque([1,1,1]) three_consonants = deque([0,0,0]) if not start: state = deque(maxlen=3) first = weighted_choice(LETTER_FIRST) state.append(IS_VOWEL[first]) letter = weighted_choice(second[first]) state.append(IS_VOWEL[letter]) word = first + letter current_length = 2 else: if not condition(start): raise ValueError('Specified string is not a valid starting string in this mode') word = start current_length = len(word) letter = word[-1] state = deque([IS_VOWEL[i] for i in word], maxlen=3) def control_letter(letter, last, obj): if mode == Mode.Letter: if state == three_vowels: while IS_VOWEL[letter]: letter = weighted_choice(obj[last]) elif state == three_consonants: while not IS_VOWEL[letter]: letter = weighted_choice(obj[last]) elif state[-1] == 0.5: while letter == 'y': letter = weighted_choice(obj[last]) state.append(IS_VOWEL[letter]) return letter if not control_states: while current_length &lt; length - 1: last = letter letter = weighted_choice(sequence[last]) letter = control_letter(letter, last, sequence) word += letter current_length += 1 if control_terminal: if letter in preend: last = word[-2] word = word[:-1] while letter in preend: letter = weighted_choice(sequence[last]) letter = control_letter(letter, last, sequence) word += letter end = weighted_choice(terminal[letter]) end = control_letter(end, letter, terminal) else: end = weighted_choice(sequence[letter]) end = control_letter(end, letter, sequence) word += end return word else: if high_conformity: return traverse_tree(treehigh, length, initial_high, start) return traverse_tree(treelow, length, initial_low, start) if __name__ == '__main__': print(weighted_pseudoword(Mode.Alternate, control_states=True)) </code></pre> <h2>Example output</h2> <pre><code># Alternate menisitype conatala wagulinal caponetal penumus sexagasoles myelatory defecidevenape tonetar filitace delacesal bicatiticic salanine disarananife everiver gasem unalayere oceturaman rateryino tasisaverege unexiset hanit fucalibe deconyme caranisure recesibe # Letter suborn jacker sesque header plagrest gorgange menthial intemple euphoned shortial backener stillier inapperm sheepend antipate armophic shordery candiate swardent helicate lactogener probationidatiouse windersionicaneral comminaristeroused calatraisensingeal antisorturialissed phospecutterreness monoundrenoticated epitationanthurian disgradulouriodont activaleshinesings portunifiant sporthostery biograperted millanomised archeterlock sapophallide mounderate parch illucianic messiblene microlitic reprecarry noncellage solabritor periscoper ingraphyte quadrithen nitractick offeropous unaceoused imposteron septablent pasticator housnesian intogratic tubularate instropoda undustrily morillinal seminoman bricology anaphillo genitento plenothes interhead imperfect advisable clamarchy plumblass folianist shinelion irretical cabackler aristilic hydrocome rabberone bombasely regenesce diatorial anishinal inconsory annescene hypocrama pinnotone castrutic accessily rectionia atteritan recorphic microcent mangeropy annulough packerina slipsidic effectose ideadstor explorant pectivate fouritude gelassive pasticule perimidae monomator handecule petistify bordenose palessate filingeal undiately pillatess survescus astration merculary carenogen bluentler recensent triciatic ballisary notiallow dragmator prophoric stageless misolvert fossioned deniticky preverser gutterter congolden disatiate recollure telectron neurophic freedicer amarrower pher sting retics motosis histilic evenette dischand melanity gallouse succento bilithes convolar tribular dropoger ventoria haemical sensular tricalin trisonal comphane blassion stranose buttinge blowerer saliania wherball composis mediffle perforth pilleter enterded gentiver misenism persatic corrulin bedentic alcohere billiary cottless paragged torthorn bombiner helluric complian homophic armouser supplier apoteral siphough finiscus spletate fuminant lustaled collabic formeant bonderse prection lactiole operasse incology misapple unconder illegate centence colocula shineous mediaria colleral simicule numergic multifer convened mistolet simillus incinion acannery winderal succular replated isothala minimate copporal stoneral valering parotory metarded martival monotomy hardiate arboarse lactiver unresign flaginal unseased somnific nonautor constate granchia collaria needless chilaria labilish zinclast cornison conjunce underion creanced parabler resentic indulate mesolate misonison breverrow marmounce thoroused ophiloquy seriarily fishmento metatious decontery retragant gamentary averlando pharporic substacer sapochone freederge gentlesce steentral rubinatic stipuline cringness pasticate unfortial unveraphy ascilland retisania deparific nephagony octoratic stoneuric sulpathen consecule pharmatic bisecting pentisant circulata pasticate puriouser squantian intection wastiblet oversento philosite forthropy spareopal landantal lambolity adulattle affrancer cursenary animprely suspector ballegite prackeric alphilite nonmentry favorough maltisate intenular aborabill graptilly survenate inderachy ordinesis # 8 letters, initial sel seleopal selegram seleness selenize selesian # 8 letters, initial mel melopher melately melighty mellatic melongal melocate mellined melastic melodily melation mellular melantly melinion melicant melively melairer mellarge mellifer melaired meligate melained meliania melotone melastor melience melastic melapsis meligate melastal meliacer melatern mellopic melastry mellarge mellarin melocule meliento mellabic </code></pre> <p>How can my code be improved?</p> <h2>Update</h2> <p>Posted all the code in the relevant scripts required by the generation process, I have strictly separated code and data because the volume of the data is way too large to fit into the scripts, you still need the files if you want to test the scripts.</p> <p>Important: The data is pickled using Python 3.9.7 x64 on Windows 10, and I have comfirmed they can be unpickled by Python 3.10 x64 on Windows 10, but I don't know if it will also be able to be unpickled on Unix-like systems or 32 bit x86 CPUs (of course my computer's CPU is x86-64), you might as well run the preprocess.py, it takes around 100 seconds on my computer with Intel i5-4430 @3.00GHz CPU and 16 GiB DDR3 (8GiB x 2) Kingston RAM, give or take.</p> <p>Also important, as the commandline argument parser isn't implemented yet, you have to paste all the necessary code (minus the import local scripts part) into a running IPython or PtIPython shell to run the code, I use PtIPython and the examples are generated using the shell. DO NOT PASTE THE SCRIPTS INTO VANILLA PYTHON INTERPRETER, it will very likely raise parsing errors as many blank lines that semantically signify end of indented blocks are missing, I omitted blank lines to save space, they will be added later, I suppose.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T04:46:50.090", "Id": "269898", "Score": "2", "Tags": [ "python", "python-3.x", "random", "markov-chain" ], "Title": "Python Markov Chain based pseudoword generator" }
269898
<p>Recently I've started to learn the C programming language. This is my first program which finds zero places of quadratic formulas. Doesn't parse, just gets the discriminants, counts delta and x1, x2.</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;math.h&gt; void set_number_from_stdin(int *num, char* buf) { int final_number; do { if (!fgets(buf, 1024, stdin)) { // reading input failed break; } final_number = atoi(buf); } while (final_number == 0); *num = final_number; } int main(void) { int a, b, c, delta, deltaSqrt; float x1, x2; char buffer[1024]; printf(&quot;Quadratic Formula Calculator\n\n \ Given a function in normal form:\n \ f(x) = ax^2 + bx + c\n\n&quot;); printf(&quot;Enter the `a` determinant: &quot;); set_number_from_stdin(&amp;a, buffer); printf(&quot;Enter the `b` determinent: &quot;); set_number_from_stdin(&amp;b, buffer); printf(&quot;Enter the `c` determinent: &quot;); set_number_from_stdin(&amp;c, buffer); printf(&quot;\n \ With given determinents:\n \ a = %d, b = %d, c = %d\n\n&quot;, a, b, c); delta = b * b - 4 * a * c; printf(&quot;The discriminator: %d \n&quot;, delta); if (delta &lt; 0) { printf(&quot;Zero places are not in the set of real numbers.\n&quot;); } else if (delta == 0) { x1 = (float) -b / (2 * a); printf(&quot;Zero place: %.2f\n&quot;, x1); } else { deltaSqrt = sqrt(delta); x1 = (float) (-b + deltaSqrt) / (2 * a); x2 = (float) (-b - deltaSqrt) / (2 * a); printf(&quot;Zero places: %.2f and %.2f\n&quot;, x1, x2); } return 0; } </code></pre> <p>It's a really simple program, but I don't think I avoided some bugs, as I'm not experienced in languages like this.</p> <p>Besides, I'm really in love with these pointers. I was scared at first, but when I would write a program in a high-level language, I would return a value from a function and then modify my variable, but not anymore. Now I can send a memory... sort of, ID number and modify its value inside my function. It's brilliant. :)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T20:23:23.460", "Id": "532739", "Score": "4", "body": "While it's great that a review enabled you to improve your code, 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, as it unfortunately invalidates the existing review(s). This is not a forum where you should keep the most updated version in your question, so I rolled your changes back to the previous version. Please see see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)* for ways to announce your new code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T20:26:58.170", "Id": "532740", "Score": "1", "body": "Alright, thank you :). I thought that updating the answer with the updated code would help people which would like to learn by my mistakes. For the sake of consistency, ofc, won't do again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T20:38:02.797", "Id": "532742", "Score": "3", "body": "Feel free to post a follow-up question, or post your new code with a summary of which changes you made *and why*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T20:46:45.630", "Id": "532743", "Score": "0", "body": "Alright, thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T22:18:06.837", "Id": "532753", "Score": "0", "body": "A little edge case: what happens if a=0? Your code does not test for this special case and does division by 0 and fails to return -b/c (if b and c is not zero) or 0 (if c is zero and b is nonzero) or ill-defined if b is zero. You can either test and reject this input (as its no longer a quadratic) or return the solution if it exists." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T22:28:15.917", "Id": "532754", "Score": "0", "body": "Another minor thing: testing for delta==0 is not great when working with floats. The equation might have a double root but due to floating point errors the code might say it has 2 roots (which will be very very close). To avoid this issue you might just as well just skip this case and always print the two roots." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T18:33:16.223", "Id": "532832", "Score": "3", "body": "Not a coding, but a naming problem: `a`, `b`, `c` are *coefficients*, whereas *discriminant* (of a quadratic equation) specifically denotes the expression b²-4ac" } ]
[ { "body": "<p>Overall clear and readable. Some remarks:</p>\n<ul>\n<li><p><code>atoi</code> is one of those standard library functions that should <em>never</em> be used. It is 100% equivalent to <code>strtol</code> family of functions, except that the latter have error handling and support for other number bases than decimal.</p>\n<p>Since you are using this function on user input which has not been sanitized, you should <em>not</em> use <code>atoi</code>, because it invokes undefined behavior when the input is incorrect.</p>\n</li>\n<li><p>The error handling in case <code>fgets</code> fails should be better - you shouldn't continue execution. Similarly, when you swap out <code>atoi</code> for <code>strtol</code>, you will be able to do some more error handling as well. For simple beginner-level programs you probably just want to print an error and then <code>exit</code>.</p>\n</li>\n<li><p>There is no obvious reason why <code>buffer</code> should be allocated in the caller, since it is only used internally by the function. It would have been better off as a local variable inside the function.</p>\n</li>\n<li><p>In case you are aiming for floating point arithmetic, make it a habit to convert <em>all</em> operands in the expression to float. That eliminates the chance of accidental type-related bugs.</p>\n<pre><code>x1 = (float)-b / (2.0f * (float)a);\n</code></pre>\n<p>That is, unless the intention is do to part of the calculation in fixed point arithmetic. In such rare cases, split the expression in several lines.</p>\n</li>\n<li><p><code>deltaSqrt = sqrt(delta);</code> converts everything to fixed point integers. Is that really the intention here? Because the results will be very different compared to floating point.</p>\n</li>\n<li><p>Minor issue - using <code>\\</code> to split strings is fishy practice - it is more readable to just to let the pre-processor do automatic string literal concatenation:</p>\n<pre><code>printf(&quot;Quadratic Formula Calculator\\n\\n&quot;\n &quot;Given a function in normal form:\\n&quot;\n</code></pre>\n<p>This is 100% equivalent to <code>&quot;Quadratic Formula Calculator\\n\\nGiven a function in normal form:\\n&quot;</code></p>\n</li>\n<li><p>Minor - You are using inconsistent brace placements here: <code>int main(void) {</code>. This is likely caused by an IDE configured to use a certain style or give a default main() - if so, you might want to look up how to set the IDE to cooperate with you instead of working against you. It's a major waste of time to have a code editor spit out code formatting which doesn't correspond with your preferred style.</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T15:54:08.320", "Id": "532709", "Score": "0", "body": "Thank you for your answer so much, it helped a lot :). I figured out, that maybe keeping the descriminents, delta and it's square root as intigers is not the best idea as I would later count the zero places with a wrong number, so the result would be wrong. I made all my variables float, and also rewrote the `set_number_from_stdin` function. Updated my question with the modified code. I might return to it and work with that `scanf` function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T20:52:47.027", "Id": "532744", "Score": "3", "body": "The concatenation is done by the compiler, not the preprocessor. See this pre-processor output: https://gcc.godbolt.org/z/dEPd41hGx" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T07:20:41.850", "Id": "532779", "Score": "2", "body": "@AyxanHaqverdili It is done in translation phase 6, before phase 7 where preprocessing tokens are converted to tokens. It would be strange to say that preprocessing has ended before phase 7. However, which translation phases that \"belong\" to the pre-processor and which that \"belong\" to the compiler is muddy, especially since the pre-processor is _part_ of the compiler. It's overall not a very meaningful topic to debate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T07:22:49.000", "Id": "532780", "Score": "0", "body": "@AyxanHaqverdili As for what gcc `-E` gives, I suppose it is the output after phase 4 where all macros are expanded." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T10:54:17.833", "Id": "269905", "ParentId": "269902", "Score": "10" } }, { "body": "<p><code>set_number_from_stdin</code> has several bugs: if <code>fgets</code> fails, you assign the uninitialised variable <code>final_number</code> to <code>*num</code>. That’s undefined behaviour. In practice a compiler might assume that UB never happens, and it might thus for instance remove the <code>break</code> statement entirely.</p>\n<p>You need to <em>handle</em> the input error. Since your current function has no way of signalling an error, you’ll need to change the function prototype. One common way is to return a status code (conventionally, a value ≠ 0 signals an error):</p>\n<pre><code>int set_number_from_stdin(int *num);\n</code></pre>\n<p>(I’ve also removed the <code>buf</code> parameter — Lundin’s answer explains why having it is a bad idea.)</p>\n<p>Alternatively you might also want to return a <code>bool</code>.</p>\n<p>Note that it’s <em>not</em> sufficient for the caller of this function to test <code>errno</code>, since <code>fgets</code> does not set <code>errno</code> when it encounters EOF. If you want to use <code>errno</code>, <em>your function</em> could set <code>errno</code> in this case; but it would still be conventional to also signal success via the return value.</p>\n<p>Another bug is that your function <code>set_number_from_stdin</code> reads too much from input, and discards the buffer. This isn’t how stdin is supposed to be used. In fact, your program will fail if somebody pipes input into it. Reading stdin into a temporary buffer in this way is fundamentally a bad idea. Using <code>(f)scanf</code> would solve this issue.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T15:50:32.700", "Id": "532707", "Score": "0", "body": "Hello, thank you for your answer :). I've used `fgets` function, because I've read that usage of the `scanf` function is dangerous and can potentially create many hard to find undefined behaviours." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T16:01:52.563", "Id": "532710", "Score": "1", "body": "@Cholewka `scanf` is unsafe when used with the `%s` string format specifier, since it is vulnerable to buffer overflows in the absence of a length specifier. Conversely, using it to parse numbers is safe. Some implementations of `sscanf` additionally have a denial-of-service vulnerability, but this only affects `sscanf`, not `scanf`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T20:15:57.867", "Id": "532735", "Score": "0", "body": "Oh, that's good to know, thank you! I'm sure I won't murder myself with creating functions parsing input from stdin (which was actually pretty fun to me if you ask, for some strange reason) and just use `scanf`. :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T11:42:55.927", "Id": "269907", "ParentId": "269902", "Score": "6" } }, { "body": "<p>You should know that <code>double</code> is the <em>normal</em> floating-point type, and <em>float</em> is half sized and should only be used where you really need to save the space.</p>\n<p>Your program is mostly dealing with reading input, which is not the problem you came to solve! A real utility program would take command line arguments, not prompt the user to type things. That is, you might issue the command <code>prompt&gt; ./quadform 34 -18.2 87</code> No retries to worry about; just an error if the args don't parse properly.</p>\n<p>You should put the real work in a function, not directly in main. Then you can call it from testing code with built-in values that runs automatically. Right now you have to re-type all your tests every time you re-test after a change! Put the input and output in separate functions too.</p>\n<p>Don't use in/out parameters. Your <code>set_number_from_stdin</code> has a perfectly good return value that's not even being used, so why is it functioning by changing the parameter?</p>\n<p>Declare variables where you need them, not all at the top. This has been the standard in C for over twenty years now.</p>\n<p>E.g. <code>const double delta = b * b - 4 * a * c;</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T20:14:46.200", "Id": "532734", "Score": "0", "body": "Hello, thank you for your advices! I've taken some time to create a program taking parameters as you've suggested and pasted it into my question aswell, but I don't think that's the best way I've wrote this. Something tells me that it can be buggy, but overall I'm happy with the result, as the program is easier to test providing a function which returns the results of algebra equations. Oh, also, I'm not sure that's the best way to return an array of doubles, but that's the way I found it on some SO page." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T20:17:26.517", "Id": "532736", "Score": "0", "body": "I don't have time for a detailed essay, but in general when you want to return something complicated, use a `struct`. In this case, it would contain an int with the number of roots (0,1,2) and an array of two values, some of which will be populated based on the first field." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T20:21:04.870", "Id": "532737", "Score": "0", "body": "I'd definitely take a look at this approach, thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T20:21:15.687", "Id": "532738", "Score": "0", "body": "The problem with returning a pointer to a static array is that the function is not thread-safe or re-enterent, and you can't call it again before copying the result out since the subsequent call will overwrite. `int size = sizeof zero_places / sizeof *zero_places;` that will not work: `zero_places` is not an array but a pointer, and the right value is only available at run-time anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T21:17:13.113", "Id": "532746", "Score": "0", "body": "I took this approach in a summary listed below. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T02:19:19.863", "Id": "532861", "Score": "0", "body": "Although a good point to declare when needed, a down-side to `const double delta = b * b - 4 * a * c` is OP (questionably) uses `int a, b, c`. To preserve precision and avoid overflow, code could use `1LL * b * b - 4LL * a * c` ." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T17:25:48.993", "Id": "269926", "ParentId": "269902", "Score": "4" } }, { "body": "<h2>Result</h2>\n<p>Thank you all for your answers. :) I think I've come to a really satisfactory result to me. I've learned a lot. In this stadium I think I'm done with this program unless there's some bug I don't know about (may be, if I know myself).</p>\n<p>Rewrote the original program to making it a running script instead of reading the result from <code>stdin</code>. Used struct to organise my result.</p>\n<p>It was fun to me to write it and I hope you have honed your C/C++ skills, too. :) Thank you all for your answers once again! You guys are absolute chads.</p>\n<h2>Source code</h2>\n<pre class=\"lang-c prettyprint-override\"><code>#include &lt;stdio.h&gt;\n#include &lt;ctype.h&gt;\n#include &lt;math.h&gt;\n#include &lt;stdlib.h&gt;\n\ndouble string_to_double(char* str)\n{\n double returned_float;\n char *endptr;\n\n returned_float = strtod(str, &amp;endptr);\n\n if (str == endptr)\n {\n printf(&quot;error: Enter parameters in as digits.\\n&quot;);\n exit(1);\n }\n\n // prevent junk at the end\n if (*endptr != 0)\n {\n printf(&quot;error: Enter parameters as only digits.\\n&quot;);\n exit(1);\n }\n\n return returned_float;\n}\n\ntypedef struct Roots\n{\n int n;\n double roots[2];\n} Roots;\n\nRoots find_zero_places(double a, double b, double c)\n{\n const double DELTA = b * b - 4 * a * c;\n printf(&quot;The discriminator: %.1f\\n&quot;, DELTA);\n\n Roots root_result;\n \n if (DELTA &gt; 0)\n {\n const double DELTA_SQRT = sqrt(DELTA);\n\n root_result.n = 2;\n root_result.roots[0] = ( -b + DELTA_SQRT ) / ( 2.0f * a );\n root_result.roots[1] = ( -b - DELTA_SQRT ) / ( 2.0f * a) ;\n }\n else if (DELTA == 0)\n {\n root_result.n = 1;\n root_result.roots[0] = -b / (2.0f * a);\n }\n else\n {\n root_result.n = 0;\n }\n\n return root_result;\n}\n\nvoid print_results(Roots *root_results)\n{\n if (root_results-&gt;n == 0)\n {\n printf(&quot;Zero places are not in the set of real numbers.\\n&quot;);\n }\n else\n {\n printf(&quot;Zero place(s): &quot;);\n\n for (int i = 0; i &lt; root_results-&gt;n; i++)\n {\n if (i != 0)\n printf(&quot;, &quot;);\n\n printf(&quot;%.1f&quot;, root_results-&gt;roots[i]);\n }\n\n printf(&quot;\\n&quot;);\n }\n}\n\nint main(int argc, char *argv[])\n{\n double a, b, c;\n\n if (argc &lt; 4)\n {\n printf(&quot;Please enter a, b and c parameter.\\n&quot;);\n exit(1);\n }\n else\n {\n if (argv[1])\n {\n a = string_to_double(argv[1]);\n\n if (a == 0)\n {\n printf(&quot;When a = 0 the function is not quadratic.\\n&quot;);\n exit(1);\n }\n }\n if (argv[2])\n b = string_to_double(argv[2]);\n if (argv[3])\n c = string_to_double(argv[3]);\n\n Roots root_results = find_zero_places(a, b, c);\n print_results(&amp;root_results);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T21:52:24.557", "Id": "532752", "Score": "6", "body": "Perhaps you should post a new question, quadratic formula calculator code version 2. Your revision still has a lot of issues =)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T07:09:37.243", "Id": "532777", "Score": "0", "body": "@chux-ReinstateMonica hello, thank you for pointing these issues :). I've updated the code above with some patches. E.g checking if the a == 0. It fixes (I believe) the arithmethic issues." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T20:05:40.757", "Id": "532839", "Score": "0", "body": "In `if (argv[3]) c = string_to_double(argv[3]);` what will be the value of `c` if the condition is not met? Can the program continue sensibly after that? Can that condition ever be false?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T02:22:51.827", "Id": "532862", "Score": "0", "body": "@ilkkachu Given the code change to `if (argc < 4)`, `argv[1], argv[2], argv[3]` will not be `NULL`. (Yes, if `argv[3]` was, somehow, `NULL`, `c` would be indefinite with the `find_zero_places(a, b, c);` call.)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T20:51:32.620", "Id": "269934", "ParentId": "269902", "Score": "0" } }, { "body": "<p><strong>Consider <code>double</code></strong></p>\n<p>Rather than <code>int</code> and <code>float</code> objects, consider <code>double</code>.</p>\n<p><strong>Printing floating point</strong></p>\n<p>Use <code>&quot;%e&quot;</code> or <code>&quot;%g&quot;</code> to see more information. <code>&quot;%f&quot;</code> prints many large values with dozens of uninformative digits. <code>&quot;%f&quot;</code> prints small values as 0.000000. Using <code>&quot;%f&quot;</code> takes the <em>float</em> out of floating point.</p>\n<pre><code>// suggestions if using float math, \nprintf(`&quot;%.8e\\n&quot;, x1);\nprintf(`&quot;%.9g\\n&quot;, x1);\n// if using double math, \nprintf(`&quot;%.16e\\n&quot;, x1);\nprintf(`&quot;%.17g\\n&quot;, x1);\n</code></pre>\n<p><strong>Prevent severe loss of precession</strong></p>\n<p>When <code>|b|</code> is near the value of <code>deltaSqrt</code>, then one of <code>-b +/- deltaSqrt</code> loses many common leading digits. Result is an imprecise <code>x1</code> or <code>x2</code>.</p>\n<p>To avoid that, recall <code>a(x-x1)(x-x2) == a*x*x + b*x + c</code>, so <code>a*x1*x2 = c</code>.</p>\n<pre><code>// int a, b, c, delta, deltaSqrt;\n...\n// x1 = (float) (-b + deltaSqrt) / (2 * a);\n// x2 = (float) (-b - deltaSqrt) / (2 * a);\n// printf(&quot;Zero places: %.2f and %.2f\\n&quot;, x1, x2);\n\nint a, b, c;\nfloat delta, deltaSqrt;\n\n if (b &lt; 0) {\n x1 = (-(float)b + deltaSqrt) / (2.0f * a);\n x2 = c/(a*x1); \n } else if (b &gt; 0) {\n x2 = (-(float)b - deltaSqrt) / (2.0f * a);\n x1 = c/(a*x2); \n } else {\n x1 = +deltaSqrt / (2.0f * a);\n x2 = -deltaSqrt / (2.0f * a);\n } \n</code></pre>\n<p>This approach does not harm results when <code>|b|</code> is far from <code>deltaSqrt</code>.</p>\n<p><strong><code>float</code> mixed with <code>double</code></strong></p>\n<p>Use either <code>float</code> constants/functions or <code>double</code> ones. Convert to FP before negating an <code>int</code> to avoid UB of <code>-INT_MIN</code>.</p>\n<pre><code> //x1 = (float) -b / (2 * a);\n //...\n // deltaSqrt = sqrt(delta);\n\n // float\n x1 = -(float)b / (2.0f * a); // add f\n ...\n deltaSqrt = sqrtf(delta); // add f\n\n // double\n x1 = -(double)b / (2.0 * a);\n ...\n deltaSqrt = sqrt(delta); //no f\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T04:35:07.013", "Id": "269937", "ParentId": "269902", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T08:29:17.897", "Id": "269902", "Score": "12", "Tags": [ "beginner", "c", "calculator" ], "Title": "My first C program: quadratic formula calculator code" }
269902
<p><strong>EDIT</strong>: Updated version available here: <a href="https://codereview.stackexchange.com/questions/269950/a-counting-loop-class-v2">A counting loop class v2</a></p> <p>Ranges (C++20) aren't quite ready, so until then, I needed a reliable counting loop class that ​works fairly well to replace the old-style <code>for</code> loops:</p> <pre class="lang-cpp prettyprint-override"><code>for (int i = x; i &lt;= y; ++i) </code></pre> <p>With a simple <code>foreach</code> loop:</p> <pre class="lang-cpp prettyprint-override"><code>for (int i: loop (x, y)) </code></pre> <p>As implemented, it is inclusive for start value and end value.</p> <p>Algorithms are supported by having all the typedefs needed for a <code>contiguous_iterator</code>.</p> <p>Here is the class:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iterator&gt; template &lt;class T&gt; class loop { public: class iterator { public: using value_type=std::remove_cv_t&lt;T&gt;; using difference_type=value_type; using pointer=T*; using reference=T&amp;; using iterator_category=std::random_access_iterator_tag; using iterator_concept=std::contiguous_iterator_tag; using self_type=iterator; iterator(T x) : curr{x} {} T operator*() { return curr; } iterator&amp; operator++() { curr++; return *this; } bool operator==(const iterator&amp; rhs) const { return curr == rhs.curr; } difference_type operator-(const iterator&amp; rhs) { return curr-rhs.curr; } private: T curr; }; loop(T x, T y) : front{x}, back{y} {} iterator begin() { return front; } iterator end() { return back + 1; } private: T front; T back; }; </code></pre> <p>And some usage examples:</p> <pre><code>int foo(int x, int y) { int sum=0; for (auto z : loop(x, y)) { sum+=z; } return sum; } #include &lt;algorithm&gt; int goo(int x, int y, int z) { loop range(x,y); auto f=std::find(range.begin(), range.end(), z); if (f != range.end()) { return *f; } return x-1; } int ggg() { return goo(3, 37, 17); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T09:08:46.353", "Id": "532686", "Score": "0", "body": "What's \"not ready\" about the Ranges library? It seems pretty workable to me." } ]
[ { "body": "<p>We currently accept non-numeric types such as other iterators - is that intended?</p>\n<hr />\n<p>I'm not convinced this is a good choice when <code>T</code> is unsigned:</p>\n<blockquote>\n<pre><code> using difference_type=value_type;\n</code></pre>\n</blockquote>\n<p>We probably want to use <code>std::make_signed_t&lt;value_type&gt;</code>. Or perhaps even <code>std::make_signed_t&lt;std::common_type_t&lt;int,value_type&gt;&gt;</code> so we don't have truncating conversion with smaller types (which get promoted to <code>int</code>).</p>\n<hr />\n<p>Unless I'm mistaken, an iterator is required to support both preincrement and postincrement, so we need <code>operator++(int)</code> as well (this one returns a new iterator, of course).</p>\n<hr />\n<p>Since the iterator type is actually also the const iterator, we can declare <code>begin()</code> and <code>end()</code> as <code>const</code>.</p>\n<p>Consider also providing <code>front()</code> and <code>back()</code> - you'll want to re-name the private members (perhaps <code>first</code> and <code>last</code>?).</p>\n<hr />\n<p>Possible enhancement: consider also supporting a <code>step</code> increment between values (default 1).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T04:53:36.987", "Id": "532768", "Score": "0", "body": "Thanks, been working on your suggestions and adding `step` -- also you can see the issue with ranges in clang there (\"ranges aren't ready\") its wrapped with an `#if 0` -- https://godbolt.org/z/Px3nfYqPx" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T13:41:13.700", "Id": "269912", "ParentId": "269903", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T08:41:52.060", "Id": "269903", "Score": "0", "Tags": [ "c++", "iterator" ], "Title": "A simple counting loop class" }
269903
<h2>Use case</h2> <p>I have a site that (at peak time) will serve 1000 requests per second. Each request should trigger a record in an SQL Server database table.</p> <h2>Requirements</h2> <ol> <li>The request must not fail, even though the writing to the database could fail.</li> <li>The user should not wait for the writing to the database</li> <li>Writing to the database should happen as fast as possible, still respecting 1. and 2. Writing should be allowed to happen in bulk, even though records are added individually to the queue.</li> </ol> <h2>My approach</h2> <p>My approach aims at using a background queue with a single thread, that will create the records in the database in bulk (using table valued parameters), which can perform 10.000+ writes per second. Using a single thread will prevent SQL connection pool starvation and local TCP port starvation. Furthermore SQL Server will perform much better compared to writing single lines individually.</p> <h2>Usage of the Memory Queue</h2> <p>I have made a general implementation that is not bound to the specific use case with a database writing of visits.</p> <p>I am using ASP.net 5 but setting up the queue and injecting it in the controller will be left out here. I will just stick to the raw usage of the queue.</p> <h3>Creating a queue</h3> <pre><code>var memoryQueue = new MemoryQueue&lt;MyQueueElementType&gt;( handler: elementList =&gt; { */ elementList will contain 1....maxBulkSize elements /* }, maxBulkSize: 10); memoryQueue.StartListening(); // This will start the internal thread </code></pre> <h3>Actual case with writing to a database</h3> <pre><code>var memoryQueue = new MemoryQueue&lt;Visit&gt;( handler: elementList =&gt; visitRepo.WriteInBulk(elementList), maxBulkSize: 10); memoryQueue.StartListening(); // This will start the internal thread </code></pre> <h3>Adding to the queue</h3> <pre><code>memoryQueue.AddAsync(new Visit(ip: &quot;1.2.3.4&quot;)); // The visit details have been left out to avoid noise. </code></pre> <p>The <code>AddAsync</code> call will return a task that completes, once the added item is part of a bulk handling. In the actual web calls, these tasks will not be awaited due to requirement 2, but it is still nice to be able to await the tasks when timing unit-test actions.</p> <h2>The implementation</h2> <p>And now to the thing that I would really like people to comment on; the implementation. I have using a <code>BlockingCollection</code> as my queue internally and a single thread reacting when at least 1 element is in this queue:</p> <h2>Interface</h2> <pre><code>public interface IMemoryQueue&lt;T&gt; : IDisposable { void StartListening(); Task AddAsync(T element); Task ShutdownAsync(); } </code></pre> <h2>Class</h2> <pre><code>public class MemoryQueue&lt;T&gt; : IMemoryQueue&lt;T&gt; { private readonly BlockingCollection&lt;MemoryElementWrapper&lt;T&gt;&gt; _queue; private readonly Action&lt;IEnumerable&lt;T&gt;&gt; _handler; private readonly int _maxBulkSize; private readonly ICommonLog _log; private readonly Type _messageType; public ThreadState InternalThreadState =&gt; _thread?.ThreadState ?? ThreadState.Unstarted; private Thread _thread = null; private TaskCompletionSource&lt;object&gt; _threadCompleteTaskSource = new TaskCompletionSource&lt;object&gt;(); private CancellationTokenSource _disposeCancelTokenSource = new CancellationTokenSource(); public MemoryQueue(Action&lt;IEnumerable&lt;T&gt;&gt; handler, int maxBulkSize, ICommonLogProvider logProvider) { _handler = handler ?? throw new ArgumentNullException(nameof(handler)); _maxBulkSize = maxBulkSize; _queue = new BlockingCollection&lt;MemoryElementWrapper&lt;T&gt;&gt;(); _log = logProvider.GetLog(GetType()); _messageType = typeof(T); } public void StartListening() { if (_thread != null) throw new ArgumentException(&quot;Start listening may only happen once&quot;); // This call will block until the thread has actually started to ensure MemoryQueue.InternalThreadState to always return 'Running' immediately after calling this method. var threadStartEvent = new ManualResetEvent(initialState: false); _thread = new Thread(new ThreadStart(() =&gt; { // Signal that thread has now started. This is used for the &quot;StartListening&quot; call to block until it is certain that thread thread has actually been started. threadStartEvent.Set(); try { _log.Warn($&quot;Thread processing messages of type {_messageType.FullName} has started&quot;); while (!_queue.IsCompleted) { // FetchAtLeastOneBlocking will block until at least 1 element can be fetched. If more element are available, up to _maxBulkSize will be returned. List&lt;MemoryElementWrapper&lt;T&gt;&gt; elementWrappers = _queue.TakeAtLeastOneBlocking(maxCount: _maxBulkSize, log: _log, cancellationToken: _disposeCancelTokenSource.Token); // Get elements var elements = elementWrappers.Select(wrapper =&gt; wrapper.Element).ToList(); // process try { _handler(elements); CompleteTasks(elements: elementWrappers); } catch (Exception ex) { _log.Fatal($&quot;Unexpected exception processing {elements.Count} of type {_messageType.FullName}. Entry data: {JsonSerializeSafe(elements)}&quot;, ex); FaultTasks(elements: elementWrappers, exceptionToSetOnTasks: ex); } } // Can reach this in case of queue ended } catch (InvalidOperationException ex) { // Queue has been completed // Sanity check and alarm if needed if(_queue.Count &gt; 0) { _log.Fatal($&quot;InvalidOperationException thrown, but {_queue.Count} elements still in queue. This is unexpected behaviour.&quot;); CompleteQueueAndFaultAllPendingTasks(exceptionToSetOnTasks: ex); } } catch (OperationCanceledException ex) { // Dispose has been called CompleteQueueAndFaultAllPendingTasks(exceptionToSetOnTasks: ex); } catch(Exception ex) { // Totally unexpected error happened in queue loop logic, unrelated to the handler. // This is a unrecoverable case and requires the memory queue to be restarted (by restarting the entire application) _log.Fatal($&quot;Internal thread in MemoryQueue {GetType().FullName} experienced an unexpected exception. The thread is no longer running. This can only be recovered by restarting the entire application.&quot;, ex); CompleteQueueAndFaultAllPendingTasks(exceptionToSetOnTasks: ex); } finally { _threadCompleteTaskSource.SetResult(null); _queue.Dispose(); _log.Warn($&quot;Thread processing messages of type {_messageType.FullName} has stopped&quot;); } // Whenever the thread is done, if any elements are still on the queue, the corresponding tasks should be notified to not let any awaiters hang. })); _thread.Start(); // Wait for thread to actually spin up threadStartEvent.WaitOne(); } private void CompleteTasks(List&lt;MemoryElementWrapper&lt;T&gt;&gt; elements) { foreach (var element in elements) { element.TaskCompletionSource.SetResult(true); } } private void FaultTasks(List&lt;MemoryElementWrapper&lt;T&gt;&gt; elements, Exception exceptionToSetOnTasks) { foreach (var element in elements) { element.TaskCompletionSource.SetException(exceptionToSetOnTasks); } } private void CompleteQueueAndFaultAllPendingTasks(Exception exceptionToSetOnTasks) { if(!_queue.IsAddingCompleted) _queue.CompleteAdding(); FaultTasks(elements: _queue.TakeAvailableNonBlocking(maxCount: int.MaxValue, log: _log), exceptionToSetOnTasks: exceptionToSetOnTasks); } private string JsonSerializeSafe(object obj) { try { return JsonConvert.SerializeObject(obj); }catch(Exception ex) { _log.Fatal(&quot;Unexpected error serializing object&quot;, ex); return $&quot;(Unexpected error serializing object. Exception message: {ex.Message})&quot;; } } public Task AddAsync(T element) { // Due to race conditions, either the thread state will not be running or the queue has been completed but the thread is not yet done. In this case, this particular guard will pass but the Add call below will throw and InvalidOperationException if (InternalThreadState != ThreadState.Running) throw new AddNotAllowedException($&quot;Cannot add element as the state of the queue is {InternalThreadState}&quot;); var wrapper = new MemoryElementWrapper&lt;T&gt;(item: element); try { _queue.Add(wrapper); } catch (InvalidOperationException) { throw new AddNotAllowedException($&quot;Queue is no longer accepting new elements&quot;); } return wrapper.TaskCompletionSource.Task; } public Task ShutdownAsync() { _queue.CompleteAdding(); // Tells the thread that no more elements will be added. This will trigger the thread to stop when the queue is empty return _threadCompleteTaskSource.Task; } public void Dispose() { // Signal to the listening thread to stop everything. Calling dispose on the queue directly here proved to be subject to deadlocks where the waiting thread would just hang forever. _disposeCancelTokenSource.Cancel(); } public Task AwaitThreadToStopRunning_ForUseInUnitTestsOnlyAsync() { return _threadCompleteTaskSource.Task; } } public class AddNotAllowedException : Exception { public AddNotAllowedException(string message) : base(message) { } } public class MemoryElementWrapper&lt;T&gt; { public TaskCompletionSource&lt;object&gt; TaskCompletionSource { get; set; } public T Element { get; set; } public MemoryElementWrapper(T item) { TaskCompletionSource = new TaskCompletionSource&lt;object&gt;(); Element = item; } } </code></pre> <h2>Unit tests</h2> <pre><code> public class MemoryQueueTest : UnitTestBase { [Fact] public void StartListening_CallTwice_ExpectException_Test() { using (var memoryQueue = new MemoryQueue&lt;UnitTestMessage&gt;(messages =&gt; { }, maxBulkSize: 5, LogProvider)) { memoryQueue.StartListening(); Assert.Throws&lt;ArgumentException&gt;(() =&gt; memoryQueue.StartListening()); Assert.Throws&lt;ArgumentException&gt;(() =&gt; memoryQueue.StartListening()); } } [Fact] public void AddAsync_WithoutListenerStarted_ExpectException_Test() { using (var memoryQueue = new MemoryQueue&lt;UnitTestMessage&gt;(messages =&gt; { }, maxBulkSize: 5, LogProvider)) { Action action = () =&gt; memoryQueue.AddAsync(new UnitTestMessage(&quot;some val&quot;)); Assert.Throws&lt;AddNotAllowedException&gt;(action); } } [Fact] public void AddAsync_AfterDisposed_ExpectException_Test() { using (var memoryQueue = new MemoryQueue&lt;UnitTestMessage&gt;(messages =&gt; { }, maxBulkSize: 5, LogProvider)) { Action action = () =&gt; memoryQueue.AddAsync(new UnitTestMessage(&quot;some val&quot;)); memoryQueue.Dispose(); Assert.Throws&lt;AddNotAllowedException&gt;(action); } } [Fact] public void AddAsync_AfterShutdown_ExpectExceptionInSyncCall_Test() { using (var memoryQueue = new MemoryQueue&lt;UnitTestMessage&gt;(elements =&gt; { }, maxBulkSize: 1, LogProvider)) { memoryQueue.StartListening(); var task = memoryQueue.ShutdownAsync(); Assert.Throws&lt;AddNotAllowedException&gt;((Action)(() =&gt; memoryQueue.AddAsync(new UnitTestMessage(&quot;val1&quot;)))); } } [Fact] public async void Dispose_EnsureQueueIsStoppedAndThreadIsStopped_AndAllPendingTasksWillBeFaulted_Test() { var msg1 = new UnitTestMessage(&quot;1&quot;); var msg2 = new UnitTestMessage(&quot;2&quot;); var msg3 = new UnitTestMessage(&quot;3&quot;); var msg4 = new UnitTestMessage(&quot;4&quot;); var msg5 = new UnitTestMessage(&quot;5&quot;); var handlerStartEvent = new ManualResetEvent(initialState: false); var handlerEndEvent = new ManualResetEvent(initialState: false); using (var memoryQueue = new MemoryQueue&lt;UnitTestMessage&gt;(messages =&gt; { handlerStartEvent.Set(); handlerEndEvent.WaitOne(); }, maxBulkSize: 2, LogProvider)) { memoryQueue.StartListening(); // Add 5 messages var task1 = memoryQueue.AddAsync(msg1); var task2 = memoryQueue.AddAsync(msg2); var task3 = memoryQueue.AddAsync(msg3); var task4 = memoryQueue.AddAsync(msg4); var task5 = memoryQueue.AddAsync(msg5); // Wait until first batch is executed handlerStartEvent.WaitOne(); // Now we know that the handler is being called and the worker thread is being blocked. // At this point we call dispose and then ensure that current tasks are completed but following tasks are faulted memoryQueue.Dispose(); // After disposing we allow the handler to proceed handlerEndEvent.Set(); await task1.ThrowIfTimeout(timeout: TimeSpan.FromSeconds(5)); await task2.ThrowIfTimeout(timeout: TimeSpan.FromSeconds(5)); await Assert.ThrowsAsync&lt;OperationCanceledException&gt;(() =&gt; task3.ThrowIfTimeout(TimeSpan.FromSeconds(5))); await Assert.ThrowsAsync&lt;OperationCanceledException&gt;(() =&gt; task4.ThrowIfTimeout(TimeSpan.FromSeconds(5))); await Assert.ThrowsAsync&lt;OperationCanceledException&gt;(() =&gt; task5.ThrowIfTimeout(TimeSpan.FromSeconds(5))); // Now we will busy loop until the internal thread expectedly ends up in 'Stopped' state. var stopwatch = System.Diagnostics.Stopwatch.StartNew(); while (ThreadState.Stopped != memoryQueue.InternalThreadState) { await Task.Delay(TimeSpan.FromMilliseconds(100)); if(stopwatch.Elapsed &gt; TimeSpan.FromSeconds(5)) throw new Exception(&quot;Thread blocking state: &quot; + ThreadState.Stopped); } } } [Fact] public async void BeginShutdown_EnsureQueueIsEmptiedAndThenThreadIsStopped_Test() { var msg1 = new UnitTestMessage(&quot;val1&quot;); var msg2 = new UnitTestMessage(&quot;val2&quot;); var msg3 = new UnitTestMessage(&quot;val3&quot;); var handlerStartedEvent = new ManualResetEvent(initialState: false); var handlerCompleteEvent = new ManualResetEvent(initialState: false); var elementsProcessed = new List&lt;UnitTestMessage&gt;(); using (var memoryQueue = new MemoryQueue&lt;UnitTestMessage&gt;(elements =&gt; { elementsProcessed.AddRange(elements); handlerStartedEvent.Set(); handlerCompleteEvent.WaitOne(); }, maxBulkSize: 1, LogProvider)) { memoryQueue.StartListening(); // Add 3 elements var task1 = memoryQueue.AddAsync(msg1); var task2 = memoryQueue.AddAsync(msg2); var task3 = memoryQueue.AddAsync(msg3); // Now trigger the shutdown and wait a second to ensure that the thread is actually blocked in the handlerStartedEvent.WaitOne(); // Ensure thread is actually in the middle of calling the handler write now Assert.Single(elementsProcessed); // Sanity testing // Now stop the actual queue var shutdownTask = memoryQueue.ShutdownAsync(); handlerCompleteEvent.Set(); // Unfreeze the thread // Ensure all elements in the queue are processed await shutdownTask; // Ensure awaiting all 3 tasks will complete await task1; await task2; await task3; // Ensure all processed Assert.Equal(3, elementsProcessed.Count); Assert.Contains(msg1, elementsProcessed); Assert.Contains(msg2, elementsProcessed); Assert.Contains(msg3, elementsProcessed); // Ensure thread is stopped Assert.Equal(ThreadState.Stopped, memoryQueue.InternalThreadState); } } [Fact] public async void AddAsync_EnsureExecuteInBackground_WithResult_ExpectTaskSuccess_Test() { var jobStartEvent = new ManualResetEvent(initialState: false); var jobContinueEvent = new ManualResetEvent(initialState: false); IEnumerable&lt;UnitTestMessage&gt; inputElementList = null; int callCount = 0; Action&lt;IEnumerable&lt;UnitTestMessage&gt;&gt; handler = (IEnumerable&lt;UnitTestMessage&gt; elementList) =&gt; { callCount++; inputElementList = elementList; jobStartEvent.Set(); jobContinueEvent.WaitOne(); }; using (var memoryQueue = new MemoryQueue&lt;UnitTestMessage&gt;(handler, maxBulkSize: 10, LogProvider)) { var element = new UnitTestMessage(&quot;some val&quot;); memoryQueue.StartListening(); var task = memoryQueue.AddAsync(element); jobStartEvent.WaitOne();// Wait for the background task to execute the job Assert.NotEqual(TaskStatus.RanToCompletion, task.Status); Assert.NotEqual(TaskStatus.Faulted, task.Status); // Now allow the job running on the other thread to run to completion jobContinueEvent.Set(); // An await the final task to complete await task; Assert.Equal(TaskStatus.RanToCompletion, task.Status); Assert.Equal(1, callCount); Assert.NotNull(inputElementList); Assert.Same(element, inputElementList.Single()); } } [Fact] public async void AddAsync_EnsureExecuteInBackground_WithException_ExpectTaskException_Test() { var jobStartEvent = new ManualResetEvent(initialState: false); var jobContinueEvent = new ManualResetEvent(initialState: false); var targetException = new FieldAccessException(&quot;Some specific exception&quot;); IEnumerable&lt;UnitTestMessage&gt; inputElementList = null; int callCount = 0; Action&lt;IEnumerable&lt;UnitTestMessage&gt;&gt; handler = (IEnumerable&lt;UnitTestMessage&gt; elementList) =&gt; { callCount++; inputElementList = elementList; jobStartEvent.Set(); jobContinueEvent.WaitOne(); throw targetException; }; using (var memoryQueue = new MemoryQueue&lt;UnitTestMessage&gt;(handler, maxBulkSize: 10, LogProvider)) { var element = new UnitTestMessage(&quot;some val&quot;); memoryQueue.StartListening(); var task = memoryQueue.AddAsync(element); jobStartEvent.WaitOne();// Wait for the background task to execute the job Assert.NotEqual(TaskStatus.RanToCompletion, task.Status); Assert.NotEqual(TaskStatus.Faulted, task.Status); // Now allow the job running on the other thread to run to completion jobContinueEvent.Set(); // An await the final task to complete try { await task; throw new Exception(&quot;Expected a FieldAccessException exception here&quot;); } catch (FieldAccessException ex) { Assert.Same(targetException, ex); } Assert.Equal(TaskStatus.Faulted, task.Status); Assert.Equal(1, callCount); Assert.NotNull(inputElementList); Assert.Same(element, inputElementList.Single()); Log.Assert(Common.LogLevel.Fatal, message: @&quot;Unexpected exception processing 1 of type Inmobile.Tools.MemoryQueues.Test.MemoryQueueTest+UnitTestMessage. Entry data: [{&quot;&quot;Foo&quot;&quot;:&quot;&quot;some val&quot;&quot;}]&quot;); } } [Fact] public async void BulkSize_EnsuringBulkSizeIsNotExceeded_Test() { var msg1 = new UnitTestMessage(&quot;val1&quot;); var msg2 = new UnitTestMessage(&quot;val2&quot;); var msg3 = new UnitTestMessage(&quot;val3&quot;); var msg4 = new UnitTestMessage(&quot;val4&quot;); var msg5 = new UnitTestMessage(&quot;val5&quot;); var msg6 = new UnitTestMessage(&quot;val6&quot;); var msg7 = new UnitTestMessage(&quot;val7&quot;); var handlerCallBulks = new List&lt;List&lt;UnitTestMessage&gt;&gt;(); var handlerStartedEvent = new ManualResetEvent(initialState: false); Action&lt;IEnumerable&lt;UnitTestMessage&gt;&gt; handler = (IEnumerable&lt;UnitTestMessage&gt; elementList) =&gt; { handlerStartedEvent.Set(); handlerCallBulks.Add(elementList.ToList()); }; using (var memoryQueue = new MemoryQueue&lt;UnitTestMessage&gt;(handler, maxBulkSize: 4, LogProvider)) // Max bulk size: 4 { var element = new UnitTestMessage(&quot;some val&quot;); memoryQueue.StartListening(); // Adding the first message will trigger adding the rest inside the handler call var task = memoryQueue.AddAsync(msg1); // Wait until the handler is called the first time - this ensures that the handler is only called with a single element handlerStartedEvent.WaitOne(); // At the first call to this handler, it is expected to only have a single element in the list // While this handler is being called, the rest of the elements are added, enabling full control of how many elements are in the queue when the worker thread is fetching new entries #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed memoryQueue.AddAsync(msg2); memoryQueue.AddAsync(msg3); memoryQueue.AddAsync(msg4); memoryQueue.AddAsync(msg5); memoryQueue.AddAsync(msg6); memoryQueue.AddAsync(msg7); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed // Now stop the memoryQueue and expect it to run until no more messages await memoryQueue.ShutdownAsync(); // Start out ensuring all elements have actually been delivered to the handler in any call var allProcessedElements = handlerCallBulks.SelectMany(list =&gt; list).ToList(); Assert.Contains(msg1, allProcessedElements); Assert.Contains(msg2, allProcessedElements); Assert.Contains(msg3, allProcessedElements); Assert.Contains(msg4, allProcessedElements); Assert.Contains(msg5, allProcessedElements); Assert.Contains(msg6, allProcessedElements); Assert.Contains(msg7, allProcessedElements); Assert.Equal(7, allProcessedElements.Count); // Now assert the expect bulk sizes with the maximum bulk size of 4. Expected calls: // msg1 // msg2, msg3, msg4, msg5 // msg6, msg7 Assert.Equal(3, handlerCallBulks.Count); Assert.Single(handlerCallBulks[0]); Assert.Equal(4, handlerCallBulks[1].Count); Assert.Equal(2, handlerCallBulks[2].Count); // An await the final task to complete await task; Assert.Equal(TaskStatus.RanToCompletion, task.Status); } } public class UnitTestMessage { public string Foo { get; set; } public UnitTestMessage(string foo) { Foo = foo; } } } </code></pre> <h2>Things I would like reviewed</h2> <h3>Is the construction of the async interface correct?</h3> <p>I am using a <code>TaskCompletionSource</code> with an object as a generic type parameter (because I couldn't find a non-generic version). Is this use correct?</p> <h3>Risk of deadlocks</h3> <p>I have already fixed one deadlock: calling <code>.Dispose()</code> directly on the collection while another thread is listening will from time to time yield a deadlock with the waiting thread keeping blocking on the <code>Take()</code> call.</p> <p>The solution is to use a cancellation token that is <code>Cancel()</code>ed in the <code>MemoryQueue.Dispose()</code> method. And then use this cancellation token inside the thread's logic and dispose the queue when the thread has run dry.</p> <p>Are there any remaining risks of deadlocks?</p> <h3>Multithreaded unit tests</h3> <p>I have to this day never created a multithreaded unit test that I was proud of. How would other people go about the testing of all this? Feel free to pinpoint single test methods to show how I could improve on this.</p> <h3>Did I miss something?</h3> <p>Should I set up my post differently? Did I reinvent the wheel? Should I go about with a totally different approach?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T09:10:09.700", "Id": "269904", "Score": "5", "Tags": [ "c#", "sql-server" ], "Title": "dotnet - creating db records in bulks in a background job" }
269904
<p>I have written this k-means algorithm without using any class structure. The audience of my code are students who are pretty new to Python. Is it possible to review the code so that it is more readable by beginner of Python, and at the same time efficient. I wrote the code quite quickly, without reviewing it properly. I have a nagging feeling that it looks more like a code spaghetti. So I need some pointers here, please.</p> <pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt import numpy as np def colorCluster(data, k , numPoints, clusterColors, numIterations): #Get the distance from the centroids def getDistFromCentroid(data,centroids,k): def getDistance(a, X): a = a.T X = X.T len = X.shape[0] distance = np.zeros(len) for i in range (len): b = X[i] distance[i] = np.sqrt(np.square(a[0] - b[0]) + np.square(a[1] - b[1])) return distance dist = np.zeros((k,numPoints)) for i in range(k): dist[i] = getDistance(centroids[i], data) return dist #Get the indices of the k clusters def getIndicesOfClusters(dist): indArr = [] for i in range(k): ind = [] for j in range(numPoints): if(np.argmin(dist[:,j]) == i): ind.append(j) indArr.append(ind) return indArr #Using the indices of the clustered points #draw on the canvas def drawClusterPoints(dist): def plotMat(mat , ind, color): ind = np.array(ind).reshape(-1,1).T p = mat[:,ind] plt.plot(p[0], p[1], 'o', color = color) indArr = getIndicesOfClusters(dist) for i in range(k): plotMat(data, indArr[i], clusterColors[i]) #Centroids are calcuated using the average #of x and y coordinates in each cluster def getCentroid(dist): indArr = getIndicesOfClusters(dist) centroids = [] for i in range(k): centroids.append(np.average(data[:,indArr[i]], axis = 1)) return np.array(centroids) #Update the whole code #Find new centroids #Calculate the new distances from centroids #Repeat for numIterations def connectAll(): centroids = np.random.randint(1,numPoints, size = [k,2]) for i in range(numIterations): dist = getDistFromCentroid(data,centroids,k) centroids = getCentroid(dist) drawClusterPoints(dist) #plt.show() plt.draw() plt.pause(0.00000000000001) plt.clf() #print(centroids.shape) connectAll() def kmeans(): #initialize numPoints = 1000 data = np.random.randint(1,numPoints, size = (2,numPoints)) plt.plot(data[0], data[1], 'o', color = &quot;black&quot;) plt.show() k = 9 numIterations = 10 clusterColors = [&quot;red&quot;,&quot;brown&quot;, &quot;black&quot;, &quot;blue&quot;, &quot;orange&quot;, &quot;purple&quot;, &quot;olive&quot;, &quot;gray&quot;, &quot;cyan&quot;] colorCluster(data, k , numPoints, clusterColors, numIterations) <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T11:45:21.120", "Id": "269908", "Score": "0", "Tags": [ "python", "performance", "algorithm" ], "Title": "Clarity and optimization of kmeans algorithms" }
269908
<p>Since I am a Unix newbie, I wanted to know if the code reflects the &quot;unix&quot; style and if there is something to add for it to be robust.</p> <p>P. S. I hope I am not overusing <code>assert</code> calls.</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;errno.h&gt; #include &lt;assert.h&gt; #include &lt;sys/types.h&gt; #include &lt;sys/socket.h&gt; #include &lt;netinet/in.h&gt; #define whaterror strerror(errno) #define PORT 0xbb8 #define BACKLOG 0xf // can't be &gt; 128. #define BUFFSIZE 0x400 void init_server(struct sockaddr_in* server) { assert(server != NULL &amp;&amp; &quot;Server pointer can't be null&quot;); server -&gt; sin_family = AF_INET; // use IP. server -&gt; sin_addr.s_addr = INADDR_ANY; // listen on any address (0.0.0.0). server -&gt; sin_port = htons(PORT); // listen on PORT. } int main() { struct sockaddr_in sock_in; // an inbound socket const int sockfd = socket(PF_INET, SOCK_STREAM, 0); // try to open the socket. assert(sockfd &gt;= 0 &amp;&amp; &quot;Error in opening socket.&quot;); // check if socket opened. memset((char*)&amp;sock_in, 0, sizeof(sock_in)); // reset sock_in to 0 init_server(&amp;sock_in); // initialize server struct assert( bind(sockfd, (const struct sockaddr*)&amp;sock_in, sizeof(sock_in)) &gt;= 0 &amp;&amp; &quot;Port binding failed.&quot; ); assert( listen(sockfd, BACKLOG) == 0 &amp;&amp; &quot;Can't listen to the socket specified.&quot; ); int bytes = 0; char* chunk = memset(malloc(BUFFSIZE), 0, BUFFSIZE); const int asocfd = accept(sockfd, NULL, 0); assert(asocfd &gt;= 0 &amp;&amp; &quot;Error in accepting socket.&quot;); // check if socket opened. do { bytes = recv(asocfd, chunk, BUFFSIZE - 1, 0); memset(bytes == -1 ? chunk : chunk + bytes, 0, BUFFSIZE); !errno ? bytes &amp;&amp; printf(&quot;%d\n%s\n&quot;, bytes, chunk) : fprintf(stderr, &quot;ERRNO: %d [%s]\n&quot;, errno, whaterror); } while (errno == EAGAIN | bytes &gt; 0); return 0; } </code></pre>
[]
[ { "body": "<blockquote>\n<p>I hope I am not overusing <code>assert</code> calls</p>\n</blockquote>\n<p>You do. <code>assert</code> is a debugging instrument. If <code>NDEBUG</code> macro is defined, the calls to <code>assert</code> are removed at the compile time. This is a usual practice for the production code.</p>\n<ul>\n<li><p><code>#define whaterror strerror(errno)</code></p>\n<p>I advise against it. The macro adds no value, and only obfuscates the code.</p>\n</li>\n<li><p><code>memset(malloc</code></p>\n<p>Keep in mind that <code>malloc</code> may fail.</p>\n</li>\n<li><p><code>memset(bytes == -1 ? chunk : chunk + bytes, 0, BUFFSIZE);</code></p>\n<p>Setting <code>BUFFSIZE</code> bytes to 0 writes beyond the allocated space. You need <code>BUFFSIZE - bytes</code>.</p>\n<p>On the other hand, clearing the entire tail of the <code>chunk</code> is not necessary. <code>chunk[bytes] = 0;</code> is enough.</p>\n</li>\n<li><p><code>!errno ?</code>, besides being another obfuscation, is quite wrong. <code>errno</code> is a way to <em>inspect</em> errors, not to <em>detect</em> them. In fact, quoting <code>man errno</code>,</p>\n<blockquote>\n<p>Successful calls never set errno; once set, it remains until another error occurs.</p>\n</blockquote>\n<p><code>recv</code> returning <code>-1</code> <em>is</em> one and only indication of error.</p>\n</li>\n<li><p>Since the socket is not marked nonblocking, it may never return <code>EAGAIN</code>. On the other hand, some errors are transient, and should not break the loop.</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T17:00:37.907", "Id": "269923", "ParentId": "269909", "Score": "1" } }, { "body": "<ol>\n<li><p>You are definitely overusing, and <strong>misusing</strong> <code>assert()</code>. The problem is that it is something that should become a no-op when your code is compiled for release. As such, it should have NO side effects (like calling <code>bind()</code> or <code>listen()</code>, and should not be used for testing environmental errors. <code>assert()</code> should only be used for testing for programming errors. This means the use of <code>assert()</code> in <code>init_server()</code> is valid, but the rest aren't.</p>\n</li>\n<li><p>Your read loop is a bit twisted. I might write it like:</p>\n<pre class=\"lang-c prettyprint-override\"><code>for (;;) {\n bytes = recv(asocfd, chunk, BUFFSIZE, 0);\n if (bytes &lt; 0) {\n fprintf(stderr, &quot;ERRNO: %d [%s]\\n&quot;, errno, whaterror);\n if (errno != EAGAIN) break;\n } else if (bytes == 0) {\n break;\n } else {\n printf(&quot;%d\\n%.*s\\n&quot;, bytes, bytes, chunk)\n }\n}\n</code></pre>\n<p>Among other issues there:</p>\n<ul>\n<li>Your <code>memset()</code> call overran your buffer, quite possibly by the entire length of the buffer.</li>\n<li>Your <code>memset()</code> was unneeded if there was an error.</li>\n<li><code>memset()</code> is excessive just to add a single trailing NUL. It could have been written <code>chunk[bytes] = 0;</code> This is actually why you included the <code>- 1</code> in the <code>recv()</code> call. (I removed the <code>- 1</code> as telling <code>printf()</code> not to go past the length is equally effective.</li>\n<li>Don't avoid <code>if</code> statements.</li>\n</ul>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T17:02:02.823", "Id": "269924", "ParentId": "269909", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T12:06:36.850", "Id": "269909", "Score": "1", "Tags": [ "c", "socket", "tcp", "unix" ], "Title": "Low level tcp socket" }
269909
<p>I am refreshing my C++ programming skills, and I'm currently reading the book C++ 17 by Ivor Horton. The idea is to code some naive implementations of numerical algorithms (Root finding, solving a system of linear equations). To hone my skills, I decided to write a custom C++ <code>Matrix</code> class. This can be an interesting and useful exercise in itself.</p> <p>My <code>Matrix</code> class supports fixed-size matrices whose dimensions are compile-time constants as well as dynamic (run-time) matrices. I overloaded the <code>&lt;&lt;</code> and <code>,</code> operators, in a way that a matrix objects can be nicely initialized as:</p> <pre><code>MatrixXi m1 {3,3}; m1 &lt;&lt;1, 0, 0, 0, 1, 0, 0, 0, 1; </code></pre> <p>The class supports a subset of basic matrix algebra - addition, subtraction, multiplication and assignment through overloaded operators. I would very much appreciate your suggestions/feedback on this project.</p> <p>I have couple of additional soft questions.</p> <ol> <li><p><code>Matrix</code> takes 4 template parameters.</p> <pre><code>template &lt;typename scalarType, int rowsAtCompileTime = 0, int colsAtCompileTime = 0, typename containerType = std::array&lt;T, r* c&gt;&gt; </code></pre> <p>At some point, (due to build failures) I ended up doing partial template specialization, i.e. I have two versions of <code>Matrix</code> class - one with <code>std::array&lt;T&gt;</code> and another with <code>std::vector&lt;T,N&gt;</code> as the <code>containerType</code>. Should I try and <strong>generalize</strong> this again, to remove duplicate code?</p> </li> <li><p>Would you call this well-designed/<strong>well-written code</strong>, or is it <strong>spaghetti code</strong>?</p> </li> </ol> <h2>Matrix.h</h2> <pre><code>#pragma once #ifndef Matrix_H #include &lt;array&gt; #include &lt;vector&gt; #include &lt;stdexcept&gt; #include &lt;type_traits&gt; #include &lt;iterator&gt; template &lt;typename T, int r = 0, int c = 0, typename cType = std::array&lt;T, r* c&gt;&gt; class Matrix; using Matrix1d = Matrix&lt;double, 1, 1, std::array&lt;double, 1&gt;&gt;; using Matrix2d = Matrix&lt;double, 2, 2, std::array&lt;double, 4&gt;&gt;; using Matrix3d = Matrix&lt;double, 3, 3, std::array&lt;double, 9&gt;&gt;; using Matrix4d = Matrix&lt;double, 4, 4, std::array&lt;double, 16&gt;&gt;; using Matrix1i = Matrix&lt;int, 1, 1, std::array&lt;int, 1&gt;&gt;; using Matrix2i = Matrix&lt;int, 2, 2, std::array&lt;int, 4&gt;&gt;; using Matrix3i = Matrix&lt;int, 3, 3, std::array&lt;int, 9&gt;&gt;; using Matrix4i = Matrix&lt;int, 4, 4, std::array&lt;int, 16&gt;&gt;; using Matrix1f = Matrix&lt;float, 1, 1, std::array&lt;float, 1&gt;&gt;; using Matrix2f = Matrix&lt;float, 2, 2, std::array&lt;float, 4&gt;&gt;; using Matrix3f = Matrix&lt;float, 3, 3, std::array&lt;float, 9&gt;&gt;; using Matrix4f = Matrix&lt;float, 4, 4, std::array&lt;float, 16&gt;&gt;; using Vector1d = Matrix&lt;double, 1, 1, std::vector&lt;double&gt;&gt;; using Vector2d = Matrix&lt;double, 1, 2, std::vector&lt;double&gt;&gt;; using Vector3d = Matrix&lt;double, 1, 3, std::vector&lt;double&gt;&gt;; using Vector4d = Matrix&lt;double, 1, 4, std::vector&lt;double&gt;&gt;; using Vector1i = Matrix&lt;int, 1, 1, std::vector&lt;double&gt;&gt;; using Vector2i = Matrix&lt;int, 2, 2, std::vector&lt;double&gt;&gt;; using Vector3i = Matrix&lt;int, 3, 3, std::vector&lt;double&gt;&gt;; using Vector4i = Matrix&lt;int, 4, 4, std::vector&lt;double&gt;&gt;; using Vector1f = Matrix&lt;float, 1, 1, std::vector&lt;double&gt;&gt;; using Vector2f = Matrix&lt;float, 2, 2, std::vector&lt;double&gt;&gt;; using Vector3f = Matrix&lt;float, 3, 3, std::vector&lt;double&gt;&gt;; using Vector4f = Matrix&lt;float, 4, 4, std::vector&lt;double&gt;&gt;; using MatrixXi = Matrix&lt;int, 0, 0, std::vector&lt;int&gt;&gt;; using MatrixXd = Matrix&lt;double, 0, 0, std::vector&lt;double&gt;&gt;; using MatrixXf = Matrix&lt;float, 0, 0, std::vector&lt;float&gt;&gt;; template &lt;typename scalarType, int rowsAtCompileTime, int colsAtCompileTime&gt; class Matrix&lt;typename scalarType, rowsAtCompileTime, colsAtCompileTime, std::array&lt;scalarType, rowsAtCompileTime* colsAtCompileTime&gt;&gt; { private: std::array&lt;scalarType, rowsAtCompileTime* colsAtCompileTime&gt; A; int _rows; int _cols; int _size; typename std::array&lt;scalarType, rowsAtCompileTime* colsAtCompileTime&gt;::iterator currentPosition; public: Matrix(); Matrix(int m, int n); Matrix(const Matrix&amp; m); int rows() const; int cols() const; int size() const; //Overloaded operators scalarType operator()(const int i, const int j) const; //Subscript operator scalarType&amp; operator()(const int i, const int j); //Subscript operator const arrays Matrix operator+(const Matrix&amp; m) const; Matrix operator-(const Matrix&amp; m) const; Matrix&amp; operator&lt;&lt;(const scalarType x); Matrix&amp; operator,(const scalarType x); Matrix&amp; operator=(const Matrix&amp; right_hand_side); }; template &lt;typename scalarType&gt; class Matrix&lt;typename scalarType, 0, 0, std::vector&lt;scalarType&gt;&gt; { private: std::vector&lt;scalarType&gt; A; int _rows; int _cols; int _size; typename std::vector&lt;scalarType&gt;::iterator currentPosition; public: Matrix(); Matrix(int m, int n); Matrix(const Matrix&amp; m); int rows() const; int cols() const; int size() const; //Overloaded operators scalarType operator()(const int i, const int j) const; scalarType&amp; operator()(const int i, const int j); Matrix operator+(const Matrix&amp; m) const; Matrix operator-(const Matrix&amp; m) const; Matrix&amp; operator&lt;&lt;(const scalarType x); Matrix&amp; operator,(const scalarType x); Matrix&amp; operator=(const Matrix&amp; right_hand_side); }; // Non-member operator functions template&lt;typename scalarType, int m, int n, int p, int q&gt; Matrix&lt;scalarType, m, q, std::vector&lt;scalarType&gt;&gt; operator*(const Matrix&lt;scalarType, m, n, std::vector&lt;scalarType&gt;&gt;&amp; A, const Matrix&lt;scalarType, p, q, std::vector&lt;scalarType&gt;&gt;&amp; B); template&lt;typename scalarType, int m, int n, int p, int q&gt; Matrix&lt;scalarType, m, q, std::array&lt;scalarType, m* q&gt;&gt; operator*(const Matrix&lt;scalarType, m, n, std::array&lt;scalarType, m* n&gt;&gt;&amp; A, const Matrix&lt;scalarType, p, q, std::array&lt;scalarType, p* q&gt;&gt;&amp; B); //Default constructor template&lt;typename scalarType, int rowsAtCompileTime, int colsAtCompileTime&gt; inline Matrix&lt;typename scalarType, rowsAtCompileTime, colsAtCompileTime, std::array&lt;scalarType, rowsAtCompileTime* colsAtCompileTime&gt;&gt;::Matrix() :_rows{ rowsAtCompileTime }, _cols{ colsAtCompileTime } { currentPosition = A.begin(); } //Default constructor template&lt;typename scalarType&gt; inline Matrix&lt;typename scalarType, 0, 0, std::vector&lt;scalarType&gt;&gt;::Matrix() :_rows{ 0 }, _cols{ 0 } { currentPosition = A.begin(); } //Fixed-Size matrices template&lt;typename scalarType, int rowsAtCompileTime, int colsAtCompileTime&gt; inline Matrix&lt;typename scalarType, rowsAtCompileTime, colsAtCompileTime, std::array&lt;scalarType, rowsAtCompileTime* colsAtCompileTime&gt;&gt;::Matrix(int m, int n) { //Do nothing. } //Run-time matrices template&lt;typename scalarType&gt; inline Matrix&lt;typename scalarType, 0, 0, std::vector&lt;scalarType&gt;&gt;::Matrix(int m, int n) : _rows{ m }, _cols{ n } { int numOfElements{ m * n }; for (int i{}; i &lt; numOfElements; ++i) { A.push_back(0); } currentPosition = A.begin(); } template&lt;typename scalarType&gt; inline Matrix&lt;typename scalarType, 0, 0, std::vector&lt;scalarType&gt;&gt;::Matrix(const Matrix&amp; m) : A{ m.A }, _rows{ m.rows() }, _cols{ m.cols() }, currentPosition{ m.currentPosition } { } template&lt;typename scalarType, int rowsAtCompileTime, int colsAtCompileTime&gt; inline Matrix&lt;typename scalarType, rowsAtCompileTime, colsAtCompileTime, std::array&lt;scalarType, rowsAtCompileTime* colsAtCompileTime&gt;&gt;::Matrix(const Matrix&amp; m) : A{ m.A }, _rows{ m.rows() }, _cols{ m.cols() }, currentPosition{ m.currentPosition } { } template&lt;typename scalarType, int rowsAtCompileTime, int colsAtCompileTime&gt; inline int Matrix&lt;scalarType, rowsAtCompileTime, colsAtCompileTime, std::array&lt;scalarType, rowsAtCompileTime* colsAtCompileTime&gt;&gt;::rows() const { return _rows; } template&lt;typename scalarType, int rowsAtCompileTime, int colsAtCompileTime&gt; inline int Matrix&lt;scalarType, rowsAtCompileTime, colsAtCompileTime, std::array&lt;scalarType, rowsAtCompileTime* colsAtCompileTime&gt;&gt;::cols() const { return _cols; } template&lt;typename scalarType&gt; inline int Matrix&lt;scalarType, 0, 0, std::vector&lt;scalarType&gt;&gt;::rows() const { return _rows; } template&lt;typename scalarType&gt; inline int Matrix&lt;scalarType, 0, 0, std::vector&lt;scalarType&gt;&gt;::cols() const { return _cols; } template&lt;typename scalarType, int rowsAtCompileTime, int colsAtCompileTime&gt; inline int Matrix&lt;scalarType, rowsAtCompileTime, colsAtCompileTime, std::array&lt;scalarType, rowsAtCompileTime* colsAtCompileTime&gt;&gt;::size() const { return A.size(); } template&lt;typename scalarType&gt; inline int Matrix&lt;scalarType, 0, 0, std::vector&lt;scalarType&gt;&gt;::size() const { return A.size(); } template&lt;typename scalarType, int rowsAtCompileTime, int colsAtCompileTime&gt; inline scalarType Matrix&lt;typename scalarType, rowsAtCompileTime, colsAtCompileTime, std::array&lt;scalarType, rowsAtCompileTime* colsAtCompileTime&gt;&gt;::operator()(const int i, const int j) const { typename std::array&lt;scalarType, rowsAtCompileTime* colsAtCompileTime&gt;::const_iterator it{ A.begin() }; it = it + (i * _cols) + j; if (it &lt; A.end()) return *it; else throw std::out_of_range(&quot;\nError accessing an element beyond matrix bounds&quot;); } template&lt;typename scalarType, int rowsAtCompileTime, int colsAtCompileTime&gt; inline scalarType&amp; Matrix&lt;typename scalarType, rowsAtCompileTime, colsAtCompileTime, std::array&lt;scalarType, rowsAtCompileTime* colsAtCompileTime&gt;&gt;::operator()(const int i, const int j) { typename std::array&lt;scalarType, rowsAtCompileTime* colsAtCompileTime&gt;::iterator it{ A.begin() }; it = it + (i * _cols) + j; if (it &lt; A.end()) return *it; else throw std::out_of_range(&quot;\nError accessing an element beyond matrix bounds&quot;); } template&lt;typename scalarType&gt; inline scalarType Matrix&lt;typename scalarType, 0, 0, std::vector&lt;scalarType&gt;&gt;::operator()(const int i, const int j) const { typename std::vector&lt;scalarType&gt;::const_iterator it{ A.begin() }; it = it + (i * _cols) + j; if (it &lt; A.end()) return *it; else throw std::out_of_range(&quot;\nError accessing an element beyond matrix bounds&quot;); } template&lt;typename scalarType&gt; inline scalarType&amp; Matrix&lt;typename scalarType, 0, 0, std::vector&lt;scalarType&gt;&gt;::operator()(const int i, const int j) { typename std::vector&lt;scalarType&gt;::iterator it{ A.begin() }; it = it + (i * _cols) + j; if (it &lt; A.end()) return *it; else throw std::out_of_range(&quot;\nError accessing an element beyond matrix bounds&quot;); } template&lt;typename scalarType, int rowsAtCompileTime, int colsAtCompileTime&gt; inline Matrix&lt;typename scalarType, rowsAtCompileTime, colsAtCompileTime, std::array&lt;scalarType, rowsAtCompileTime* colsAtCompileTime&gt;&gt; Matrix&lt;typename scalarType, rowsAtCompileTime, colsAtCompileTime, std::array&lt;scalarType, rowsAtCompileTime* colsAtCompileTime&gt;&gt;::operator+(const Matrix&amp; m) const { Matrix&lt;scalarType, rowsAtCompileTime, colsAtCompileTime, std::array&lt;scalarType, rowsAtCompileTime* colsAtCompileTime&gt;&gt; result{}; if (this-&gt;rows() == m.rows() &amp;&amp; this-&gt;cols() == m.cols()) { typename std::array&lt;scalarType, rowsAtCompileTime* colsAtCompileTime&gt;::const_iterator it1{ A.begin() }; typename std::array&lt;scalarType, rowsAtCompileTime* colsAtCompileTime&gt;::const_iterator it2{ m.A.begin() }; typename std::array&lt;scalarType, rowsAtCompileTime* colsAtCompileTime&gt;::iterator resultIter{ result.A.begin() }; while (it1 &lt; A.end() &amp;&amp; it2 &lt; m.A.end()) { *resultIter = *it1 + *it2; ++it1; ++it2; ++resultIter; } } else { throw std::logic_error(&quot;Matrices have different dimensions; therefore cannot be added!&quot;); } return result; } template&lt;typename scalarType, int rowsAtCompileTime, int colsAtCompileTime&gt; inline Matrix&lt;typename scalarType, rowsAtCompileTime, colsAtCompileTime, std::array&lt;scalarType, rowsAtCompileTime* colsAtCompileTime&gt;&gt; Matrix&lt;typename scalarType, rowsAtCompileTime, colsAtCompileTime, std::array&lt;scalarType, rowsAtCompileTime* colsAtCompileTime&gt;&gt;::operator-(const Matrix&amp; m) const { Matrix&lt;scalarType, rowsAtCompileTime, colsAtCompileTime, std::array&lt;scalarType, rowsAtCompileTime* colsAtCompileTime&gt;&gt; result{}; if (this-&gt;rows() == m.rows() &amp;&amp; this-&gt;cols() == m.cols()) { typename std::array&lt;scalarType, rowsAtCompileTime* colsAtCompileTime&gt;::const_iterator it1{ A.begin() }; typename std::array&lt;scalarType, rowsAtCompileTime* colsAtCompileTime&gt;::const_iterator it2{ m.A.begin() }; typename std::array&lt;scalarType, rowsAtCompileTime* colsAtCompileTime&gt;::iterator resultIter{ result.A.begin() }; while (it1 &lt; A.end() &amp;&amp; it2 &lt; m.A.end()) { *resultIter = *it1 - *it2; ++it1; ++it2; ++resultIter; } } else { throw std::logic_error(&quot;Matrices have different dimensions; therefore cannot be added!&quot;); } return result; } template&lt;typename scalarType, int rowsAtCompileTime, int colsAtCompileTime&gt; inline Matrix&lt;typename scalarType, rowsAtCompileTime, colsAtCompileTime, std::array&lt;scalarType, rowsAtCompileTime* colsAtCompileTime&gt;&gt;&amp; Matrix&lt;typename scalarType, rowsAtCompileTime, colsAtCompileTime, std::array&lt;scalarType, rowsAtCompileTime* colsAtCompileTime&gt;&gt;::operator&lt;&lt;(const scalarType x) { if (currentPosition &lt; A.end()) { *currentPosition = x; ++currentPosition; } else { throw std::logic_error(&quot;Error: Attempting to set values beyond matrix bounds!&quot;); } return *this; } template&lt;typename scalarType&gt; inline Matrix&lt;typename scalarType, 0, 0, std::vector&lt;scalarType&gt;&gt;&amp; Matrix&lt;typename scalarType, 0, 0, std::vector&lt;scalarType&gt;&gt;::operator&lt;&lt;(const scalarType x) { if (currentPosition &lt; A.end()) { *currentPosition = x; ++currentPosition; } else { throw std::logic_error(&quot;Error: Attempting to set values beyond matrix bounds!&quot;); } return *this; } template&lt;typename scalarType, int rowsAtCompileTime, int colsAtCompileTime&gt; inline Matrix&lt;typename scalarType, rowsAtCompileTime, colsAtCompileTime, std::array&lt;scalarType, rowsAtCompileTime* colsAtCompileTime&gt;&gt;&amp; Matrix&lt;typename scalarType, rowsAtCompileTime, colsAtCompileTime, std::array&lt;scalarType, rowsAtCompileTime* colsAtCompileTime&gt;&gt;::operator,(const scalarType x) { if (currentPosition &lt; A.end()) { *currentPosition = x; ++currentPosition; } else { throw std::logic_error(&quot;Error: Attempting to set values beyond matrix bounds!&quot;); } return *this; } template&lt;typename scalarType, int rowsAtCompileTime, int colsAtCompileTime&gt; inline Matrix&lt;typename scalarType, rowsAtCompileTime, colsAtCompileTime, std::array&lt;scalarType, rowsAtCompileTime* colsAtCompileTime&gt;&gt;&amp; Matrix&lt;typename scalarType, rowsAtCompileTime, colsAtCompileTime, std::array&lt;scalarType, rowsAtCompileTime* colsAtCompileTime&gt;&gt;::operator=(const Matrix&amp; right_hand_side) { if (this-&gt;rows() != right_hand_side.rows() || this-&gt;cols() != right_hand_side.cols()) throw std::logic_error(&quot;Assignment failed, matrices have different dimensions&quot;); if (this == &amp;right_hand_side) return *this; this-&gt;A = right_hand_side.A; this-&gt;_rows = right_hand_side._rows; this-&gt;_cols = right_hand_side._cols; this-&gt;currentPosition = right_hand_side.currentPosition; return *this; } template&lt;typename scalarType&gt; inline Matrix&lt;typename scalarType, 0, 0, std::vector&lt;scalarType&gt;&gt;&amp; Matrix&lt;typename scalarType, 0, 0, std::vector&lt;scalarType&gt;&gt;::operator=(const Matrix&amp; right_hand_side) { if (this-&gt;rows() != right_hand_side.rows() || this-&gt;cols() != right_hand_side.cols()) throw std::logic_error(&quot;Assignment failed, matrices have different dimensions&quot;); if (this == &amp;right_hand_side) return *this; this-&gt;A = right_hand_side.A; this-&gt;_rows = right_hand_side._rows; this-&gt;_cols = right_hand_side._cols; this-&gt;currentPosition = right_hand_side.currentPosition; return *this; } template&lt;typename scalarType&gt; inline Matrix&lt;typename scalarType, 0, 0, std::vector&lt;scalarType&gt;&gt;&amp; Matrix&lt;typename scalarType, 0, 0, std::vector&lt;scalarType&gt;&gt;::operator,(const scalarType x) { if (currentPosition &lt; A.end()) { *currentPosition = x; ++currentPosition; } else { throw std::logic_error(&quot;Error: Attempting to set values beyond matrix bounds!&quot;); } return *this; } template&lt;typename scalarType&gt; inline Matrix&lt;typename scalarType, 0, 0, std::vector&lt;scalarType&gt;&gt; Matrix&lt;typename scalarType, 0, 0, std::vector&lt;scalarType&gt;&gt;::operator+(const Matrix&amp; m) const { if (this-&gt;rows() == m.rows() &amp;&amp; this-&gt;cols() == m.cols()) { Matrix&lt;scalarType, 0, 0, std::vector&lt;scalarType&gt;&gt; result{m.rows(),m.cols()}; typename std::vector&lt;scalarType&gt;::const_iterator it1{ A.begin() }; typename std::vector&lt;scalarType&gt;::const_iterator it2{ m.A.begin() }; typename std::vector&lt;scalarType&gt;::iterator resultIter{ result.A.begin() }; while (it1 &lt; A.end() &amp;&amp; it2 &lt; m.A.end()) { *resultIter = *it1 + *it2; ++it1; ++it2; ++resultIter; } return result; } else { throw std::logic_error(&quot;Matrices have different dimensions; therefore cannot be added!&quot;); } } template&lt;typename scalarType&gt; inline Matrix&lt;typename scalarType, 0, 0, std::vector&lt;scalarType&gt;&gt; Matrix&lt;typename scalarType, 0, 0, std::vector&lt;scalarType&gt;&gt;::operator-(const Matrix&amp; m) const { if (this-&gt;rows() == m.rows() &amp;&amp; this-&gt;cols() == m.cols()) { Matrix&lt;scalarType, 0, 0, std::vector&lt;scalarType&gt;&gt; result{ m.rows(),m.cols() }; typename std::vector&lt;scalarType&gt;::const_iterator it1{ A.begin() }; typename std::vector&lt;scalarType&gt;::const_iterator it2{ m.A.begin() }; typename std::vector&lt;scalarType&gt;::iterator resultIter{ result.A.begin() }; while (it1 &lt; A.end() &amp;&amp; it2 &lt; m.A.end()) { *resultIter = *it1 - *it2; ++it1; ++it2; ++resultIter; } return result; } else { throw std::logic_error(&quot;Matrices have different dimensions; therefore cannot be added!&quot;); } } template&lt;typename scalarType, int m, int n, int p, int q&gt; inline Matrix&lt;scalarType, m, q, std::vector&lt;scalarType&gt;&gt; operator*(const Matrix&lt;scalarType, m, n, std::vector&lt;scalarType&gt;&gt;&amp; A, const Matrix&lt;scalarType, p, q, std::vector&lt;scalarType&gt;&gt;&amp; B) { if (n != p) throw std::logic_error(&quot;Error multiplying the matrices; the number of cols(A) must equal the number of rows(B)!&quot;); Matrix&lt;scalarType, 0, 0, std::vector&lt;scalarType&gt;&gt; result{ m,q }; for (int i{}; i &lt; m; ++i) { for (int k{}; k &lt; p; ++k) { scalarType sum{}; for (int j{}; j &lt; n; ++j) { sum += A(i, j) * B(j, k); } result(i, k) = sum; } } return result; } template&lt;typename scalarType, int m, int n, int p, int q&gt; Matrix&lt;scalarType, m, q, std::array&lt;scalarType, m* q&gt;&gt; operator*(const Matrix&lt;scalarType, m, n, std::array&lt;scalarType, m* n&gt;&gt;&amp; A, const Matrix&lt;scalarType, p, q, std::array&lt;scalarType, p* q&gt;&gt;&amp; B) { if (n != p) throw std::logic_error(&quot;Error multiplying the matrices; the number of cols(A) must equal the number of rows(B)!&quot;); Matrix&lt;scalarType, m, q, std::array&lt;scalarType, m* q&gt;&gt; result; for (int i{}; i &lt; m; ++i) { for (int k{}; k &lt; p; ++k) { scalarType sum{}; for (int j{}; j &lt; n; ++j) { sum += A(i, j) * B(j, k); } result(i, k) = sum; } } return result; } #endif // !Matrix_H </code></pre> <h2>TestMatrix.cpp</h2> <pre><code>// MatrixImpl.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include &lt;iostream&gt; #include &quot;Matrix.h&quot; #include &lt;iomanip&gt; int main() { MatrixXi m1(3,3); m1 &lt;&lt;1, 0, 0, 0, 1, 0, 0, 0, 1; MatrixXi m2{ 3,3 }; //m2 = m1; m2 &lt;&lt; 2, 0, 0, 0, 1, 0, 0, 0, 3; MatrixXi m3 = m1 + m2; for (int i{}; i &lt; 3; ++i) { for (int j{}; j &lt; 3; ++j) { std::cout &lt;&lt; std::setw(5) &lt;&lt; m3(i, j); } std::cout &lt;&lt; std::endl; } return 0; } </code></pre> <hr /> <p><strong>Update</strong>:</p> <p><a href="https://github.com/quantophile/mathlib/blob/main/src/MatrixX.h" rel="nofollow noreferrer">Source code</a></p> <p><a href="https://github.com/quantophile/mathlib/blob/main/tests/tests.cpp" rel="nofollow noreferrer">Unit Tests</a></p> <p><a href="https://quantophile.github.io/mathlib/api-doc/index.html" rel="nofollow noreferrer">Documentation</a></p>
[]
[ { "body": "<p>We have a stray <code>typename</code> keyword, that's considered incorrect by GCC 11:</p>\n<pre><code>template &lt;typename scalarType, int rowsAtCompileTime, int colsAtCompileTime&gt;\nclass Matrix&lt;typename scalarType, rowsAtCompileTime, colsAtCompileTime, std::array&lt;scalarType, rowsAtCompileTime* colsAtCompileTime&gt;&gt;\n// here\n</code></pre>\n<p>There are a few more instances of the same problem. Fixing these enables compilation.</p>\n<hr />\n<p>My main concern with the code is its ambition. We're actually providing two different types, but shoehorning them into the same template. It might be better to provide separate types for compile-time constant size matrices and run-time-sized ones.</p>\n<p>I would expect to see a <code>std::initializer_list</code> constructor, and I think that's more valuable than the <code>&lt;&lt;</code> operator. Fixed-size matrices perhaps ought to be constructible from an appropriate <code>std::array</code>, too (open question - do you want to make a copy or just refer to the data?).</p>\n<hr />\n<p>Please use <code>std::size_t</code> for dimensions rather than <code>int</code>.</p>\n<hr />\n<p>What's the <code>_size</code> member for? It's never assigned or used.</p>\n<hr />\n<p>There's no need to write <code>inline</code> when defining template functions.</p>\n<hr />\n<p>Missing functionality:</p>\n<ul>\n<li>I'd expect to see <code>+=</code>, <code>-=</code>, unary <code>+</code> and <code>-</code>; perhaps also scalar multiplication. Probably implement <code>+</code> and <code>-</code> in terms of <code>+=</code> and <code>-=</code>.</li>\n<li>Dot-product and cross-product should be provided.</li>\n<li>A transpose function could be useful.</li>\n<li>A rectangular view of a matrix is also often useful.</li>\n<li>For square matrices, we might want to compute the determinant.</li>\n</ul>\n<p>Some of the extra functionality might be simpler if we can move to C++20 and use the <code>&lt;concepts&gt;</code> header to constrain templates.</p>\n<hr />\n<p>This isn't the best way to populate a vector:</p>\n<blockquote>\n<pre><code>template&lt;typename scalarType&gt;\ninline Matrix&lt;scalarType, 0, 0, std::vector&lt;scalarType&gt;&gt;::Matrix(int m, int n) : _rows{ m }, _cols{ n }\n{\n int numOfElements{ m * n };\n for (int i{}; i &lt; numOfElements; ++i)\n {\n A.push_back(0);\n }\n\n currentPosition = A.begin();\n}\n</code></pre>\n</blockquote>\n<p>We can make it more efficient using <code>A.reserve(numOfElements)</code>, but really we should just construct it with the right size (and no longer depend on being able to convert <code>0</code> to <code>T</code>):</p>\n<pre><code>template&lt;typename scalarType&gt;\ninline Matrix&lt;scalarType, 0, 0, std::vector&lt;scalarType&gt;&gt;::Matrix(std::size_t m, std::size_t n)\n : A(m * n),\n _rows{m}, _cols{n},\n currentPosition{A.begin()}\n{\n}\n</code></pre>\n<hr />\n<p>Something that will make the code much more useful is the ability to <em>promote</em> a matrix, e.g. from <code>Matrix&lt;int&gt;</code> to <code>Matrix&lt;long&gt;</code> (of the same dimensions). At present, the binary operations require two matrices of the same type, but they become a lot more powerful when we can put two different matrices together and get a result of their common type.</p>\n<p>It's also a good idea to provide (<code>explicit</code>) narrowing conversions too.</p>\n<hr />\n<p>The tests at present exercise only a small subset of the functionality. Consider learning to use one of the available test frameworks to get a more comprehensive set of self-checking unit tests. That's a whole subject in itself, but a very valuable skill to acquire.</p>\n<p>When expanding the tests, remember to include some tests where <code>T</code> is an aggregate type such as <code>std::complex</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T12:56:13.300", "Id": "532805", "Score": "0", "body": "[`std::span`](//en.cppreference.com/w/cpp/container/span) is an example of a class having such a dichotomy. Arguably, all allocator-aware containers would also apply, ymmv. ..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T12:55:03.747", "Id": "532883", "Score": "0", "body": "@TobySpeight, I implemented row(A, i) and col(A, j) operations that return by value. But, I also would like these methods, such that they can be on the left-hand side of an expression. Do you think it's possible to achieve this with the current implementation?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T13:40:00.553", "Id": "532887", "Score": "0", "body": "Sounds like a good self-review. Yes, it does make sense to make assignable versions of those functions - that would fall out naturally if you implement the rectangular views (since rows and cols are just special cases of such views)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T16:50:22.407", "Id": "269921", "ParentId": "269914", "Score": "5" } }, { "body": "<blockquote>\n<p>I overloaded the &lt;&lt; and , operators, in a way that a matrix objects can be nicely initialized...</p>\n</blockquote>\n<p>How's that any nicer than just using an initializer list or variadic parameter list in the constructor?</p>\n<hr />\n<p>Your trivial member functions like <code>size</code> would be much simpler if coded inline in the class.</p>\n<hr />\n<p>Your test code only tests one operation?<br />\nAnd, your need for nested loops in the test to print out the result shows that you need a element iterator supplied as part of the class.</p>\n<hr />\n<p>Yes, you should abstract out the choice of container by using a <strong>base class</strong> that only holds the representation and any necessary functions for manipulating the container; then a single implementation of all the interesting math functions and simple accessors can be written in universal code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T15:12:33.583", "Id": "269952", "ParentId": "269914", "Score": "1" } } ]
{ "AcceptedAnswerId": "269921", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T14:21:05.220", "Id": "269914", "Score": "6", "Tags": [ "c++", "matrix", "mathematics", "c++17" ], "Title": "Writing a C++ Matrix class" }
269914
<p>I wrote a simple neural network binary classification algorithm using Pytorch. It uses the dataset from <a href="https://www.kaggle.com/pritsheta/heart-attack" rel="nofollow noreferrer">https://www.kaggle.com/pritsheta/heart-attack</a>, which consists of a table with 300 rows and 14 columns. The final column, 'target', is the training goal and indicates whether this patient has a hearth disease.</p> <p>I define two classes, CustomDataset and NeuralNet. The CustomDataset modifies the data into Pytorch tensors. This is done by standardizing the columns containing quantities and one-hot-encoding the columns containing categorical data.</p> <p>The NeuralNet class represents a fully connected neural network with a hidden layer and a sigmoid function at the end.</p> <p>Furthermore, the function get_accuracy() gets the fraction of correctly predicted labels. Finally, I create a loop that trains the neural network and plot the losses and accuracies.</p> <pre><code>from torch.utils.data import DataLoader,Dataset,random_split from torch import Generator,nn import torch import pandas as pd from matplotlib import pyplot as plt import numpy as np class CustomDataset(Dataset): def __init__(self,file): &quot;&quot;&quot; Reads the csv with data and converts it to tensors. There are 3 types of columns: self.cols_standardize : Columns for which the values will be standardized self.cols_binary: Columns with binary values self.cols_ohe: Columns with categorical data. Will be converted to one hot encoding &quot;&quot;&quot; self.data = pd.read_csv(file) #Set colums to take into account self.cols_standardize = ['age','trestbps','chol','thalach','oldpeak'] self.cols_binary = ['sex','exang','fbs'] self.cols_ohe = ['cp','restecg','slope','ca','thal'] #Create empty tensor ohe_num_classes = self.data[self.cols_ohe].nunique().values self.x_cols_num = len(self.cols_standardize) + len(self.cols_binary) + ohe_num_classes.sum() self.x = torch.empty((len(self.data),self.x_cols_num), dtype=torch.float64) #Add standardized values means = self.data[self.cols_standardize].mean() stds = self.data[self.cols_standardize].std() x_std = (self.data[self.cols_standardize] - means)/stds self.x[:,:x_std.shape[1]] = torch.from_numpy(x_std.values) current_col = x_std.shape[1] #Add binary values x_bin = self.data[self.cols_binary] self.x[:,current_col:current_col+x_bin.shape[1]] = torch.from_numpy(x_bin.values) current_col += x_bin.shape[1] #Add ohe values ohe_data = torch.from_numpy(self.data[self.cols_ohe].values.astype(np.int64)) for i,num_classes in enumerate(ohe_num_classes): x_ohe = nn.functional.one_hot(ohe_data[:,i],num_classes) self.x[:,current_col:current_col + x_ohe.shape[1]] = x_ohe current_col += x_ohe.shape[1] #Set target value to tensors self.y = torch.Tensor(self.data['target'].values) def __len__(self): return len(self.data) def __getitem__(self,idx): return self.x[idx], self.y[idx] class NeuralNet(nn.Module): &quot;&quot;&quot; Neural network with one hidden layer and a sigmoid function applied to the y_logits &quot;&quot;&quot; def __init__(self,input_size,hidden_size): super(NeuralNet,self).__init__() self.layer1 = nn.Linear(input_size,hidden_size) self.relu = nn.ReLU() self.layer2 = nn.Linear(hidden_size,1) self.out_layer = nn.Sigmoid() def forward(self,x): out = self.layer1(x.float()) out = self.relu(out) out = self.layer2(out) out = self.out_layer(out) return out def get_accuracy(y_true,y_prob): &quot;&quot;&quot; :param y_true: True values for y :param y_prob: Estimated values for y :return: Accuracy of estimation &quot;&quot;&quot; y_estimate = y_prob &gt; 0.5 return (y_true == y_estimate).sum() / y_true.size(0) if __name__ == '__main__': device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') #Set parameters learning_rate = 10e-3 num_epochs = 25 weight_decay = 10e-5 batch_size=32 hidden_layers = 10 #Create dataset dataset = CustomDataset('data.csv') #Split dataset into train and test data train_split = 0.8 train_len = round(train_split*len(dataset)) train_data,test_data = random_split(dataset,[train_len,len(dataset)-train_len],generator=Generator().manual_seed(0)) train_dataloader = DataLoader(train_data,batch_size=batch_size,shuffle=True) test_dataloader = DataLoader(test_data,batch_size=batch_size,shuffle=True) #Create model model = NeuralNet(dataset.x_cols_num,hidden_layers).to(device) criterion = nn.BCELoss() optimizer = torch.optim.Adam(model.parameters(),lr=learning_rate,weight_decay=weight_decay) #Train model accs = [] losses = [] for epoch in range(num_epochs): print('Epoch ',epoch) for i, (x,y) in enumerate(train_dataloader): model.train() optimizer.zero_grad() yhat = model(x) loss = criterion(yhat[:,0],y) loss.backward() optimizer.step() losses.append(loss.item()) #Get accuracy with torch.no_grad(): x_test = test_data[:][0] y_test = test_data[:][1] y_pred = model(x_test)[:,0] acc = get_accuracy(y_test,y_pred) print(f'test set accuracy: {acc}') accs.append(acc.item()) #Plot results plt.figure() plt.plot(accs) plt.plot(losses) plt.legend(['test set accuracy','loss']) </code></pre> <p>Since this is my first time working with Pytorch, i'm quite sure there are many suggestions for improvement and everything is welcome. However, I am particularly interested in the following:</p> <ul> <li><strong>Machine learning wise improvements</strong>: I know there are probably many things to improve on this and my goal is not to build the perfect predictor. However, are there any standard things that basically everyone with a bit of experience would add, that I seem to be missing?</li> <li><strong>Conventions/standard coding/rookie mistakes</strong>: Are there any things that I am doing that are considered obsolete/stupid/overly complicated?</li> <li><strong>Code structure</strong>: I create 2 classes and 1 function. Does this seem oke as a structure, or is something else recommended?</li> </ul> <p>Thanks in advance for any feedback!</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T15:50:04.383", "Id": "269918", "Score": "0", "Tags": [ "python", "machine-learning", "neural-network", "pytorch" ], "Title": "Binary classification with pytorch" }
269918
<p>Let me just say this right off the bat: <strong>If-Else</strong> is often a poor choice. It leads to complicated designs, less readable code, and may be pain inducing to refactor.</p> <p>The objective of this method is to make a panel in green color if the candidate has exceeded a volume and if he has spoken in a non-stop manner greater than two seconds of silence. The panel become red if a candidate is speaking, then it stops without reaching the minimum second threshold to talk or we have a silence about suddenly I want to write this method in another way so that it is more readable and easy to understand.</p> <p><strong>Here is the code :</strong></p> <pre><code>private Stopwatch stopSpeach = new Stopwatch(); private Stopwatch startSpeach = new Stopwatch(); bool startTimer = false; void SoundInput() { if (VolumeMicro &gt; NumVolume_Minimum.Value) { if (startTimer) { stopSpeech.Restart(); } else { startTimer = true; startSpeech.Restart(); stopSpeech.Restart(); } } else if (startTimer &amp;&amp; stopSpeech.ElapsedMilliseconds &gt; numericUpDown_WaitStop.Value) { if (panel_Timer.BackColor != Color.Red) { SetInfoPanel(Color.Red); } startTimer = false; } if (startTimer &amp;&amp; startSpeech.ElapsedMilliseconds &gt; numericUpDown_WaitStart.Value) { if (panel_Timer.BackColor != Color.Green &amp;&amp; stopSpeech.ElapsedMilliseconds &lt; 100) SetInfoPanel(Color.Green); if (VolumeMicro &gt; NumVolume_Maximum.Value &amp;&amp; panel_Timer.BackColor != Color.Green) SetInfoPanel(Color.Orange); } } </code></pre> <p>I thought about getting rid of the previous code and using a <strong>dictionary</strong> :</p> <pre><code> public void PerformOp(string operationName) { var operations = new Dictionary&lt;string, Action&gt;(); operations[&quot;green&quot;] = () =&gt; { SetInfoPanel(Color.Green); }; operations[&quot;red&quot;] = () =&gt; { SetInfoPanel(Color.Red); }; operations[&quot;orange&quot;] = () =&gt; { SetInfoPanel(Color.Red); }; operations[operationName].Invoke(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T00:17:18.117", "Id": "532757", "Score": "2", "body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state the task accomplished by the code. Please see [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask), as well as [How to get the best value out of Code Review: Asking Questions](https://codereview.meta.stackexchange.com/q/2436/120114) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T01:44:04.677", "Id": "532759", "Score": "1", "body": "Speach like, speech?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T07:07:25.350", "Id": "532776", "Score": "0", "body": "(Have a spelling checker help you.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T09:27:36.587", "Id": "532788", "Score": "0", "body": "@Reinderien yes" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T10:40:26.317", "Id": "532795", "Score": "0", "body": "I would recommend you to always use braces `{}` where you can, even if your `if`s body only contains one line of code. It just makes the entire code more readable and consistent." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T13:14:29.977", "Id": "533114", "Score": "0", "body": "I would say that this is a procedural approach. You might want to consider switching to an object-oriented approach. Maybe make a `Speech` class with methods like `Start()`, `Stop()` and `Elapsed()` and an `InfoPanel` class with a method like `SetColor(speechTime)`." } ]
[ { "body": "<blockquote>\n<p>I thought about getting rid of the previous code and using a dictionary</p>\n</blockquote>\n<p>I have no idea how the second snippet is a rewrite of the first snippet. There is no contextual overlap whatsoever. But I'll review both snippets independently.</p>\n<hr />\n<h2>Snippet 2</h2>\n<pre><code>public void PerformOp(string operationName)\n{\n var operations = new Dictionary&lt;string, Action&gt;();\n operations[&quot;green&quot;] = () =&gt; { SetInfoPanel(Color.Green); };\n operations[&quot;red&quot;] = () =&gt; { SetInfoPanel(Color.Red); };\n operations[&quot;orange&quot;] = () =&gt; { SetInfoPanel(Color.Red); };\n operations[operationName].Invoke();\n}\n</code></pre>\n<p>What you have here is a <code>switch</code>. This is in essence a &quot;multiple <code>if</code>&quot;.</p>\n<pre><code>public void PerformOp(string operationName)\n{\n switch(operationName)\n {\n case &quot;green&quot;:\n SetInfoPanel(Color.Green);\n break;\n case &quot;orange&quot;:\n SetInfoPanel(Color.Orange);\n break;\n case &quot;red&quot;:\n SetInfoPanel(Color.Red);\n break;\n default:\n throw new Exception($&quot;Unknown operation name: ${operationName}&quot;);\n}\n</code></pre>\n<p>This achieves the same thing, without having to resort to a dictionary.</p>\n<p>However, there is still some things to review here.</p>\n<ul>\n<li><p>Notice how I added a <code>default</code> case to deal with unknown values. You should let the caller know when they use a bad value, instead of silently doing nothing (unless it makes contextual sense to do so).</p>\n</li>\n<li><p>Since you're dealing with a closed set of operation names, an enum would be relevant here.</p>\n</li>\n</ul>\n\n<pre><code>public enum OperationType { Green, Orange, Red };\n\npublic void PerformOp(OperationType operationType)\n{\n switch(operationType)\n {\n case OperationType.Green:\n SetInfoPanel(Color.Green);\n break;\n // ...\n }\n}\n</code></pre>\n<ul>\n<li>But then you realize that you're really just mapping one enum (<code>OperationType</code>) to another (<code>Color</code>). Maybe that's what you need here, if you want to strictly keep it do just those three colors and not every possible <code>Color</code> value. However, if any possible <code>Color</code> value goes, then you can simply cut out the middle man:</li>\n</ul>\n\n<pre><code>public void PerformOp(Color color)\n{\n SetInfoPanel(color);\n}\n</code></pre>\n<ul>\n<li>But at this point, there seems to be little purpose to the <code>PerformOp</code> method itself, no?</li>\n</ul>\n<hr />\n<h2>Snippet 1</h2>\n<p>The problem with this code is that it is very complex. You've broken a complex problem down into its constituent parts, but you've made no effort to describe the separate parts, which makes it impossible to follow.</p>\n<p>For the life of me, I don't understand what your code tries to achieve. I understand individual lines and evaluations, but not how one relates to another, and what the overall goal here is. For the sake of example, I'm going to invent descriptions here, to show you how you could've made this easier to parse. Obviously, rename them to suit your specific scenario.</p>\n<p>Whenever you're dealing with a non-trivial evaluation, try to store it in a boolean value that describes what it expresses. For example:</p>\n<pre><code>bool currentPlaybackExceedsUpperLimit = startTimer &amp;&amp; stopSpeech.ElapsedMilliseconds &gt; numericUpDown_WaitStop.Value;\n\nif (currentPlaybackExceedsUpperLimit)\n{\n if (panel_Timer.BackColor != Color.Red)\n {\n SetInfoPanel(Color.Red);\n }\n startTimer = false;\n}\n</code></pre>\n<p>The first <code>if</code> was complex, but now I can easily read what that evaluation means in human terms. The second <code>if</code>, however, is trivially readable, so there was no point to adding a boolean variable to describe it any further.</p>\n<p>In some cases, it makes sense to further separate the evaluations from the logic, and start using separate class methods/properties for this. Since you're dealing with a chain of operations here, that seems a valid reason to do so.</p>\n<p>As a second step, you can then also separate the actual resulting logic from the decision tree which decides what should be done. This means that you separate your monolith method into three different parts:</p>\n<ul>\n<li>The logic for evaluating the current state (= the <code>if</code> evaluations)</li>\n<li>The logic for mutating the current state (= the <code>if</code> bodies)</li>\n<li>The decision logic (= the <code>if</code> structure itself)</li>\n</ul>\n<p>The principle is the same as before, but instead of using a variable, you can also use a class method/property. The whole method could be rewritten as:</p>\n<pre><code>// The logic for evaluating the current state (= the `if` evaluations)\n\nprivate bool VolumeIsTooLoud =&gt; VolumeMicro &gt; NumVolume_Minimum.Value;\n\nprivate bool CurrentPlaybackExceedsUpperLimit =&gt;\n startTimer \n &amp;&amp; stopSpeech.ElapsedMilliseconds &gt; numericUpDown_WaitStop.Value;\n\nprivate bool CurrentPlaybackIsInProgress =&gt;\n startTimer \n &amp;&amp; startSpeech.ElapsedMilliseconds &gt; numericUpDown_WaitStart.Value;\n\n// The logic for mutating the current state (= the `if` bodies)\n\nprivate void RestartSpeech()\n{\n if (!startTimer)\n {\n startTimer = true;\n startSpeech.Restart();\n } \n \n stopSpeech.Restart();\n}\n\nprivate void FinishPlayback()\n{\n if (panel_Timer.BackColor != Color.Red)\n {\n SetInfoPanel(Color.Red);\n }\n startTimer = false;\n}\n\nprivate void ShowCurrentState()\n{\n if (panel_Timer.BackColor != Color.Green \n &amp;&amp; stopSpeech.ElapsedMilliseconds &lt; 100)\n {\n SetInfoPanel(Color.Green);\n }\n\n if (VolumeMicro &gt; NumVolume_Maximum.Value \n &amp;&amp; panel_Timer.BackColor != Color.Green)\n {\n SetInfoPanel(Color.Orange);\n }\n}\n\n// The decision logic (= the `if` structure itself)\n\nvoid SoundInput()\n{\n if (VolumeIsTooLoud)\n {\n RestartSpeech();\n }\n else if (CurrentPlaybackExceedsUpperLimit)\n {\n FinishPlayback();\n }\n\n if (CurrentPlaybackIsInProgress)\n {\n ShowCurrentState();\n }\n}\n</code></pre>\n<p>There are probably further improvements to be done here, but they require a more contextual understanding of the code, and I don't quite understand the specifics going on here.</p>\n<p>However, I hope this example makes it clear that by separating your code into smaller chunks that are more easily digestible and are clearly named, you can make significant improvements to the code's readability and maintainability.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T12:10:52.150", "Id": "532802", "Score": "0", "body": "Thanks it is vert helpful" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T10:56:35.837", "Id": "269943", "ParentId": "269919", "Score": "2" } } ]
{ "AcceptedAnswerId": "269943", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T15:59:02.420", "Id": "269919", "Score": "0", "Tags": [ "c#" ], "Title": "How to make this more readable with many if else" }
269919
<p>Currently working on a website with the following sorting function, but it's slow and reloads several times when I search for someone; how can I improve its performance? Or, more importantly, which parts of this function are slowing down the search?</p> <pre><code> const getFilteredPeople = ({ people, searchQuery, isMatch }) =&gt; { let list = people; if (searchQuery.length &gt; 0) { const searchTerm = searchQuery.trim().toLowerCase().split(/\s+/); list = people.filter((person) =&gt; isMatch(searchTerm, person)); } if (list) { return list.sort((a, b) =&gt; (a.knownAs || a.firstName).localeCompare(b.knownAs || b.firstName) ); } return []; }; </code></pre> <p>As for the arguments to that function where it's called: people:</p> <pre><code>const people = useSelector((state) =&gt; state.people.items); </code></pre> <p>searchQuery:</p> <p><em><strong>text input for person's name, added via useState hook</strong></em></p> <p>isMatch:</p> <pre><code> const isJobRoleMatch = (searchTerm, person) =&gt; { const personFrags = person.jobRole?.toLowerCase().split(/\s+/); return searchTerm.every((searchWord) =&gt; personFrags?.some((personJobRoleFragment) =&gt; personJobRoleFragment.includes(searchWord)) ); }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T23:33:07.967", "Id": "532755", "Score": "1", "body": "Welcome to CR! Showing a complete component would make it easier to help. How large is `people` and what sort of `searchQuery` is causing the performance trouble?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T16:21:42.627", "Id": "269920", "Score": "0", "Tags": [ "javascript", "performance", "sorting", "react.js" ], "Title": "React filter-and-search algorithm" }
269920
<p>This was the first time I dipped my toes into Spring Cloud Stream in combination with reactive programming via a reactive WebSocket client.</p> <p>It works in terms of general functionality - A subscriber to the topic receives the message payloads received via the WebSocket client - But I still have problems implementing a graceful shutdown when SIGINT is sent to the process.</p> <p>Due to me being new to reactive programming in Java (Only have experience using RxJS) I may have also taken a completely wrong approach when implementing my use case, so feedback on that would be greatly appreciated.</p> <h1>Main Application</h1> <pre><code>@SpringBootApplication class WebSocketSourceApplication { @Bean fun websocketPayloads(): Sinks.Many&lt;String&gt; = Sinks.many().unicast().onBackpressureBuffer() @PollableBean fun payloadSupplier(websocketPayloads: Sinks.Many&lt;String&gt;) = Supplier&lt;Flux&lt;String&gt;&gt; { websocketPayloads.asFlux() } } fun main(args: Array&lt;String&gt;) { runApplication&lt;WebSocketSourceApplication&gt;(*args) } </code></pre> <h1>WebSocketSession</h1> <pre class="lang-kotlin prettyprint-override"><code>private val log = KotlinLogging.logger {} @Component class WebSocketSession(val websocketPayloads: Sinks.Many&lt;String&gt;) : DisposableBean { private val socketSubscription: Disposable init { val client = ReactorNettyWebSocketClient() val webSocketUri = URI.create(&quot;wss://websocketserver&quot;) socketSubscription = client.execute(webSocketUri) { session -&gt; session.receive() .doOnEach { message -&gt; message.get()?.let { websocketPayloads.tryEmitNext(it.payloadAsText) } } .then() }.subscribe() } override fun destroy() { log.info { &quot;Closing websocket&quot; } socketSubscription.dispose() } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T17:09:08.620", "Id": "269925", "Score": "0", "Tags": [ "kotlin", "spring", "reactive-programming" ], "Title": "Reactive Spring Cloud Stream WebSocket Source Service" }
269925
<p>I'm a developer who has completed almost one year of full-stack development &amp; learning. I published my very first package lately, and I don't know is my code good or bad. So I jumped down here.</p> <p>EditorJS is block based medium-like rich text editor, <a href="https://editorjs.io/" rel="nofollow noreferrer">so here's a link to it.</a></p> <p>The package gets the JSON input, passes to official handler then handles array of blocks. Everything works around an array of blocks. My approach to handle these blocks is collection. At the root we have a block class to handle blocks It self, at the middle collection of blocks and at the top of that main EditorJS class wrapper. For sample JSON output, you can look at tests directory.</p> <p>I hope I explained it well enough. I just need a little review of my code. Don't worry It's a small package, so It's not complex. Here's the Github repository of my code; <a href="https://github.com/megasteve19/editorjs-php" rel="nofollow noreferrer">Github repository</a>.</p> <h3>Block class</h3> <pre class="lang-php prettyprint-override"><code>&lt;?php namespace Megasteve19\EditorJS\Block; { /** * Base class for all block types. * * @author megasteve19 */ class Block { /** * @var string The block's unique ID. */ private string $id; /** * @var string Type of the block. */ private string $type; /** * @var array Data of the block. */ private array $data; /** * Constructor * * @param array $block The block data to fill the object with. * @return void */ public function __construct(array $block) { $this-&gt;id = uniqid('editorjs'); $this-&gt;type = $block['type']; $this-&gt;data = $block['data'] ?? []; } /** * Get the block's unique ID. * * @return string */ public function getId() { return $this-&gt;id; } /** * Get the block's type. * * @return string */ public function getType() { return $this-&gt;type; } /** * Get the block's data. * * @return array */ public function getData() { return $this-&gt;data; } /** * Rescurively search for a specific key in the block's data. * Syntax: `$block-&gt;find('key1.key2.key3')`. * * @param string $key The key to get the data from. * @return array|string The data or empty string if not found. */ public function find(string $key) { $data = $this-&gt;data; $keys = explode('.', $key); foreach($keys as $key) { if(isset($data[$key])) $data = $data[$key]; else return ''; } return $data; } /** * Inserts a new data key into the block's data. * Syntax: `$block-&gt;insert('key1.key2.key3', $value)`. * * @param string $key The key to insert. * @param mixed $value The value to insert. * @return void */ public function insert(string $key, $value) { $keys = explode('.', $key); $data = &amp;$this-&gt;data; foreach($keys as $key) { if(empty($data[$key])) { $data[$key] = []; } $data = &amp;$data[$key]; } if(empty($data)) { $data = $value; } } /** * Update the block's data with a new one. * Syntax: `$block-&gt;update('key1.key2.key3', $newData)`. * * @param string $key The key to replace the data. * @param mixed $data The new data. * @return void */ public function update(string $key, $newData) { $data = &amp;$this-&gt;data; $keys = explode('.', $key); foreach($keys as $key) { if(isset($data[$key])) $data = &amp;$data[$key]; else return; } $data = $newData; } /** * Remove a key from the block's data. * Syntax: `$block-&gt;remove('key1.key2.key3')`. * * @param string $key The key to remove. * @return void */ public function remove(string $key) { $keys = explode('.', $key); $lastKey = array_pop($keys); $data = &amp;$this-&gt;data; foreach($keys as $key) { if(empty($data[$key])) { return; } $data = &amp;$data[$key]; } // Unset if the key exists. if(!empty($data[$lastKey])) { unset($data[$lastKey]); } } /** * Convert the block to an array. * * @return array Converted block. */ public function toArray() { return [ 'type' =&gt; $this-&gt;type, 'data' =&gt; $this-&gt;data ]; } /** * Renders HTML from the block. * * @param string $templatePath The path to the template file. * @return string The HTML. */ public function toHTML(string $templatePath) { if(file_exists($templatePath)) { ob_start(); extract($this-&gt;data, EXTR_SKIP); include $templatePath; return ob_get_clean(); } return ''; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T18:41:08.030", "Id": "532729", "Score": "0", "body": "Welcome to Code Review! I [changed the title](https://codereview.stackexchange.com/revisions/269929/3) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T18:41:59.910", "Id": "532730", "Score": "0", "body": "Thank you, sorry for all of that" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T18:45:22.267", "Id": "532732", "Score": "1", "body": "honestly, I still find it hard to guess what this class is supposed to do. What blocks? of cheese? of chocolate? ;-) Perhaps explaining what `type` may be would be useful. then explain briefly what are the most common operations that your app performs on these blocks. Cheers!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T04:46:05.330", "Id": "532767", "Score": "0", "body": "EditorJS is block based rich text editor, what I mean by blocks is; block-level HTML tags, header, paragraph, lists and goes on." } ]
[ { "body": "<p>Your package builds on the <code>getBlocks()</code> method of EditorJS. You get all blocks, which represent HTML tags and their content, and you render it as HTML output using PHP template files. The ugly code is probably hidden in these templates?</p>\n<p>You have not explained why you would want to access the content of a block using a stringed key. What is the practical use of that?</p>\n<p>Anyway, I have noticed several things:</p>\n<p>In four methods; <code>find()</code>, <code>insert()</code>, <code>update()</code> and <code>remove()</code>, you use very similar ways to get at the data. Why not use a private method for this, so you don't have to repeat yourself? Something like:</p>\n<pre><code>private function accessData($key)\n{\n $data = &amp;$this-&gt;data;\n $pins = explode('.', $key);\n foreach($pins as $pin) {\n $data = &amp;$data[$pin] ?? NULL;\n }\n return $data;\n}\n</code></pre>\n<p>I used <code>$pins</code> instead of <code>$keys</code>, because it is weird when a single key consists out of multiple keys. It makes more sense to say that one key has multiple pins. I also use the new <a href=\"https://www.php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op\" rel=\"nofollow noreferrer\">null coalescing operator</a> because this is a perfect place to use it. You can now reuse this method in the four methods I mentioned before, making those a lot shorter.</p>\n<p>Personally I am not too fond of using extract, output buffering, and include some template file, for each block you want to translate to HTML. PHP will probably do this quite efficiently, but it seems a lot of hassle, and it is not very <a href=\"https://en.wikipedia.org/wiki/Object-oriented_programming\" rel=\"nofollow noreferrer\">OOP</a>. Now that you have your blocks in PHP, why not use the power of OOP?</p>\n<p>Instead of using <code>include()</code> why not use <a href=\"https://www.php.net/manual/en/function.spl-autoload-register.php\" rel=\"nofollow noreferrer\">spl_autoload_register()</a> to load template classes? For instance, when the class name, for rendering an item list, is 'ListBlock&quot;, and the PHP file in which that class is defined is called &quot;listblock.php&quot;, you could use something like this:</p>\n<pre><code>function blockToHtml($className)\n{\n $path = __DIR__.'/templates/'.strtolower($className).'.php';\n if (is_readable($path)) require($path);\n}\n\nspl_autoload_register('blockToHtml');\n</code></pre>\n<p>You can now convert the data to HTML in a PHP class, using something like this inside your <code>Block</code> class:</p>\n<pre><code>public function toHTML($htmlVersion = 5)\n{\n $classname = $this-&gt;getType().'Block';\n $template = new {$classname}($this-&gt;getData());\n return $template-&gt;toHTML($htmlVersion);\n}\n</code></pre>\n<p>There are advantages to doing it this way. As you can see I supply <code>$htmlVersion</code> as a parameter to the <code>toHTML()</code>. This is just an example, but you can do a lot more in the template class now. You could, for instance define a <code>toXML()</code> method. One template class could also call another template class. This code is just more flexible, and fully OOP.</p>\n<p>I see this a lot in programmers starting with OOP. They program some parts of their code very neatly, and even implement tests, but other parts are just old school stuff while there's no need for that. Old habits die hard.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T13:09:18.563", "Id": "532806", "Score": "0", "body": "Why not write directly to `$this->data` instead of declaring a reference variable `$data`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T14:34:32.990", "Id": "532817", "Score": "1", "body": "@mickmackusa You mean in my `accessData()` method? That is because the original data cannot be used multiple times if you overwrite it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T14:35:26.930", "Id": "532818", "Score": "0", "body": "I must not be following the logic then. Is it not the same as this: https://3v4l.org/TDVF9 ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T14:36:52.720", "Id": "532819", "Score": "1", "body": "@mickmackusa: All it does is return a part of the data array given a key." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T14:40:00.653", "Id": "532820", "Score": "0", "body": "About templates, yes bot no :). It would be great for package but not for MVC. Other than that I'm agree with you, I was using bitwise operators for the first time so I didn't moved away to a new method. Thanks for your time!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T16:56:04.533", "Id": "532828", "Score": "0", "body": "@megasteve Sorry, I don't understand the connection with MVC? The [separation of concerns](https://en.wikipedia.org/wiki/Separation_of_concerns) stays the same as in your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T19:48:19.587", "Id": "532838", "Score": "0", "body": "As I said It's a great idea for package, normally I was coding this for my CodeIgniter project. So It was optimized for work with views, It's too easy to add templates in views; thus It can be too customizable. But I'm gonna change in repo, your idea makes more sense :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T20:51:38.940", "Id": "532841", "Score": "0", "body": "@megasteve Ah, I understand. That information was missing from your question." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T10:44:05.860", "Id": "269942", "ParentId": "269929", "Score": "3" } } ]
{ "AcceptedAnswerId": "269942", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T18:06:17.897", "Id": "269929", "Score": "2", "Tags": [ "php", "json" ], "Title": "Handling Medium-like text editor output at backend" }
269929
<p>I have never tried this before. Just started with Kotlin and Android CameraX. Here is a fragment I would like some feedback on so I can writer safer and better Kotlin code.</p> <pre><code>package com.name.app.maincontroller import android.Manifest import android.annotation.SuppressLint import android.content.Context import android.content.pm.PackageManager import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageButton import androidx.camera.core.* import androidx.camera.lifecycle.ProcessCameraProvider import androidx.camera.view.PreviewView import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.lifecycle.LifecycleOwner import com.name.app.persistentdata.getOutputDirectory import java.io.* import java.text.SimpleDateFormat import java.util.* import java.util.concurrent.Executors import kotlin.random.Random const val height: Int = 175 const val width: Int = 100 class CameraActivityFragment : Fragment() { private val permissions = listOf(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO) private val permissionsRequestCode = Random.nextInt(0, 10000) private var isRecording = false private val videoCapture = VideoCapture.Builder().build() private lateinit var cameraCaptureButton: ImageButton private lateinit var cameraPreview: PreviewView private lateinit var cameraProvider: ProcessCameraProvider private lateinit var preview: Preview private val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA private fun setRecordVideoListener() { // Disable all camera controls cameraCaptureButton.setOnClickListener { it.isEnabled = false if (!isRecording) { isRecording = true cameraCaptureButton.setBackgroundResource(R.drawable.ic_shutter_pressed) it.invalidate() startRecording() } else { isRecording = false cameraCaptureButton.setBackgroundResource(R.drawable.ic_shutter_normal) it.invalidate() stopRecording() } // Re-enable camera controls it.isEnabled = true } } @SuppressLint(&quot;RestrictedApi&quot;) private fun startRecording() { val appName = resources.getString(R.string.app_name) val currentTime = System.currentTimeMillis() val videoFile = File( getOutputDirectory(requireActivity(), appName), SimpleDateFormat( &quot;yyyy-MM-dd-HH-mm-ss-SSS&quot;, Locale.US ).format(currentTime) + &quot;.mp4&quot; ) val outputOptions = VideoCapture.OutputFileOptions.Builder(videoFile).build() if (ActivityCompat.checkSelfPermission( requireContext(), Manifest.permission.RECORD_AUDIO ) != PackageManager.PERMISSION_GRANTED ) { return } videoCapture.startRecording(outputOptions, ContextCompat.getMainExecutor(activity), object : VideoCapture.OnVideoSavedCallback { override fun onError(videoCaptureError: Int, message: String, cause: Throwable?) { Log.e(TAG, &quot;Video capture failed: $message&quot;) } override fun onVideoSaved(outputFileResults: VideoCapture.OutputFileResults) { } }) } @SuppressLint(&quot;RestrictedApi&quot;) private fun stopRecording() { videoCapture.stopRecording() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) cameraCaptureButton = view.findViewById(R.id.camera_capture_button) cameraPreview = view.findViewById(R.id.camera_preview) setRecordVideoListener() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_camera_activity, container, false) } @SuppressLint(&quot;UnsafeExperimentalUsageError&quot;) private fun bindVideoCapture() { // Create a new camera selector each time, enforcing lens facing try { // Apply declared configs to CameraX using the same lifecycle owner cameraProvider.bindToLifecycle( this as LifecycleOwner, cameraSelector, preview, videoCapture ) } catch (exc: Exception) { Log.e(&quot;BindVideoCapture&quot;, &quot;Use case binding failed&quot;, exc) } } private fun startCamera() { val cameraProviderFuture = ProcessCameraProvider.getInstance(requireContext()) cameraProviderFuture.addListener({ // Used to bind the lifecycle of cameras to the lifecycle owner cameraProvider = cameraProviderFuture.get() cameraProvider.unbindAll() // Set up the view finder use case to display camera preview preview = Preview.Builder() .build() try { bindVideoCapture() } catch (exc: Exception) { Log.e(&quot;TestCameraPytorch&quot;, &quot;Use case binding failed&quot;, exc) } preview.setSurfaceProvider(cameraPreview.surfaceProvider) }, ContextCompat.getMainExecutor(requireContext())) } override fun onResume() { super.onResume() // Request permissions each time the app resumes, since they can be revoked at any time if (!context?.let { hasPermissions(it) }!!) { activity?.let { ActivityCompat.requestPermissions( it, permissions.toTypedArray(), permissionsRequestCode ) } } else { startCamera() } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array&lt;out String&gt;, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == permissionsRequestCode &amp;&amp; hasPermissions(requireContext())) { startCamera() } else { activity?.finish() // If we don't have the required permissions, we can't run } } /** Convenience method used to check if all permissions required by this app are granted */ private fun hasPermissions(context: Context) = permissions.all { ContextCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED } companion object { private val TAG = MainActivity::class.java.simpleName } } </code></pre>
[]
[ { "body": "<p>I haven't worked with CameraX, so I'll just point out other things I noticed.</p>\n<hr />\n<p>In this code:</p>\n<pre><code> cameraCaptureButton.setOnClickListener {\n it.isEnabled = false\n if (!isRecording) {\n isRecording = true\n cameraCaptureButton.setBackgroundResource(R.drawable.ic_shutter_pressed)\n it.invalidate()\n startRecording()\n\n } else {\n isRecording = false\n cameraCaptureButton.setBackgroundResource(R.drawable.ic_shutter_normal)\n it.invalidate()\n stopRecording()\n }\n // Re-enable camera controls\n it.isEnabled = true\n }\n</code></pre>\n<p>It is poor practice for code clarity to use the implicit parameter name <code>it</code> in a multi-line lambda. In this case, you don't need to use it at all, so you don't need to name it, since it refers to the same object as the already-named property <code>cameraCaptureButton</code>.</p>\n<p>Also, disabling it and re-enabling it here in the listener won't accomplish anything because input processing is not handled concurrently with this code run on the main thread. Multiple taps that happen rapidly between two frames of the main thread will be queued and then all submitted in succession on the main thread. If your goal is to avoid the possibility of someone double-tapping the button faster than the state can be changed, you must use some sort of debouncing. (<a href=\"https://stackoverflow.com/a/60193549/506796\">See here</a> for example.)</p>\n<p>The <code>invalidate</code> calls are redundant because changing anything about the view's appearance (like setting the background) will invalidate it.</p>\n<hr />\n<p>If the only thing you're doing in <code>onCreateView</code> is inflating and returning a Layout, you can omit it completely and simply pass the layout to the super-class constructor:</p>\n<pre><code>class CameraActivityFragment : Fragment(R.layout.fragment_camera_activity)\n</code></pre>\n<hr />\n<p>This code in <code>onResume()</code> is self-contradictory:</p>\n<pre><code>!context?.let { hasPermissions(it) }!!\n</code></pre>\n<p>You use a null-safe call followed by a non-null assertion. Either you know the object is not null or you don't, but this code simultaneously communicates that you're not sure (<code>?.</code>) and then says that you are sure (<code>!!</code>). If you know it's not null, you should be bold and use it at the source like this:</p>\n<pre><code>!hasPermissions(context!!)\n</code></pre>\n<p>Incidentally, we know from the documentation of the Fragment lifecycle that <code>context</code> will not be null during lifecycle functions like <code>onResume</code>, so <code>context!!</code> is safe. However, Android provides <code>requireContext()</code> and <code>requireActivity()</code> functions that are preferable to <code>context!!</code> and <code>activity!!</code>, because they will provide better error messages if you use them in the wrong place. Also, since <code>!!</code> is so often a code smell, these functions help show your intent more deliberately without alarming anyone that's reviewing your code.</p>\n<p>In this related code:</p>\n<pre><code> activity?.let {\n ActivityCompat.requestPermissions(\n it, permissions.toTypedArray(), permissionsRequestCode\n )\n }\n</code></pre>\n<p>You demonstrate with <code>?.let</code> that you are unsure if <code>activity</code> might be null, and you don't want to do anything if it is null. If that were actually possible, your code would not start the camera and would not check permissions, so you'd just have kind of blank screen with no feedback to the user why nothing is happening indefinitely.</p>\n<p>If you were actually unsure of whether <code>activity</code> could be null, you would have a fallback action to take in the flow of how your app behaves to the user.</p>\n<p>But in actuality, we know the activity is not null during <code>onResume</code>, so you can use <code>requireActivity()</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T21:42:12.783", "Id": "269993", "ParentId": "269933", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T19:42:19.500", "Id": "269933", "Score": "3", "Tags": [ "android", "kotlin" ], "Title": "Fragment to control and show camera images" }
269933
<p>I have implemented a simple pattern matching for the below algorithm in Java with time complexity of O(n)(n is the size of the input array).</p> <p>Any suggestions for optimization??</p> <p><strong>one of the most important aspects of accurately matching records to candidates is ensuring that the name in the record matches the name or a known alias of the candidate. In this exercise, you’ll build a method nameMatch() that receives an array of known names and a name from a record to match.</strong></p> <p><strong>The method should pass the following tests:</strong></p> <p><strong>1. Exact match</strong></p> <p>known_aliases = ['Alphonse Gabriel Capone', 'Al Capone']</p> <p>name_match(known_aliases, 'Alphonse Gabriel Capone') =&gt; True</p> <p>name_match(known_aliases, 'Al Capone') =&gt; True</p> <p>name_match(known_aliases, 'Alphonse Francis Capone') =&gt; False</p> <p><strong>2.Middle name missing (on alias)</strong></p> <p>known_aliases = ['Alphonse Capone']</p> <p>name_match(known_aliases, 'Alphonse Gabriel Capone') =&gt; True</p> <p>name_match(known_aliases, 'Alphonse Francis Capone') =&gt; True</p> <p>name_match(known_aliases, 'Alexander Capone') =&gt; False</p> <p><strong>3.Middle name missing (on record name)</strong></p> <p>known_aliases = ['Alphonse Gabriel Capone']</p> <p>name_match(known_aliases, 'Alphonse Capone') =&gt; True</p> <p>name_match(known_aliases, 'Alphonse Francis Capone') =&gt; False</p> <p>name_match(known_aliases, 'Alexander Capone') =&gt; False</p> <p><strong>4.More middle name tests</strong></p> <p>known_aliases = ['Alphonse Gabriel Capone', 'Alphonse Francis Capone']</p> <p>name_match(known_aliases, 'Alphonse Gabriel Capone') =&gt; True</p> <p>name_match(known_aliases, 'Alphonse Francis Capone') =&gt; True</p> <p>name_match(known_aliases, 'Alphonse Edward Capone') =&gt; False</p> <p><strong>5.Middle initial matches middle name</strong></p> <p>known_aliases = ['Alphonse Gabriel Capone', 'Alphonse F Capone']</p> <p>name_match(known_aliases, 'Alphonse G Capone') =&gt; True</p> <p>name_match(known_aliases, 'Alphonse Francis Capone') =&gt; True</p> <p>name_match(known_aliases, 'Alphonse E Capone') =&gt; False</p> <p>name_match(known_aliases, 'Alphonse Edward Capone') =&gt; False</p> <p>name_match(known_aliases, 'Alphonse Gregory Capone') =&gt; False</p> <p><strong>6. Transposition of middle name and first name, All of the test cases implemented previously also apply to the transposed name.</strong></p> <p><strong>'Gabriel Alphonse Capone' is a valid transposition of 'Alphonse Gabriel Capone'</strong></p> <p>known_aliases = ['Alphonse Gabriel Capone']</p> <p>name_match(known_aliases, 'Gabriel Alphonse Capone') =&gt; True</p> <p>name_match(known_aliases, 'Gabriel A Capone') =&gt; True</p> <p>name_match(known_aliases, 'Gabriel Capone') =&gt; True</p> <p>name_match(known_aliases, 'Gabriel Francis Capone') =&gt; False</p> <p><strong>7. Last name cannot be transposed</strong></p> <p><strong>'Alphonse Capone Gabriel' is NOT a valid transposition of 'Alphonse Gabriel Capone'<br /> 'Capone Alphonse Gabriel' is NOT a valid transposition of 'Alphonse Gabriel Capone'</strong></p> <p>known_aliases = ['Alphonse Gabriel Capone']</p> <p>name_match(known_aliases, 'Alphonse Capone Gabriel') =&gt; False</p> <p>name_match(known_aliases, 'Capone Alphonse Gabriel') =&gt; False</p> <p>name_match(known_aliases, 'Capone Gabriel') =&gt; False</p> <pre><code>public class PatternMatch { public boolean nameMatch(List&lt;String&gt; knownAliases, String name){ for(String alias : knownAliases){ if(nameMatch(name,alias)) return true; } return false; } private boolean nameMatch(String name, String alias){ //case7: lastName check String aliasLastName = extractLastName(alias); String lastName = extractLastName(name); if(aliasLastName.equalsIgnoreCase(lastName)){ String firstName = extractFirstName(name); String middleName = extractMiddleName(name); //case6: transposition of middle name and first name, by swapping alias firstName and middleName if(firstNameAndMiddleNameMatch(firstName,middleName,extractFirstName(alias),extractMiddleName(alias))) return true; if(firstNameAndMiddleNameMatch(firstName,middleName,extractMiddleName(alias),extractFirstName(alias))) return true; } return false; } private boolean firstNameAndMiddleNameMatch(String firstName, String middleName, String aliasFirstName, String aliasMiddleName){ if(aliasFirstName == null || aliasFirstName.length() == 0) return false; boolean firstNameMatch = firstName.equalsIgnoreCase(aliasFirstName); if(firstNameMatch){ if(middleName!=null &amp;&amp; aliasMiddleName!=null){ //case1: exact match boolean middleNameMatch = middleName.equalsIgnoreCase(aliasMiddleName); //case5: Middle initial matches middle name boolean middleInitialsMatch = middleName.charAt(0) == aliasMiddleName.charAt(0); return middleNameMatch || middleInitialsMatch; } //case2 &amp; case3: middle name is missing return firstNameMatch; } return false; } private String extractFirstName(String name){ if(name == null || name.length() == 0) return null; String[] split = name.split(&quot; &quot;); return split[0]; } private String extractMiddleName(String name){ if(name == null || name.length() == 0) return null; String[] split = name.split(&quot; &quot;); StringBuilder sb = new StringBuilder(); for(int i =1;i&lt;split.length-1;i++){ sb.append(&quot; &quot;); sb.append(split[i]); } if(sb.length() == 0) return null; return sb.toString().trim(); } private String extractLastName(String name){ if(name == null || name.length() == 0) return null; String[] split = name.split(&quot; &quot;); return split[split.length-1]; } } </code></pre>
[]
[ { "body": "<p>your code looks fine - some minor issues:</p>\n<h2>test driven developement</h2>\n<p>if you have clear requirements, write test to validate them.</p>\n<blockquote>\n<p><em>&quot;The method should pass the following tests&quot;</em></p>\n</blockquote>\n<p>i hope you <strong>have these tests</strong> and just forgot to add them on the code review.</p>\n<h2>exception handling</h2>\n<p>instead of returning <code>null</code> you should throw an excpetion, namely <a href=\"https://docs.oracle.com/javase/7/docs/api/java/lang/IllegalArgumentException.html\" rel=\"nofollow noreferrer\">IllegalArgumentAexception</a>, if you don't you violate the <a href=\"https://clean-code-developer.com/grades/grade-3-yellow/#Principle_of_Least_Astonishment\" rel=\"nofollow noreferrer\">Principle of Least Astonishment</a>.</p>\n<p><code>if(name == null || name.length() == 0) throw new IllegalArgumentExcpetion(&quot;name must not be null&quot;);</code></p>\n<p><strong>Note</strong></p>\n<p>Java code convention says: <a href=\"https://www.oracle.com/java/technologies/javase/codeconventions-statements.html\" rel=\"nofollow noreferrer\">always use bracket on program flow control</a>:</p>\n<pre><code>if(name == null || name.length() == 0){\n throw new IllegalArgumentExcpetion(&quot;name must not be null&quot;);\n}\n</code></pre>\n<h2>Data Object</h2>\n<p>i would advise you to create a data object for your purpose. instead of using a <code>List&lt;String&gt; knownAliases</code> i would create a class <code>NameAlias</code> that gives you the proper access on your desired fields.</p>\n<pre><code>class NameAlias {\n String getFirstName();\n String getLastName();\n List&lt;String&gt; getMiddleNames(); //should it be rather a Set than a List?\n}\n</code></pre>\n<p>that would increase the readability of your test (of your code) and also increase performance since you need to split the input only once and can re-use the information then.</p>\n<p><strong>Note:</strong></p>\n<p>you split your input within every method <code>extractFirstName</code>, <code>extractMiddleName</code> and <code>extractLastName</code> - a DataModel class would do it <strong>only once</strong>!</p>\n<p><strong>Note 2:</strong></p>\n<p>within your data object you could also do the work for UpperCasting. Again it would be done only once instead for each check:</p>\n<pre><code>class NameAlias {\n ...\n String getFirstNameUpperCase(); \n //and so on...\n}\n</code></pre>\n<p><strong>Note 3</strong></p>\n<p>if you had a data object you could even reduce the error handling.</p>\n<pre><code>class NameAlias {\n ...\n boolean hasMiddleName();\n ...\n}\n</code></pre>\n<h2>Deeper Data Modelling?</h2>\n<p>instead of using <code>String</code> for a <strong>Name</strong> you could create a <code>class Name</code>. Especially when you have interactions (methods) with your name</p>\n<pre><code>class Name{ \n boolean startsWith(String capital);\n boolean isCapital(); //true if name.length==1, sorry, my english lacks here\n}\n</code></pre>\n<h2>more objects</h2>\n<p>the complexity of your code is high. You should try to reduce the complexity by separating your code into smaller pieces that belong together (objects).</p>\n<p>i am missing a <code>class FirstNameMatcher</code> that is responsible for... well, simply to check if your <code>NameAlias.firstName</code> matches. and of course Matcher for the other cases as well.</p>\n<pre><code>class FirstNameMatcher{\n boolean matches(NameAlias alias);\n}\n</code></pre>\n<p>aside from reducing mere complexity you would follow the <a href=\"https://clean-code-developer.com/grades/grade-2-orange/#Single_Responsibility_Principle_SRP\" rel=\"nofollow noreferrer\">single responsibility principle</a> .</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T14:46:35.190", "Id": "532903", "Score": "1", "body": "Thankyou soo much. This helps a lot" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T08:19:42.647", "Id": "269970", "ParentId": "269936", "Score": "3" } }, { "body": "<h2>null</h2>\n<p>Nulls can be useful, however they can also be more trouble than their worth.\nDo you really need to use null, or could you get away with using <code>&quot;&quot;</code> instead? Consider the impact this would have on your code for simplifying statements like this: <code>if(aliasFirstName == null || aliasFirstName.length() == 0)</code></p>\n<h2>Multiple middle names</h2>\n<p>Reading the test cases, it seems like a person may have a middle name, or not have a middle name. It doesn't appear like a person can have multiple middle names. Your code, however allows multiple middle names. Initially this sounds reasonable, because it makes sense that a person can have multiple middle names, however for the purposes of this it seems like scope creep. One of the biggest problems with scope creep like this is the ambiguity that it can introduce. What's the impact of having multiple middle names on rule 6?:</p>\n<blockquote>\n<p>Transposition of middle name and first name, All of the test cases implemented previously also apply to the transposed name</p>\n</blockquote>\n<p>From above, for single middle names, these should be true:</p>\n<ul>\n<li>alias('Alphonse Gabriel Capone'), name('Gabriel Alphonse Capone')</li>\n<li>alias('Alphonse Gabriel Capone'), name('Gabriel A Capone')</li>\n</ul>\n<p>Supporting middle names, for the alias('Alphonse Gabriel Francis Capone') what are the expected name matches?</p>\n<ul>\n<li>Alphonse Gabriel Francis Capone // This is the only one that works</li>\n<li>Gabriel Francis Alphonse Capone</li>\n<li>Gabriel Alphonse Francis Capone</li>\n<li>Francis Alphonse Gabriel Capone</li>\n<li>Francis Gabriel Alphonse Capone</li>\n</ul>\n<p>That's before considering the impact of rule 5 (Middle initial matches middle name).</p>\n<h2>Rule 5 - Middle initial matches middle name</h2>\n<p>The way you've implemented this seems a bit lax to me. Rather than matching an initial for the middle name, you're matching the first letter of the middle name, without considering how long that name is. This means that for the alias <code>&quot;Alphonse Gabriel Capone&quot;</code> it would match <code>&quot;Alphonse George Capone&quot;</code>. This seems wrong. Because of the way you've allowed multiple middle names, it would also match <code>&quot;Alphonse George isn't really my name Capone&quot;</code>.</p>\n<h2>Data cleansing</h2>\n<p>The inputs to your matching method might be validated by another class. But if not, then consider the impact a space in the wrong place could have on the matching process. Whilst a user would probably consider the following the same, the program treats them differently &quot;Alphonse Gabriel Capone&quot; and &quot; Alphonse Gabriel Capone&quot; because of the leading space.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T05:45:26.703", "Id": "532944", "Score": "0", "body": "returning `null` or `\"\"` seems both not satisfying - if it is not guaranteed that a value does return a valid value you should offer a check method `hasXxx()`. if `hasXxx` returns false and you call `getXxx()` logically an exception should be thrown (that what would be the least astounding behaviour) - alternativly you provide a wrapper object that supports this functionallity (namely: `Optional<Xxx>` has `isPresent()`). - i am mentioning this with deepest respect on your answer!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T08:46:37.957", "Id": "532958", "Score": "0", "body": "i like your comment about *code creep*" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T11:11:33.383", "Id": "532971", "Score": "1", "body": "@MartinFrank I mostly agree with you. I prefer `Optional` over `has/get` because it's less prone to race conditions in mutable objects. `Optional` allows you to represent a non-present object without worrying about null-pointers and flag to the caller this might happen. Some classes like `String` and `List` have a built in way of saying that they're empty. In your example you have `List<String> getMiddleNames()`. Does this throw if there's no middle names, or return an `emptyList()`? Sometimes I need to work the code to find the best fit but part of that is bottoming out the requirements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T11:16:52.440", "Id": "532972", "Score": "1", "body": "@MartinFrank as an aside... you really don't need the disclaimer, at least not with me, I've read enough of your stuff on here to respect your opinion and I've got a pretty thick skin, even against the dreaded down vote. 5 developers will have 5 ideas about the best solution... in my case at least sitting down at a problem 5 times will also often end up with 5 (often slightly) different solutions. It's all a journey." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T11:57:29.163", "Id": "532974", "Score": "0", "body": "thats sound like are a professional worker - i'm glad we can learn from each other :-)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T23:53:43.390", "Id": "270001", "ParentId": "269936", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T03:06:19.403", "Id": "269936", "Score": "3", "Tags": [ "java", "programming-challenge", "pattern-matching" ], "Title": "pattern matching coding challenge" }
269936
<p>I have used the factory pattern for one of my projects. I want to know if this is a good design or if my code can be improved to make it as fast as possible.</p> <p>I am not an expert in C#. This is what I came up with after 2 days of research, with lots of rewrites. What I want to ask is:<br /> Is this the right approach? Can I improve it to be faster and safer?</p> <p><strong>Source Problem:</strong> There is incoming data which includes JSON data. Data structure is like:</p> <pre><code>char.base {&quot;level&quot;: 20, &quot;name&quot;: &quot;somename&quot;} </code></pre> <p>What I call first <code>char.base</code> part is the module. There are 12 modules like this and each of them have different properties.</p> <pre><code>// ./Models/Model.cs namespace Example.Models { public abstract class Model { } } </code></pre> <p>Those 12 models have their own classes which uses this <code>Model</code> class as their base. Example Model:</p> <pre><code>// ./Models/Base.cs namespace Example.Models { public class Base : Model { public int Level { get; internal set; } public string? Name { get; internal set; } } } </code></pre> <p>Factory class:</p> <pre><code>namespace Example { internal abstract class Factory { public Type Type { get =&gt; typeof(Factory); } internal abstract void Deserialize(string json); } internal class Factory&lt;T&gt; : Factory where T : Model { public new Type Type { get =&gt; typeof(T); } private JsonSerializerOptions _options = new() { PropertyNameCaseInsensitive = true }; private Root _root { get; set; } internal Factory(Root root) { _root = root; } internal override void Deserialize(string json) { T? obj = JsonSerializer.Deserialize&lt;T&gt;(json, _options); if (obj == null) throw new ArgumentNullException($&quot;{typeof(T)} cannot be deserialized with the given data: {json}&quot;); _root.AddOrUpdate(obj); } } } </code></pre> <p>Finally Root class that gets the incoming data and sends to the right factory:</p> <pre><code>namespace Example { public class Root { private readonly Dictionary&lt;string, Factory&gt; ModelFactory; private readonly ConcurrentDictionary&lt;Type, Model&gt; Models = new(); public Root() { ModelFactory = new() { { &quot;char.base&quot;, new Factory&lt;Base&gt;(this) }, // 11 more like this }; } public void Parse(string text) { int i = text.IndexOf(' '); if (i &lt; 0) return; // text: char.base {...} // text: [module] [JSON] string module = text[..i].ToLower(); string json = text[(i + 1)..]; if (!ModelFactory.ContainsKey(module)) return; ModelFactory[module].Deserialize(json); } public T? Get&lt;T&gt;() where T : Model, new() { return (T)Models.GetOrAdd(typeof(T), _ =&gt; new T()); } internal void AddOrUpdate&lt;T&gt;(T value) where T : Model { Models.AddOrUpdate(typeof(T), value, (key, oldValue) =&gt; value); } } } </code></pre> <p>The codes that needs these models will get it like this:</p> <pre><code>var base = root.Get&lt;Base&gt;(); </code></pre> <p><strong>Edit</strong></p> <p>Here is some sample incoming data:</p> <pre><code>char.base { &quot;name&quot;: &quot;Valour&quot;, &quot;class&quot;: &quot;Warrior&quot;, &quot;subclass&quot;: &quot;Soldier&quot;, &quot;race&quot;: &quot;Elf&quot;, &quot;clan&quot;: &quot;wolf&quot;, &quot;pretitle&quot;: &quot;Testing &quot;, &quot;perlevel&quot;: 1000, &quot;tier&quot;: 1, &quot;remorts&quot;: 7 } </code></pre> <pre><code>char.vitals { &quot;hp&quot;: 100000, &quot;mana&quot;: 90000, &quot;moves&quot;: 41599 } </code></pre> <pre><code>comm.tick { } </code></pre> <p>There is nothing going on with the Model classes. Just some getter properties according to these JSON data.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T08:05:30.743", "Id": "532781", "Score": "0", "body": "Maybe I abstract generic model class would be more suitable?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T11:44:28.893", "Id": "532799", "Score": "0", "body": "Or maybe simple ```switch``` statement? But I will have to rewrite same code for every model with against with DRY coding?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T08:16:28.207", "Id": "532869", "Score": "1", "body": "Welcome to CodeReview! Could you please share with us two or three sample inputs and related `Model` derived classes? It would give us more context why did you choose Factory method." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T11:35:20.757", "Id": "532880", "Score": "0", "body": "`There are 12 modules like this and each of them have different properties.` can you give us two different samples of the `Json` data" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T11:56:44.547", "Id": "532881", "Score": "0", "body": "I added some sample data @PeterCsala" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T11:57:46.907", "Id": "532882", "Score": "0", "body": "I made an edit to the question @iSR5" } ]
[ { "body": "<p>I think you have over-engineered the problem. You don't need neither the <code>Factory</code> nor the <code>Factory&lt;T&gt;</code> classes.</p>\n<pre><code>public class Root\n{\n private readonly Dictionary&lt;string, Type&gt; ModelMapping;\n private readonly ConcurrentDictionary&lt;Type, Model&gt; Models = new();\n private readonly JsonSerializerOptions Options = new() { PropertyNameCaseInsensitive = true };\n\n public Root()\n {\n ModelMapping = new()\n {\n { &quot;char.base&quot;, typeof(Base) },\n // 11 more like this\n };\n }\n\n public void Parse(string text)\n {\n int separatorIdx = text.IndexOf(' ');\n if (separatorIdx &lt; 0) return;\n string module = text[..separatorIdx].ToLower();\n\n if (!ModelMapping.ContainsKey(module)) return;\n\n string json = text[(separatorIdx + 1)..];\n\n var parsed = Deserialize(json, ModelMapping[module]);\n Models.AddOrUpdate(ModelMapping[module], parsed, (key, oldValue) =&gt; parsed);\n }\n\n private Model Deserialize(string json, Type parseTo)\n =&gt; JsonSerializer.Deserialize(json, parseTo, Options) as Model\n ?? throw new ArgumentNullException($&quot;{parseTo} cannot be deserialized with the given data: {json}&quot;);\n\n public T? Get&lt;T&gt;() where T : Model, new()\n =&gt; (T)Models.GetOrAdd(typeof(T), _ =&gt; new T());\n}\n</code></pre>\n<ul>\n<li>I've replaced your <code>ModelFactory</code> to <code>ModelMapping</code> (maps <code>string</code> to <code>Type</code>)</li>\n<li>I've moved the <code>Deserialize</code> method from the <code>Factory</code> to here\n<ul>\n<li>I've also changed the return type from <code>void</code> to <code>Model</code></li>\n<li>Now the <code>Parse</code> can call the <code>AddOrUpdate</code> method</li>\n</ul>\n</li>\n<li>I've made the <code>Deserialize</code> work on <code>Type</code> rather than expecting a <code>T</code> type parameter</li>\n</ul>\n<hr />\n<p>I've used to following code for testing:</p>\n<pre><code>var @base = new Base { Name = &quot;test&quot;, Level = 20 };\nvar source = @&quot;char.base &quot; + JsonSerializer.Serialize(@base);\nvar root = new Root();\nroot.Parse(source);\nvar newBase = root.Get&lt;Base&gt;();\nConsole.WriteLine(newBase.Level == @base.Level);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T14:40:32.697", "Id": "532902", "Score": "1", "body": "Thanks. It seems I really over-engineered the problem. I always forget the easy method is the best method most of the time!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T15:27:10.300", "Id": "532904", "Score": "1", "body": "@Valour In addition of @Peter-Csala answer, It would be more feasible if you just make use of `JsonSerializerOptions` and add custom `JsonConverter` to work with these incoming `Json`. find out more about it here https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-converters-how-to?pivots=dotnet-6-0" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T19:33:13.857", "Id": "532915", "Score": "0", "body": "Can I use records instead of class in models with this code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T19:41:42.627", "Id": "532916", "Score": "0", "body": "@Valour yes you can." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T12:32:15.320", "Id": "269974", "ParentId": "269939", "Score": "2" } } ]
{ "AcceptedAnswerId": "269974", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T07:39:04.130", "Id": "269939", "Score": "0", "Tags": [ "c#", "factory-method" ], "Title": "Factory pattern to build multiple models" }
269939
<p>I am not sure how to accurately describe what this program does in just a few words, anyway this program is very simple and easy to use, what it does is very simple and it is good at it.</p> <p>Let me start from the beginning, I want to generate random pronounceable strings that closely resemble English text, and I want my program to be the best in this field in the world.</p> <p>And I did some researching and found Markov Chain to be the best way to implement my ideas, and Markov Chain needs a very large population to be useful/accurate, so after a countless Google searches I have found GCIDE, and pulled 105230 words from it.</p> <p>And I analyzed the corpus and used the data to write the pseudoword generation program. And it is very good, but the output of the letter mode has a probability of being unpronounceable, a probability that is higher than acceptable level. Let me be clear, I want the output to be exactly impossible to be unpronounceable, period.</p> <p>The morphology of English orthography is very complex, and it allows multiple consonant letters to be adjacent to each other, a word that can be pronounced must also be able to be completely syllabified, some consonant letters put together can fit in a single syllable at either the start and/or the end, some consonant letters put together can't fit in a syllable but can fit in the end of one syllable and the start of the next syllable. And some consonant letters put together do not make sense wherever they are, if they appear then the word can't be completely syllabified and is invalidated.</p> <p>It is very hard to accurately describe, whenever I see a random string of letters, I can tell if it is valid pronounceable word or garbage text, with 100% accuracy, the moment I see it.</p> <p>You can too, but the computer can't. This knowledge is implicit knowledge and very hard to explicitly write down, and I need to program it.</p> <p>And GCIDE is corpus, it collected various strings, most of the valid words, yet many are completely garbage text. For example, it includes acronyms (ALL CONSONANTS KIND), Roman Numerals, some made up words, some extremely rare foreign words that aren't valid in English standards...</p> <p>For example, acronyms like HTTP, FTP, TCP, FBI and something simple like Mr., Ms. and Dr. Let me be clear, they are all invalid words that aren't pronounceable at all, they are all invalid garbage text(the output of my program must be all lowercase, because Python is CASE SENSITIVE, and they don't make any sense in all lowercase).</p> <p>Sure, I know HTTP stands for HyperText Transfer Protocol, FTP: File Transfer Protocol, TCP: Transfer Control Protocol, FBI: Federal Bureau of Investigations... But how do you pronounce them? When you pronounce HTTP, aren't you pronouncing aitch, tee, tee, pee, or you can somehow actually pronounce a string of consonants with NO VOWELS? If they are considered pronounceable, then, PDLGFSTJ must also be considered pronounceable.</p> <p>And there are garbage text included in GCIDE like houyhnhnm and eschscholtzia...</p> <p>In short, I want to find all non-breaking consonants (consonant clusters that can be put into a single syllable) and which consonant can be put after which consonant and exactly how many of them can be put together without invalidating the string...</p> <p>Hard code the rules, and use the rules to filter out garbage text and monitor the text generation process.</p> <p>So I have written this program that helps me manually find non-breaking consonants.</p> <p>You will need this file:</p> <pre><code>{ &quot;r&quot;: 28755, &quot;n&quot;: 27823, &quot;t&quot;: 26506, &quot;l&quot;: 24402, &quot;c&quot;: 20898, &quot;d&quot;: 18615, &quot;s&quot;: 17766, &quot;m&quot;: 17102, &quot;p&quot;: 11882, &quot;g&quot;: 7839, &quot;b&quot;: 7734, &quot;v&quot;: 7294, &quot;nt&quot;: 7023, &quot;st&quot;: 6564, &quot;f&quot;: 5454, &quot;ss&quot;: 5181, &quot;h&quot;: 4820, &quot;ng&quot;: 4312, &quot;ll&quot;: 4237, &quot;bl&quot;: 3380, &quot;nd&quot;: 3315, &quot;nc&quot;: 3148, &quot;ph&quot;: 2974, &quot;tr&quot;: 2892, &quot;w&quot;: 2821, &quot;th&quot;: 2545, &quot;ch&quot;: 2536, &quot;z&quot;: 2518, &quot;pr&quot;: 2459, &quot;ct&quot;: 2413, &quot;k&quot;: 2109, &quot;sh&quot;: 2065, &quot;sc&quot;: 1961, &quot;rm&quot;: 1939, &quot;gr&quot;: 1907, &quot;x&quot;: 1907, &quot;sm&quot;: 1823, &quot;rt&quot;: 1762, &quot;cr&quot;: 1615, &quot;ns&quot;: 1561, &quot;sp&quot;: 1547, &quot;rr&quot;: 1433, &quot;br&quot;: 1394, &quot;rd&quot;: 1358, &quot;tt&quot;: 1292, &quot;ck&quot;: 1215, &quot;mp&quot;: 1214, &quot;pl&quot;: 1206, &quot;q&quot;: 1196, &quot;rn&quot;: 1157, &quot;str&quot;: 1074, &quot;nn&quot;: 1068, &quot;j&quot;: 1052, &quot;dr&quot;: 1047, &quot;rs&quot;: 1046, &quot;cl&quot;: 1029, &quot;pt&quot;: 1019, &quot;mm&quot;: 937, &quot;rc&quot;: 888, &quot;mb&quot;: 868, &quot;fl&quot;: 856, &quot;lt&quot;: 813, &quot;rg&quot;: 783, &quot;rb&quot;: 750, &quot;rl&quot;: 715, &quot;ff&quot;: 698, &quot;gl&quot;: 684, &quot;gn&quot;: 681, &quot;pp&quot;: 681, &quot;ngl&quot;: 665, &quot;fr&quot;: 639, &quot;sl&quot;: 625, &quot;nf&quot;: 614, &quot;ntr&quot;: 607, &quot;nch&quot;: 579, &quot;cc&quot;: 573, &quot;rp&quot;: 532, &quot;ld&quot;: 506, &quot;rv&quot;: 486, &quot;ps&quot;: 468, &quot;nv&quot;: 460, &quot;rch&quot;: 411, &quot;rk&quot;: 411, &quot;wh&quot;: 398, &quot;nth&quot;: 397, &quot;rh&quot;: 387, &quot;ght&quot;: 378, &quot;lm&quot;: 377, &quot;gg&quot;: 374, &quot;nl&quot;: 367, &quot;nk&quot;: 365, &quot;sk&quot;: 365, &quot;nr&quot;: 358, &quot;lv&quot;: 351, &quot;sn&quot;: 334, &quot;chr&quot;: 323, &quot;dl&quot;: 323, &quot;ntl&quot;: 323, &quot;ndr&quot;: 318, &quot;dd&quot;: 314, &quot;tch&quot;: 308, &quot;lc&quot;: 305, &quot;rf&quot;: 302, &quot;nh&quot;: 301, &quot;sw&quot;: 295, &quot;mpl&quot;: 291, &quot;bb&quot;: 277, &quot;mn&quot;: 270, &quot;scr&quot;: 270, &quot;rth&quot;: 260, &quot;dg&quot;: 246, &quot;sq&quot;: 242, &quot;ft&quot;: 241, &quot;nm&quot;: 238, &quot;cs&quot;: 231, &quot;ls&quot;: 229, &quot;nb&quot;: 229, &quot;xt&quot;: 219, &quot;nst&quot;: 218, &quot;thr&quot;: 218, &quot;mbr&quot;: 213, &quot;dn&quot;: 212, &quot;wn&quot;: 210, &quot;xp&quot;: 209, &quot;mph&quot;: 203, &quot;sph&quot;: 203, &quot;np&quot;: 200, &quot;rph&quot;: 200, &quot;ln&quot;: 199, &quot;rw&quot;: 197, &quot;gh&quot;: 195, &quot;mpr&quot;: 194, &quot;nw&quot;: 194, &quot;rsh&quot;: 192, &quot;bs&quot;: 191, &quot;gm&quot;: 191, &quot;lph&quot;: 190, &quot;lg&quot;: 188, &quot;tl&quot;: 186, &quot;sch&quot;: 184, &quot;lk&quot;: 182, &quot;nct&quot;: 178, &quot;tw&quot;: 178, &quot;ckl&quot;: 175, &quot;mbl&quot;: 174, &quot;lp&quot;: 171, &quot;wl&quot;: 170, &quot;ctr&quot;: 164, &quot;nthr&quot;: 162, &quot;kn&quot;: 160, &quot;wr&quot;: 158, &quot;nsh&quot;: 154, &quot;nq&quot;: 152, &quot;ndl&quot;: 151, &quot;xc&quot;: 147, &quot;mpt&quot;: 146, &quot;ttl&quot;: 146, &quot;stl&quot;: 145, &quot;lb&quot;: 143, &quot;ngr&quot;: 143, &quot;nstr&quot;: 143, &quot;ppr&quot;: 141, &quot;ncl&quot;: 136, &quot;ncr&quot;: 136, &quot;spr&quot;: 135, &quot;lf&quot;: 134, &quot;ppl&quot;: 133, &quot;nsp&quot;: 130, &quot;ddl&quot;: 127, &quot;nj&quot;: 127, &quot;phr&quot;: 123, &quot;dv&quot;: 122, &quot;chl&quot;: 120, &quot;dm&quot;: 120, &quot;xtr&quot;: 120, &quot;bd&quot;: 119, &quot;spl&quot;: 119, &quot;ffl&quot;: 114, &quot;npr&quot;: 113, &quot;phth&quot;: 107, &quot;sb&quot;: 106, &quot;nfr&quot;: 105, &quot;rst&quot;: 105, &quot;sth&quot;: 104, &quot;pn&quot;: 102, &quot;bbl&quot;: 97, &quot;nfl&quot;: 97, &quot;ts&quot;: 96, &quot;chn&quot;: 94, &quot;bst&quot;: 93, &quot;dj&quot;: 92, &quot;bt&quot;: 87, &quot;rrh&quot;: 86, &quot;tm&quot;: 86, &quot;rtl&quot;: 80, &quot;scl&quot;: 80, &quot;nz&quot;: 79, &quot;tf&quot;: 77, &quot;rtr&quot;: 74, &quot;shr&quot;: 74, &quot;sr&quot;: 74, &quot;nsc&quot;: 73, &quot;dw&quot;: 72, &quot;shm&quot;: 72, &quot;ml&quot;: 70, &quot;dh&quot;: 68, &quot;rdl&quot;: 68, &quot;zz&quot;: 67, &quot;ggl&quot;: 66, &quot;phl&quot;: 66, &quot;bj&quot;: 63, &quot;ffr&quot;: 63, &quot;wb&quot;: 63, &quot;xpl&quot;: 63, &quot;rpr&quot;: 62, &quot;tb&quot;: 62, &quot;ws&quot;: 62, &quot;xh&quot;: 62, &quot;sf&quot;: 60, &quot;cch&quot;: 59, &quot;mf&quot;: 59, &quot;thm&quot;: 59, &quot;cq&quot;: 58, &quot;ms&quot;: 58, &quot;chth&quot;: 56, &quot;ltr&quot;: 56, &quot;ngs&quot;: 56, &quot;nsl&quot;: 56, &quot;ds&quot;: 55, &quot;nsm&quot;: 53, &quot;sd&quot;: 53, &quot;tn&quot;: 53, &quot;wd&quot;: 53, &quot;nkl&quot;: 52, &quot;rpl&quot;: 52, &quot;rq&quot;: 52, &quot;rthr&quot;: 52, &quot;kl&quot;: 51, &quot;thl&quot;: 50, &quot;rcl&quot;: 49, &quot;sg&quot;: 49, &quot;ngn&quot;: 48, &quot;ttr&quot;: 48, &quot;df&quot;: 47, &quot;lch&quot;: 46, &quot;zzl&quot;: 46, &quot;cks&quot;: 45, &quot;bstr&quot;: 44, &quot;cn&quot;: 44, &quot;lr&quot;: 44, &quot;rfl&quot;: 44, &quot;shl&quot;: 44, &quot;ssl&quot;: 44, &quot;bc&quot;: 43, &quot;bm&quot;: 43, &quot;rj&quot;: 43, &quot;lh&quot;: 42, &quot;lw&quot;: 42, &quot;ntn&quot;: 42, &quot;rsp&quot;: 42, &quot;ckw&quot;: 41, &quot;stf&quot;: 41, &quot;tz&quot;: 41, &quot;ckb&quot;: 40, &quot;rgr&quot;: 40, &quot;shn&quot;: 40, &quot;stm&quot;: 40, &quot;db&quot;: 39, &quot;lth&quot;: 39, &quot;pst&quot;: 39, &quot;ggr&quot;: 38, &quot;kr&quot;: 38, &quot;pm&quot;: 38, &quot;wf&quot;: 38, &quot;ccl&quot;: 37, &quot;wk&quot;: 37, &quot;ghtl&quot;: 35, &quot;ngh&quot;: 34, &quot;npl&quot;: 34, &quot;nsw&quot;: 34, &quot;rbl&quot;: 34, &quot;rcr&quot;: 34, &quot;bn&quot;: 33, &quot;ckn&quot;: 33, &quot;ndm&quot;: 33, &quot;nsf&quot;: 33, &quot;pb&quot;: 33, &quot;rbr&quot;: 33, &quot;rdr&quot;: 33, &quot;wm&quot;: 33, &quot;xpr&quot;: 33, &quot;chm&quot;: 32, &quot;lst&quot;: 32, &quot;nds&quot;: 32, &quot;bh&quot;: 31, &quot;bv&quot;: 31, &quot;mv&quot;: 31, &quot;nbl&quot;: 31, &quot;rstr&quot;: 31, &quot;ssm&quot;: 31, &quot;ssn&quot;: 31, &quot;ckm&quot;: 30, &quot;gw&quot;: 30, &quot;ghtf&quot;: 29, &quot;ndw&quot;: 29, &quot;ngst&quot;: 29, &quot;nscr&quot;: 29, &quot;ptr&quot;: 29, &quot;rds&quot;: 29, &quot;tp&quot;: 29, &quot;bsc&quot;: 28, &quot;ctl&quot;: 28, &quot;llm&quot;: 28, &quot;nbr&quot;: 28, &quot;pf&quot;: 28, &quot;pw&quot;: 28, &quot;rpt&quot;: 28, &quot;rtm&quot;: 28, &quot;thw&quot;: 28, &quot;dst&quot;: 27, &quot;ndf&quot;: 27, &quot;nx&quot;: 27, &quot;rtn&quot;: 27, &quot;thn&quot;: 27, &quot;btr&quot;: 26, &quot;lsh&quot;: 26, &quot;mr&quot;: 26, &quot;mst&quot;: 26, &quot;ntm&quot;: 26, &quot;rct&quot;: 26, &quot;rz&quot;: 26, &quot;stw&quot;: 26, &quot;xs&quot;: 26, &quot;kh&quot;: 25, &quot;rgl&quot;: 25, &quot;rkl&quot;: 25, &quot;wt&quot;: 25, &quot;ckh&quot;: 24, &quot;hm&quot;: 24, &quot;ldr&quot;: 24, &quot;nchr&quot;: 24, &quot;nwr&quot;: 24, &quot;xcr&quot;: 24, &quot;llb&quot;: 23, &quot;llh&quot;: 23, &quot;ngb&quot;: 23, &quot;tst&quot;: 23, &quot;ccr&quot;: 22, &quot;gb&quot;: 22, &quot;gd&quot;: 22, &quot;ghb&quot;: 22, &quot;nkn&quot;: 22, &quot;thf&quot;: 22, &quot;ckf&quot;: 21, &quot;gs&quot;: 21, &quot;llf&quot;: 21, &quot;llw&quot;: 21, &quot;rnm&quot;: 21, &quot;sgr&quot;: 21, &quot;xl&quot;: 21, &quot;ckst&quot;: 20, &quot;mps&quot;: 20, &quot;ntw&quot;: 20, &quot;rsl&quot;: 20, &quot;sj&quot;: 20, &quot;ssb&quot;: 20, &quot;bf&quot;: 19, &quot;dc&quot;: 19, &quot;ngth&quot;: 19, &quot;rthw&quot;: 19, &quot;shb&quot;: 19, &quot;tc&quot;: 19, &quot;bp&quot;: 18, &quot;ckr&quot;: 18, &quot;dp&quot;: 18, &quot;ngt&quot;: 18, &quot;rgh&quot;: 18, &quot;ssp&quot;: 18, &quot;stn&quot;: 18, &quot;tg&quot;: 18, &quot;vr&quot;: 18, &quot;wp&quot;: 18, &quot;wth&quot;: 18, &quot;ww&quot;: 18, &quot;hl&quot;: 17, &quot;ndb&quot;: 17, &quot;pc&quot;: 17, &quot;rml&quot;: 17, &quot;rnl&quot;: 17, &quot;rtf&quot;: 17, &quot;ssw&quot;: 17, &quot;tbr&quot;: 17, &quot;ths&quot;: 17, &quot;xcl&quot;: 17, &quot;ckp&quot;: 16, &quot;ctn&quot;: 16, &quot;ldl&quot;: 16, &quot;md&quot;: 16, &quot;mw&quot;: 16, &quot;ndh&quot;: 16, &quot;ndn&quot;: 16, &quot;ngd&quot;: 16, &quot;psh&quot;: 16, &quot;rdn&quot;: 16, &quot;ssf&quot;: 16, &quot;cht&quot;: 15, &quot;lz&quot;: 15, &quot;nts&quot;: 15, &quot;rchl&quot;: 15, &quot;ssh&quot;: 15, &quot;bw&quot;: 14, &quot;dsh&quot;: 14, &quot;ghl&quot;: 14, &quot;hn&quot;: 14, &quot;hr&quot;: 14, &quot;kw&quot;: 14, &quot;lln&quot;: 14, &quot;nks&quot;: 14, &quot;ntsh&quot;: 14, &quot;rdw&quot;: 14, &quot;rfr&quot;: 14, &quot;rtw&quot;: 14, &quot;tchw&quot;: 14, &quot;dth&quot;: 13, &quot;gnm&quot;: 13, &quot;ldf&quot;: 13, &quot;mc&quot;: 13, &quot;mpn&quot;: 13, &quot;msh&quot;: 13, &quot;ngf&quot;: 13, &quot;ntf&quot;: 13, &quot;rdb&quot;: 13, &quot;rnb&quot;: 13, &quot;rnf&quot;: 13, &quot;rsc&quot;: 13, &quot;rsw&quot;: 13, &quot;shf&quot;: 13, &quot;stp&quot;: 13, &quot;tsh&quot;: 13, &quot;bbr&quot;: 12, &quot;cd&quot;: 12, &quot;cz&quot;: 12, &quot;ks&quot;: 12, &quot;lld&quot;: 12, &quot;mt&quot;: 12, &quot;nsv&quot;: 12, &quot;rdsh&quot;: 12, &quot;rsk&quot;: 12, &quot;rts&quot;: 12, &quot;rwh&quot;: 12, &quot;stb&quot;: 12, &quot;wc&quot;: 12, &quot;wsh&quot;: 12, &quot;ckt&quot;: 11, &quot;dgm&quot;: 11, &quot;ghtw&quot;: 11, &quot;kk&quot;: 11, &quot;lfr&quot;: 11, &quot;llr&quot;: 11, &quot;mscr&quot;: 11, &quot;ngm&quot;: 11, &quot;nkh&quot;: 11, &quot;nsk&quot;: 11, &quot;rchd&quot;: 11, &quot;rdf&quot;: 11, &quot;rdm&quot;: 11, &quot;rkm&quot;: 11, &quot;rps&quot;: 11, &quot;rscr&quot;: 11, &quot;rthl&quot;: 11, &quot;shw&quot;: 11, &quot;tchm&quot;: 11, &quot;wdr&quot;: 11, &quot;chs&quot;: 10, &quot;cksh&quot;: 10, &quot;dt&quot;: 10, &quot;ftl&quot;: 10, &quot;ghtn&quot;: 10, &quot;ghts&quot;: 10, &quot;km&quot;: 10, &quot;ksh&quot;: 10, &quot;lgr&quot;: 10, &quot;lpt&quot;: 10, &quot;mfl&quot;: 10, &quot;mh&quot;: 10, &quot;nchm&quot;: 10, &quot;ndst&quot;: 10, &quot;nph&quot;: 10, &quot;nsch&quot;: 10, &quot;pd&quot;: 10, &quot;phn&quot;: 10, &quot;rkn&quot;: 10, &quot;rsm&quot;: 10, &quot;rtz&quot;: 10, &quot;stc&quot;: 10, &quot;tchb&quot;: 10, &quot;td&quot;: 10, &quot;tpr&quot;: 10, &quot;tsp&quot;: 10, &quot;tv&quot;: 10, &quot;wnw&quot;: 10, &quot;xch&quot;: 10, &quot;btl&quot;: 9, &quot;ckd&quot;: 9, &quot;cm&quot;: 9, &quot;dsm&quot;: 9, &quot;dstr&quot;: 9, &quot;ftsm&quot;: 9, &quot;gf&quot;: 9, &quot;ghtm&quot;: 9, &quot;gt&quot;: 9, &quot;kt&quot;: 9, &quot;ldn&quot;: 9, &quot;lls&quot;: 9, &quot;msp&quot;: 9, &quot;nchn&quot;: 9, &quot;ndp&quot;: 9, &quot;nkf&quot;: 9, &quot;nshr&quot;: 9, &quot;ptl&quot;: 9, &quot;rkw&quot;: 9, &quot;rnst&quot;: 9, &quot;rwr&quot;: 9, &quot;sv&quot;: 9, &quot;thh&quot;: 9, &quot;vv&quot;: 9, &quot;wnl&quot;: 9, &quot;xb&quot;: 9, &quot;xf&quot;: 9, &quot;chw&quot;: 8, &quot;ckstr&quot;: 8, &quot;ctm&quot;: 8, &quot;ddr&quot;: 8, &quot;ghm&quot;: 8, &quot;ghth&quot;: 8, &quot;gp&quot;: 8, &quot;kb&quot;: 8, &quot;ldw&quot;: 8, &quot;llt&quot;: 8, &quot;ltl&quot;: 8, &quot;ngw&quot;: 8, &quot;nkb&quot;: 8, &quot;nwh&quot;: 8, &quot;rchw&quot;: 8, &quot;rmf&quot;: 8, &quot;rtb&quot;: 8, &quot;rtg&quot;: 8, &quot;sht&quot;: 8, &quot;sthm&quot;: 8, &quot;tfl&quot;: 8, &quot;wg&quot;: 8, &quot;wst&quot;: 8, &quot;xw&quot;: 8, &quot;bscr&quot;: 7, &quot;ctf&quot;: 7, &quot;ftm&quot;: 7, &quot;ghh&quot;: 7, &quot;ghn&quot;: 7, &quot;ghw&quot;: 7, &quot;gsh&quot;: 7, &quot;hs&quot;: 7, &quot;kf&quot;: 7, &quot;ldb&quot;: 7, &quot;ldh&quot;: 7, &quot;lkw&quot;: 7, &quot;llst&quot;: 7, &quot;mg&quot;: 7, &quot;nchl&quot;: 7, &quot;ngsh&quot;: 7, &quot;nkw&quot;: 7, &quot;nsgr&quot;: 7, &quot;nsn&quot;: 7, &quot;nspl&quot;: 7, &quot;nthl&quot;: 7, &quot;pbr&quot;: 7, &quot;pg&quot;: 7, &quot;pk&quot;: 7, &quot;ptn&quot;: 7, &quot;rchm&quot;: 7, &quot;rdc&quot;: 7, &quot;rdsm&quot;: 7, &quot;rld&quot;: 7, &quot;rsch&quot;: 7, &quot;rsn&quot;: 7, &quot;rthb&quot;: 7, &quot;skr&quot;: 7, &quot;thb&quot;: 7, &quot;tk&quot;: 7, &quot;zl&quot;: 7, &quot;bg&quot;: 6, &quot;bgl&quot;: 6, &quot;bk&quot;: 6, &quot;cb&quot;: 6, &quot;dk&quot;: 6, &quot;ftw&quot;: 6, &quot;ghf&quot;: 6, &quot;gnl&quot;: 6, &quot;gst&quot;: 6, &quot;hd&quot;: 6, &quot;hv&quot;: 6, &quot;hw&quot;: 6, &quot;lds&quot;: 6, &quot;lfl&quot;: 6, &quot;lkh&quot;: 6, &quot;llp&quot;: 6, &quot;lq&quot;: 6, &quot;lthf&quot;: 6, &quot;mfr&quot;: 6, &quot;mj&quot;: 6, &quot;nchb&quot;: 6, &quot;ndc&quot;: 6, &quot;ndsh&quot;: 6, &quot;ngc&quot;: 6, &quot;nkst&quot;: 6, &quot;ntz&quot;: 6, &quot;psk&quot;: 6, &quot;pstr&quot;: 6, &quot;rkb&quot;: 6, &quot;rks&quot;: 6, &quot;rnt&quot;: 6, &quot;schn&quot;: 6, &quot;sdr&quot;: 6, &quot;sfr&quot;: 6, &quot;shp&quot;: 6, &quot;stt&quot;: 6, &quot;tchl&quot;: 6, &quot;tcr&quot;: 6, &quot;tgr&quot;: 6, &quot;thdr&quot;: 6, &quot;thst&quot;: 6, &quot;tsc&quot;: 6, &quot;tsch&quot;: 6, &quot;tstr&quot;: 6, &quot;wdl&quot;: 6, &quot;xm&quot;: 6, &quot;xq&quot;: 6, &quot;zd&quot;: 6, &quot;btf&quot;: 5, &quot;ckc&quot;: 5, &quot;cksm&quot;: 5, &quot;cph&quot;: 5, &quot;dbr&quot;: 5, &quot;dch&quot;: 5, &quot;ddh&quot;: 5, &quot;dfl&quot;: 5, &quot;dz&quot;: 5, &quot;ffm&quot;: 5, &quot;fn&quot;: 5, &quot;ftn&quot;: 5, &quot;kst&quot;: 5, &quot;ldm&quot;: 5, &quot;lkm&quot;: 5, &quot;lks&quot;: 5, &quot;lsp&quot;: 5, &quot;ltm&quot;: 5, &quot;mbd&quot;: 5, &quot;mk&quot;: 5, &quot;mstr&quot;: 5, &quot;nctl&quot;: 5, &quot;nkm&quot;: 5, &quot;nsq&quot;: 5, &quot;pht&quot;: 5, &quot;pj&quot;: 5, &quot;pph&quot;: 5, &quot;rchb&quot;: 5, &quot;rchpr&quot;: 5, &quot;rkf&quot;: 5, &quot;rldl&quot;: 5, &quot;rnc&quot;: 5, &quot;rnp&quot;: 5, &quot;rnw&quot;: 5, &quot;rstl&quot;: 5, &quot;rthn&quot;: 5, &quot;rtsh&quot;: 5, &quot;rtsm&quot;: 5, &quot;shh&quot;: 5, &quot;skl&quot;: 5, &quot;sst&quot;: 5, &quot;tchf&quot;: 5, &quot;tj&quot;: 5, &quot;tsw&quot;: 5, &quot;tts&quot;: 5, &quot;vsk&quot;: 5, &quot;wbr&quot;: 5, &quot;wfl&quot;: 5, &quot;wnb&quot;: 5, &quot;wnh&quot;: 5, &quot;wnst&quot;: 5, &quot;wsl&quot;: 5, &quot;xd&quot;: 5, &quot;xn&quot;: 5, &quot;bq&quot;: 4, &quot;chf&quot;: 4, &quot;ckg&quot;: 4, &quot;ckj&quot;: 4, &quot;ckkn&quot;: 4, &quot;cksl&quot;: 4, &quot;cksw&quot;: 4, &quot;cp&quot;: 4, &quot;cst&quot;: 4, &quot;cth&quot;: 4, &quot;dspr&quot;: 4, &quot;ffs&quot;: 4, &quot;fgh&quot;: 4, &quot;fth&quot;: 4, &quot;ghbr&quot;: 4, &quot;ghtr&quot;: 4, &quot;kd&quot;: 4, &quot;lbl&quot;: 4, &quot;lbr&quot;: 4, &quot;lchr&quot;: 4, &quot;lcr&quot;: 4, &quot;ldsp&quot;: 4, &quot;lfp&quot;: 4, &quot;lgh&quot;: 4, &quot;lkl&quot;: 4, &quot;llfl&quot;: 4, &quot;ltf&quot;: 4, &quot;ltn&quot;: 4, &quot;ltz&quot;: 4, &quot;mbf&quot;: 4, &quot;mbm&quot;: 4, &quot;mcr&quot;: 4, &quot;mpb&quot;: 4, &quot;mpf&quot;: 4, &quot;mphl&quot;: 4, &quot;mphr&quot;: 4, &quot;mpk&quot;: 4, &quot;mpst&quot;: 4, &quot;nchp&quot;: 4, &quot;nck&quot;: 4, &quot;ndbr&quot;: 4, &quot;ndt&quot;: 4, &quot;nkg&quot;: 4, &quot;nkr&quot;: 4, &quot;nscl&quot;: 4, &quot;nspr&quot;: 4, &quot;ntc&quot;: 4, &quot;pch&quot;: 4, &quot;pfl&quot;: 4, &quot;pps&quot;: 4, &quot;rdh&quot;: 4, &quot;rgm&quot;: 4, &quot;rkr&quot;: 4, &quot;rksh&quot;: 4, &quot;rlb&quot;: 4, &quot;rlw&quot;: 4, &quot;rmn&quot;: 4, &quot;rms&quot;: 4, &quot;rnbl&quot;: 4, &quot;rnfl&quot;: 4, &quot;rnn&quot;: 4, &quot;rns&quot;: 4, &quot;rnsh&quot;: 4, &quot;rshr&quot;: 4, &quot;rtbr&quot;: 4, &quot;rthm&quot;: 4, &quot;rtstr&quot;: 4, &quot;schw&quot;: 4, &quot;sphr&quot;: 4, &quot;sthr&quot;: 4, &quot;stpl&quot;: 4, &quot;sts&quot;: 4, &quot;stsc&quot;: 4, &quot;tbl&quot;: 4, &quot;tchc&quot;: 4, &quot;tchp&quot;: 4, &quot;tdr&quot;: 4, &quot;thp&quot;: 4, &quot;tpl&quot;: 4, &quot;wch&quot;: 4, &quot;wnf&quot;: 4, &quot;wz&quot;: 4, &quot;xtl&quot;: 4, &quot;bch&quot;: 3, &quot;bcr&quot;: 3, &quot;bsp&quot;: 3, &quot;chb&quot;: 3, &quot;chh&quot;: 3, &quot;chst&quot;: 3, &quot;ckbr&quot;: 3, &quot;ckcl&quot;: 3, &quot;cksc&quot;: 3, &quot;cksk&quot;: 3, &quot;cksp&quot;: 3, &quot;ckth&quot;: 3, &quot;cts&quot;: 3, &quot;dsw&quot;: 3, &quot;ffh&quot;: 3, &quot;ffn&quot;: 3, &quot;ffsh&quot;: 3, &quot;ffw&quot;: 3, &quot;ftf&quot;: 3, &quot;fts&quot;: 3, &quot;gc&quot;: 3, &quot;ghfl&quot;: 3, &quot;ghg&quot;: 3, &quot;ghp&quot;: 3, &quot;ghtb&quot;: 3, &quot;ghtsh&quot;: 3, &quot;ghtsm&quot;: 3, &quot;gsk&quot;: 3, &quot;gtr&quot;: 3, &quot;gz&quot;: 3, &quot;hns&quot;: 3, &quot;hsh&quot;: 3, &quot;jp&quot;: 3, &quot;lcl&quot;: 3, &quot;lct&quot;: 3, &quot;ldcr&quot;: 3, &quot;ldp&quot;: 3, &quot;ldsh&quot;: 3, &quot;ldst&quot;: 3, &quot;ldt&quot;: 3, &quot;lfb&quot;: 3, &quot;lfh&quot;: 3, &quot;llbr&quot;: 3, &quot;lml&quot;: 3, &quot;lms&quot;: 3, &quot;lpf&quot;: 3, &quot;lpl&quot;: 3, &quot;lpr&quot;: 3, &quot;lsm&quot;: 3, &quot;lstr&quot;: 3, &quot;lthl&quot;: 3, &quot;ltp&quot;: 3, &quot;ltw&quot;: 3, &quot;lx&quot;: 3, &quot;mbk&quot;: 3, &quot;mpm&quot;: 3, &quot;mpsh&quot;: 3, &quot;mptr&quot;: 3, &quot;mq&quot;: 3, &quot;mth&quot;: 3, &quot;ncht&quot;: 3, &quot;ndg&quot;: 3, &quot;ndgr&quot;: 3, &quot;ndk&quot;: 3, &quot;ndsc&quot;: 3, &quot;ndsl&quot;: 3, &quot;ndsm&quot;: 3, &quot;ngcr&quot;: 3, &quot;ngk&quot;: 3, &quot;ngsp&quot;: 3, &quot;nksg&quot;: 3, &quot;nns&quot;: 3, &quot;nrh&quot;: 3, &quot;nsfr&quot;: 3, &quot;nskr&quot;: 3, &quot;nsph&quot;: 3, &quot;nssh&quot;: 3, &quot;ntb&quot;: 3, &quot;ntbr&quot;: 3, &quot;ntg&quot;: 3, &quot;ntsm&quot;: 3, &quot;pdr&quot;: 3, &quot;pgr&quot;: 3, &quot;psc&quot;: 3, &quot;psw&quot;: 3, &quot;pth&quot;: 3, &quot;pwr&quot;: 3, &quot;rchch&quot;: 3, &quot;rck&quot;: 3, &quot;rdpl&quot;: 3, &quot;rdt&quot;: 3, &quot;rgn&quot;: 3, &quot;rkh&quot;: 3, &quot;rlp&quot;: 3, &quot;rmh&quot;: 3, &quot;rmst&quot;: 3, &quot;rnd&quot;: 3, &quot;rsph&quot;: 3, &quot;rspr&quot;: 3, &quot;rtc&quot;: 3, &quot;rtgr&quot;: 3, &quot;rthd&quot;: 3, &quot;rthf&quot;: 3, &quot;rtp&quot;: 3, &quot;rx&quot;: 3, &quot;schr&quot;: 3, &quot;shg&quot;: 3, &quot;shwh&quot;: 3, &quot;skf&quot;: 3, &quot;skn&quot;: 3, &quot;skw&quot;: 3, &quot;spn&quot;: 3, &quot;ssc&quot;: 3, &quot;ssr&quot;: 3, &quot;sstr&quot;: 3, &quot;stcl&quot;: 3, &quot;std&quot;: 3, &quot;stscr&quot;: 3, &quot;sz&quot;: 3, &quot;tchh&quot;: 3, &quot;tchk&quot;: 3, &quot;tcl&quot;: 3, &quot;tq&quot;: 3, &quot;tsb&quot;: 3, &quot;tsm&quot;: 3, &quot;ttw&quot;: 3, &quot;wbl&quot;: 3, &quot;wgr&quot;: 3, &quot;wkn&quot;: 3, &quot;wnc&quot;: 3, &quot;wntr&quot;: 3, &quot;wpl&quot;: 3, &quot;wspr&quot;: 3, &quot;wstr&quot;: 3, &quot;wtr&quot;: 3, &quot;xg&quot;: 3, &quot;xsc&quot;: 3, &quot;xscr&quot;: 3, &quot;xsp&quot;: 3, &quot;zw&quot;: 3, &quot;bbs&quot;: 2, &quot;bcl&quot;: 2, &quot;bfl&quot;: 2, &quot;bgr&quot;: 2, &quot;bpr&quot;: 2, &quot;bsl&quot;: 2, &quot;bsph&quot;: 2, &quot;bz&quot;: 2, &quot;chbl&quot;: 2, &quot;chcl&quot;: 2, &quot;chd&quot;: 2, &quot;chwh&quot;: 2, &quot;ckcr&quot;: 2, &quot;ckfr&quot;: 2, &quot;ckgr&quot;: 2, &quot;ckpl&quot;: 2, &quot;cksn&quot;: 2, &quot;dcl&quot;: 2, &quot;dcr&quot;: 2, &quot;dph&quot;: 2, &quot;dpl&quot;: 2, &quot;dq&quot;: 2, &quot;dsc&quot;: 2, &quot;dscr&quot;: 2, &quot;dsk&quot;: 2, &quot;dsp&quot;: 2, &quot;dthw&quot;: 2, &quot;fb&quot;: 2, &quot;fc&quot;: 2, &quot;fd&quot;: 2, &quot;ffb&quot;: 2, &quot;ffc&quot;: 2, &quot;ffsc&quot;: 2, &quot;fft&quot;: 2, &quot;fk&quot;: 2, &quot;fm&quot;: 2, &quot;fpr&quot;: 2, &quot;fst&quot;: 2, &quot;ftb&quot;: 2, &quot;ftp&quot;: 2, &quot;gch&quot;: 2, &quot;gdr&quot;: 2, &quot;ggh&quot;: 2, &quot;ggsh&quot;: 2, &quot;ghc&quot;: 2, &quot;ghdr&quot;: 2, &quot;ghj&quot;: 2, &quot;ghr&quot;: 2, &quot;ghs&quot;: 2, &quot;ghsh&quot;: 2, &quot;ghtcl&quot;: 2, &quot;ghwr&quot;: 2, &quot;gnn&quot;: 2, &quot;gsd&quot;: 2, &quot;gsm&quot;: 2, &quot;hlb&quot;: 2, &quot;hmg&quot;: 2, &quot;hnn&quot;: 2, &quot;hrg&quot;: 2, &quot;jj&quot;: 2, &quot;kv&quot;: 2, &quot;ldbr&quot;: 2, &quot;ldc&quot;: 2, &quot;ldgr&quot;: 2, &quot;ldsm&quot;: 2, &quot;lfc&quot;: 2, &quot;lfk&quot;: 2, &quot;lfm&quot;: 2, &quot;lfn&quot;: 2, &quot;lft&quot;: 2, &quot;lfw&quot;: 2, &quot;lj&quot;: 2, &quot;lkc&quot;: 2, &quot;lkn&quot;: 2, &quot;llc&quot;: 2, &quot;llg&quot;: 2, &quot;llk&quot;: 2, &quot;llpr&quot;: 2, &quot;llsh&quot;: 2, &quot;lltr&quot;: 2, &quot;llwh&quot;: 2, &quot;lmm&quot;: 2, &quot;lmn&quot;: 2, &quot;lmsg&quot;: 2, &quot;lmsm&quot;: 2, &quot;lpm&quot;: 2, &quot;lsgr&quot;: 2, &quot;lsk&quot;: 2, &quot;lsw&quot;: 2, &quot;ltb&quot;: 2, &quot;ltc&quot;: 2, &quot;lts&quot;: 2, &quot;lwr&quot;: 2, &quot;mbb&quot;: 2, &quot;mbn&quot;: 2, &quot;mbsk&quot;: 2, &quot;mpstr&quot;: 2, &quot;mptl&quot;: 2, &quot;msk&quot;: 2, &quot;msm&quot;: 2, &quot;mz&quot;: 2, &quot;nchw&quot;: 2, &quot;ncm&quot;: 2, &quot;nctn&quot;: 2, &quot;ndcr&quot;: 2, &quot;ndd&quot;: 2, &quot;ndfl&quot;: 2, &quot;ndq&quot;: 2, &quot;ndsw&quot;: 2, &quot;ndthr&quot;: 2, &quot;ndwr&quot;: 2, &quot;ngstr&quot;: 2, &quot;ngthf&quot;: 2, &quot;ngthl&quot;: 2, &quot;ngthw&quot;: 2, &quot;ngtr&quot;: 2, &quot;nkp&quot;: 2, &quot;nksh&quot;: 2, &quot;nkt&quot;: 2, &quot;nnk&quot;: 2, &quot;nsd&quot;: 2, &quot;nsfl&quot;: 2, &quot;nsr&quot;: 2, &quot;nss&quot;: 2, &quot;nthm&quot;: 2, &quot;nxt&quot;: 2, &quot;pkn&quot;: 2, &quot;psp&quot;: 2, &quot;pspr&quot;: 2, &quot;ptf&quot;: 2, &quot;pthr&quot;: 2, &quot;pts&quot;: 2, &quot;rbst&quot;: 2, &quot;rchg&quot;: 2, &quot;rchn&quot;: 2, &quot;rchr&quot;: 2, &quot;rchsh&quot;: 2, &quot;rchtr&quot;: 2, &quot;rfm&quot;: 2, &quot;rghm&quot;: 2, &quot;rksm&quot;: 2, &quot;rkt&quot;: 2, &quot;rlst&quot;: 2, &quot;rmw&quot;: 2, &quot;rncr&quot;: 2, &quot;rng&quot;: 2, &quot;rnh&quot;: 2, &quot;rnwr&quot;: 2, &quot;rpn&quot;: 2, &quot;rpsh&quot;: 2, &quot;rsd&quot;: 2, &quot;rspl&quot;: 2, &quot;rsth&quot;: 2, &quot;rtcl&quot;: 2, &quot;rtd&quot;: 2, &quot;rthp&quot;: 2, &quot;rthq&quot;: 2, &quot;rthst&quot;: 2, &quot;sbl&quot;: 2, &quot;sbr&quot;: 2, &quot;sfl&quot;: 2, &quot;sgl&quot;: 2, &quot;shc&quot;: 2, &quot;shcl&quot;: 2, &quot;shk&quot;: 2, &quot;skm&quot;: 2, &quot;ssbl&quot;: 2, &quot;ssbr&quot;: 2, &quot;ssgr&quot;: 2, &quot;stbr&quot;: 2, &quot;stcr&quot;: 2, &quot;stgl&quot;: 2, &quot;stwh&quot;: 2, &quot;stwr&quot;: 2, &quot;swr&quot;: 2, &quot;tdw&quot;: 2, &quot;thbr&quot;: 2, &quot;thpl&quot;: 2, &quot;tkn&quot;: 2, &quot;tsk&quot;: 2, &quot;tsl&quot;: 2, &quot;tspr&quot;: 2, &quot;tth&quot;: 2, &quot;tthr&quot;: 2, &quot;twh&quot;: 2, &quot;twr&quot;: 2, &quot;tzp&quot;: 2, &quot;vl&quot;: 2, &quot;vts&quot;: 2, &quot;wgl&quot;: 2, &quot;wkb&quot;: 2, &quot;wkw&quot;: 2, &quot;wld&quot;: 2, &quot;wls&quot;: 2, &quot;wlw&quot;: 2, &quot;wnbr&quot;: 2, &quot;wnm&quot;: 2, &quot;wnp&quot;: 2, &quot;wns&quot;: 2, &quot;wnsm&quot;: 2, &quot;wnstr&quot;: 2, &quot;wsm&quot;: 2, &quot;wsp&quot;: 2, &quot;wsw&quot;: 2, &quot;wv&quot;: 2, &quot;xsh&quot;: 2, &quot;xst&quot;: 2, &quot;xth&quot;: 2, &quot;zc&quot;: 2, &quot;zt&quot;: 2, &quot;bcd&quot;: 1, &quot;bdr&quot;: 1, &quot;bfr&quot;: 1, &quot;blr&quot;: 1, &quot;bpl&quot;: 1, &quot;brd&quot;: 1, &quot;bsq&quot;: 1, &quot;bsw&quot;: 1, &quot;bth&quot;: 1, &quot;btm&quot;: 1, &quot;bwh&quot;: 1, &quot;cbm&quot;: 1, &quot;cf&quot;: 1, &quot;cg&quot;: 1, &quot;chc&quot;: 1, &quot;chcr&quot;: 1, &quot;chsh&quot;: 1, &quot;chsr&quot;: 1, &quot;chsst&quot;: 1, &quot;chtm&quot;: 1, &quot;chts&quot;: 1, &quot;chtsm&quot;: 1, &quot;ckch&quot;: 1, &quot;ckdr&quot;: 1, &quot;ckfl&quot;: 1, &quot;ckk&quot;: 1, &quot;cksch&quot;: 1, &quot;ckscr&quot;: 1, &quot;ckthr&quot;: 1, &quot;cktr&quot;: 1, &quot;ckwh&quot;: 1, &quot;cphr&quot;: 1, &quot;cthl&quot;: 1, &quot;ctsh&quot;: 1, &quot;ctz&quot;: 1, &quot;cw&quot;: 1, &quot;ddb&quot;: 1, &quot;ddf&quot;: 1, &quot;ddm&quot;: 1, &quot;ddn&quot;: 1, &quot;dds&quot;: 1, &quot;dfr&quot;: 1, &quot;dgl&quot;: 1, &quot;dgr&quot;: 1, &quot;dgsh&quot;: 1, &quot;dkn&quot;: 1, &quot;dpr&quot;: 1, &quot;dsl&quot;: 1, &quot;dsn&quot;: 1, &quot;dthl&quot;: 1, &quot;dthr&quot;: 1, &quot;dwh&quot;: 1, &quot;dzh&quot;: 1, &quot;fch&quot;: 1, &quot;ffbr&quot;: 1, &quot;ffd&quot;: 1, &quot;ffg&quot;: 1, &quot;ffpr&quot;: 1, &quot;ffsk&quot;: 1, &quot;ffspr&quot;: 1, &quot;fj&quot;: 1, &quot;fkl&quot;: 1, &quot;fnm&quot;: 1, &quot;fs&quot;: 1, &quot;fsk&quot;: 1, &quot;ftg&quot;: 1, &quot;ftgr&quot;: 1, &quot;fthl&quot;: 1, &quot;ftr&quot;: 1, &quot;ftsp&quot;: 1, &quot;ftt&quot;: 1, &quot;fw&quot;: 1, &quot;gfr&quot;: 1, &quot;ggn&quot;: 1, &quot;ggpl&quot;: 1, &quot;ggs&quot;: 1, &quot;ghch&quot;: 1, &quot;ghd&quot;: 1, &quot;ghsc&quot;: 1, &quot;ghsch&quot;: 1, &quot;ghsp&quot;: 1, &quot;ghst&quot;: 1, &quot;ghstr&quot;: 1, &quot;ghtc&quot;: 1, &quot;ghtcr&quot;: 1, &quot;ghtdr&quot;: 1, &quot;ghtg&quot;: 1, &quot;ghthl&quot;: 1, &quot;ghtj&quot;: 1, &quot;ghtpr&quot;: 1, &quot;ghtsc&quot;: 1, &quot;ghtst&quot;: 1, &quot;ghtt&quot;: 1, &quot;ghtv&quot;: 1, &quot;ghwh&quot;: 1, &quot;gj&quot;: 1, &quot;gk&quot;: 1, &quot;gnb&quot;: 1, &quot;gnc&quot;: 1, &quot;gnf&quot;: 1, &quot;gnh&quot;: 1, &quot;gnp&quot;: 1, &quot;gnsh&quot;: 1, &quot;gnt&quot;: 1, &quot;gsc&quot;: 1, &quot;gsl&quot;: 1, &quot;gsn&quot;: 1, &quot;gssp&quot;: 1, &quot;gsw&quot;: 1, &quot;gth&quot;: 1, &quot;gv&quot;: 1, &quot;gwh&quot;: 1, &quot;hf&quot;: 1, &quot;hj&quot;: 1, &quot;hlst&quot;: 1, &quot;hlw&quot;: 1, &quot;hmm&quot;: 1, &quot;hms&quot;: 1, &quot;hnhnm&quot;: 1, &quot;hrst&quot;: 1, &quot;hrw&quot;: 1, &quot;htr&quot;: 1, &quot;hvh&quot;: 1, &quot;jh&quot;: 1, &quot;jr&quot;: 1, &quot;kc&quot;: 1, &quot;kcr&quot;: 1, &quot;khs&quot;: 1, &quot;kpl&quot;: 1, &quot;kpr&quot;: 1, &quot;ksb&quot;: 1, &quot;ksd&quot;: 1, &quot;kthr&quot;: 1, &quot;lchm&quot;: 1, &quot;lddr&quot;: 1, &quot;lfcl&quot;: 1, &quot;lff&quot;: 1, &quot;lfs&quot;: 1, &quot;lfsb&quot;: 1, &quot;lfsk&quot;: 1, &quot;lfth&quot;: 1, &quot;lftht&quot;: 1, &quot;lftw&quot;: 1, &quot;lgl&quot;: 1, &quot;lkb&quot;: 1, &quot;lkf&quot;: 1, &quot;lkp&quot;: 1, &quot;lksh&quot;: 1, &quot;lksl&quot;: 1, &quot;lksr&quot;: 1, &quot;lkst&quot;: 1, &quot;lkt&quot;: 1, &quot;llcl&quot;: 1, &quot;lldr&quot;: 1, &quot;llfr&quot;: 1, &quot;llgr&quot;: 1, &quot;lll&quot;: 1, &quot;llpl&quot;: 1, &quot;llsn&quot;: 1, &quot;llsp&quot;: 1, &quot;llspr&quot;: 1, &quot;llsw&quot;: 1, &quot;llth&quot;: 1, &quot;llv&quot;: 1, &quot;llwr&quot;: 1, &quot;lmbr&quot;: 1, &quot;lmcr&quot;: 1, &quot;lmr&quot;: 1, &quot;lmsd&quot;: 1, &quot;lmsf&quot;: 1, &quot;lmsh&quot;: 1, &quot;lmw&quot;: 1, &quot;lnh&quot;: 1, &quot;lphl&quot;: 1, &quot;lphth&quot;: 1, &quot;lpn&quot;: 1, &quot;lptr&quot;: 1, &quot;lpw&quot;: 1, &quot;lsb&quot;: 1, &quot;lsc&quot;: 1, &quot;lshm&quot;: 1, &quot;lsl&quot;: 1, &quot;lsth&quot;: 1, &quot;ltch&quot;: 1, &quot;lths&quot;: 1, &quot;lthw&quot;: 1, &quot;ltsch&quot;: 1, &quot;ltschm&quot;: 1, &quot;ltsf&quot;: 1, &quot;ltspr&quot;: 1, &quot;ltst&quot;: 1, &quot;ltt&quot;: 1, &quot;lwh&quot;: 1, &quot;mbbr&quot;: 1, &quot;mbcl&quot;: 1, &quot;mbpr&quot;: 1, &quot;mbs&quot;: 1, &quot;mbscr&quot;: 1, &quot;mbsh&quot;: 1, &quot;mbst&quot;: 1, &quot;mcc&quot;: 1, &quot;mck&quot;: 1, &quot;mcl&quot;: 1, &quot;mdm&quot;: 1, &quot;mdr&quot;: 1, &quot;mmh&quot;: 1, &quot;mnl&quot;: 1, &quot;mnn&quot;: 1, &quot;mpbl&quot;: 1, &quot;mpc&quot;: 1, &quot;mpd&quot;: 1, &quot;mptn&quot;: 1, &quot;mpw&quot;: 1, &quot;msb&quot;: 1, &quot;msc&quot;: 1, &quot;msd&quot;: 1, &quot;msl&quot;: 1, &quot;mstv&quot;: 1, &quot;mtr&quot;: 1, &quot;mtsch&quot;: 1, &quot;mwh&quot;: 1, &quot;nchc&quot;: 1, &quot;nchf&quot;: 1, &quot;ncp&quot;: 1, &quot;ndch&quot;: 1, &quot;ndcl&quot;: 1, &quot;nddr&quot;: 1, &quot;ndgl&quot;: 1, &quot;ndj&quot;: 1, &quot;ndsbr&quot;: 1, &quot;ndsk&quot;: 1, &quot;ndsp&quot;: 1, &quot;ndspr&quot;: 1, &quot;ndsth&quot;: 1, &quot;ndstr&quot;: 1, &quot;ndth&quot;: 1, &quot;ndtr&quot;: 1, &quot;ndwh&quot;: 1, &quot;ngp&quot;: 1, &quot;ngsg&quot;: 1, &quot;ngthn&quot;: 1, &quot;ngthr&quot;: 1, &quot;ngtz&quot;: 1, &quot;ngwh&quot;: 1, &quot;nhh&quot;: 1, &quot;nkc&quot;: 1, &quot;nkfl&quot;: 1, &quot;nkpl&quot;: 1, &quot;nksm&quot;: 1, &quot;nkwr&quot;: 1, &quot;nnh&quot;: 1, &quot;nnw&quot;: 1, &quot;nnwfn&quot;: 1, &quot;nnwn&quot;: 1, &quot;nps&quot;: 1, &quot;nschl&quot;: 1, &quot;ntch&quot;: 1, &quot;ntd&quot;: 1, &quot;ntgr&quot;: 1, &quot;nths&quot;: 1, &quot;ntj&quot;: 1, &quot;ntt&quot;: 1, &quot;nttr&quot;: 1, &quot;ntv&quot;: 1, &quot;ntwh&quot;: 1, &quot;nxm&quot;: 1, &quot;nxr&quot;: 1, &quot;pbl&quot;: 1, &quot;pcl&quot;: 1, &quot;pfr&quot;: 1, &quot;phsl&quot;: 1, &quot;psl&quot;: 1, &quot;psm&quot;: 1, &quot;psn&quot;: 1, &quot;pspl&quot;: 1, &quot;psq&quot;: 1, &quot;ptc&quot;: 1, &quot;pthl&quot;: 1, &quot;ptm&quot;: 1, &quot;pv&quot;: 1, &quot;pwh&quot;: 1, &quot;ql&quot;: 1, &quot;rbs&quot;: 1, &quot;rchf&quot;: 1, &quot;rchp&quot;: 1, &quot;rdbr&quot;: 1, &quot;rdgr&quot;: 1, &quot;rdk&quot;: 1, &quot;rdp&quot;: 1, &quot;rdsp&quot;: 1, &quot;rdst&quot;: 1, &quot;rdsw&quot;: 1, &quot;rdv&quot;: 1, &quot;rfb&quot;: 1, &quot;rfd&quot;: 1, &quot;rff&quot;: 1, &quot;rfg&quot;: 1, &quot;rfh&quot;: 1, &quot;rfsk&quot;: 1, &quot;rggr&quot;: 1, &quot;rghb&quot;: 1, &quot;rghbr&quot;: 1, &quot;rghf&quot;: 1, &quot;rgschr&quot;: 1, &quot;rgst&quot;: 1, &quot;rkd&quot;: 1, &quot;rkscr&quot;: 1, &quot;rksp&quot;: 1, &quot;rlc&quot;: 1, &quot;rlcr&quot;: 1, &quot;rlf&quot;: 1, &quot;rlfr&quot;: 1, &quot;rlh&quot;: 1, &quot;rlk&quot;: 1, &quot;rll&quot;: 1, &quot;rmb&quot;: 1, &quot;rmc&quot;: 1, &quot;rmch&quot;: 1, &quot;rmcl&quot;: 1, &quot;rmg&quot;: 1, &quot;rmgl&quot;: 1, &quot;rmp&quot;: 1, &quot;rmpl&quot;: 1, &quot;rmr&quot;: 1, &quot;rmsp&quot;: 1, &quot;rmth&quot;: 1, &quot;rmthl&quot;: 1, &quot;rnbr&quot;: 1, &quot;rnk&quot;: 1, &quot;rnpl&quot;: 1, &quot;rnsm&quot;: 1, &quot;rnsn&quot;: 1, &quot;rnsp&quot;: 1, &quot;rnv&quot;: 1, &quot;rphr&quot;: 1, &quot;rpm&quot;: 1, &quot;rrf&quot;: 1, &quot;rrfl&quot;: 1, &quot;rrnh&quot;: 1, &quot;rrst&quot;: 1, &quot;rrw&quot;: 1, &quot;rsb&quot;: 1, &quot;rscht&quot;: 1, &quot;rschw&quot;: 1, &quot;rshb&quot;: 1, &quot;rshch&quot;: 1, &quot;rshl&quot;: 1, &quot;rshn&quot;: 1, &quot;rsht&quot;: 1, &quot;rsq&quot;: 1, &quot;rstb&quot;: 1, &quot;rstf&quot;: 1, &quot;rstn&quot;: 1, &quot;rstw&quot;: 1, &quot;rstwh&quot;: 1, &quot;rtcr&quot;: 1, &quot;rtgl&quot;: 1, &quot;rthbr&quot;: 1, &quot;rthc&quot;: 1, &quot;rthdr&quot;: 1, &quot;rthg&quot;: 1, &quot;rthh&quot;: 1, &quot;rthpl&quot;: 1, &quot;rthsh&quot;: 1, &quot;rthwh&quot;: 1, &quot;rtq&quot;: 1, &quot;rtsch&quot;: 1, &quot;rtst&quot;: 1, &quot;rtsw&quot;: 1, &quot;rtt&quot;: 1, &quot;rtwh&quot;: 1, &quot;rtwr&quot;: 1, &quot;schl&quot;: 1, &quot;schm&quot;: 1, &quot;schsch&quot;: 1, &quot;shd&quot;: 1, &quot;shfl&quot;: 1, &quot;shq&quot;: 1, &quot;shsk&quot;: 1, &quot;shst&quot;: 1, &quot;shv&quot;: 1, &quot;shz&quot;: 1, &quot;skc&quot;: 1, &quot;skj&quot;: 1, &quot;slt&quot;: 1, &quot;sml&quot;: 1, &quot;spb&quot;: 1, &quot;sscr&quot;: 1, &quot;ssfl&quot;: 1, &quot;ssg&quot;: 1, &quot;ssj&quot;: 1, &quot;sspl&quot;: 1, &quot;sspr&quot;: 1, &quot;sssh&quot;: 1, &quot;stfr&quot;: 1, &quot;stg&quot;: 1, &quot;stgr&quot;: 1, &quot;stkn&quot;: 1, &quot;stpr&quot;: 1, &quot;stsh&quot;: 1, &quot;stsph&quot;: 1, &quot;stv&quot;: 1, &quot;stz&quot;: 1, &quot;tchbl&quot;: 1, &quot;tchbr&quot;: 1, &quot;tchcr&quot;: 1, &quot;tchd&quot;: 1, &quot;tchdr&quot;: 1, &quot;tchfl&quot;: 1, &quot;tchn&quot;: 1, &quot;tchst&quot;: 1, &quot;tchstr&quot;: 1, &quot;tcht&quot;: 1, &quot;tfr&quot;: 1, &quot;tgl&quot;: 1, &quot;thbl&quot;: 1, &quot;thc&quot;: 1, &quot;thcl&quot;: 1, &quot;thcr&quot;: 1, &quot;thd&quot;: 1, &quot;thg&quot;: 1, &quot;thml&quot;: 1, &quot;thsh&quot;: 1, &quot;thsk&quot;: 1, &quot;thsm&quot;: 1, &quot;thsp&quot;: 1, &quot;tht&quot;: 1, &quot;thth&quot;: 1, &quot;thv&quot;: 1, &quot;tph&quot;: 1, &quot;tsf&quot;: 1, &quot;ttd&quot;: 1, &quot;ttm&quot;: 1, &quot;ttv&quot;: 1, &quot;tzg&quot;: 1, &quot;tzkr&quot;: 1, &quot;tzn&quot;: 1, &quot;tzschk&quot;: 1, &quot;tzsk&quot;: 1, &quot;vd&quot;: 1, &quot;vn&quot;: 1, &quot;wcl&quot;: 1, &quot;wdn&quot;: 1, &quot;wdst&quot;: 1, &quot;wgh&quot;: 1, &quot;wj&quot;: 1, &quot;wkl&quot;: 1, &quot;wks&quot;: 1, &quot;wksb&quot;: 1, &quot;wlb&quot;: 1, &quot;wldr&quot;: 1, &quot;wlf&quot;: 1, &quot;wll&quot;: 1, &quot;wln&quot;: 1, &quot;wlst&quot;: 1, &quot;wnd&quot;: 1, &quot;wng&quot;: 1, &quot;wnn&quot;: 1, &quot;wnr&quot;: 1, &quot;wnsf&quot;: 1, &quot;wnsh&quot;: 1, &quot;wnsl&quot;: 1, &quot;wnsp&quot;: 1, &quot;wnthr&quot;: 1, &quot;wq&quot;: 1, &quot;wsb&quot;: 1, &quot;wsc&quot;: 1, &quot;wsk&quot;: 1, &quot;wsr&quot;: 1, &quot;wss&quot;: 1, &quot;wthf&quot;: 1, &quot;wthr&quot;: 1, &quot;wwh&quot;: 1, &quot;wwr&quot;: 1, &quot;xfl&quot;: 1, &quot;xgl&quot;: 1, &quot;xk&quot;: 1, &quot;xr&quot;: 1, &quot;xstr&quot;: 1, &quot;xsw&quot;: 1, &quot;xthl&quot;: 1, &quot;xtm&quot;: 1, &quot;xx&quot;: 1, &quot;zg&quot;: 1, &quot;zj&quot;: 1, &quot;zm&quot;: 1, &quot;zn&quot;: 1, &quot;zp&quot;: 1, &quot;zq&quot;: 1, &quot;zv&quot;: 1, &quot;zzs&quot;: 1 } </code></pre> <p>In short I used this regex '[bcdfghjklmnpqrstvwxyz]+' on the comma joined corpus to find all consonant chunks and turned it into a <code>Counter</code> and sorted it in the order of <code>(-x[1], x[0])</code> and dumped it using <code>json</code>( all in one line).</p> <h2>Program</h2> <pre class="lang-py prettyprint-override"><code>import json import re import sys from pathlib import Path from PyQt6.QtCore import * from PyQt6.QtGui import * from PyQt6.QtWidgets import * from PyQt6.sip import delete DIRECTORY = str(Path(__file__).absolute().parent).replace('\\', '/') ALIGNMENT = Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop FLAG = Qt.ItemFlag QGROUPBOXHIGHLIGHT = &quot;&quot;&quot; QGroupBox { border: 3px groove #4080ff; border-radius: 6px; background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.75, x3: 0, y3: 1, stop: 0 #4080c0, stop: 0.75 #0080c0, stop: 1 #4080c0); } QLabel { border: 0px solid black; color: #00ffff; } &quot;&quot;&quot; QGROUPBOXNORMAL = &quot;&quot;&quot; QGroupBox { border: 3px groove #204080; border-radius: 6px; background: #002050; } QLabel { border: 0px solid black; color: #87CEEB; } &quot;&quot;&quot; MAINSTYLE = &quot;&quot;&quot; QFrame {{ border: 3px groove #123456; border-radius: 6px; }} QHeaderView::section {{ background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #004060, stop: 1 #102372); color: #00ffff; border: 4px groove #102030; padding-left: 4px; }} QTableWidget {{ background: #002050; alternate-background-color: #200050; show-decoration-selected: 1; }} QTableWidget QTableCornerButton::section {{ background-color: #003b6f; border: 2px solid #202040; }} QTableWidget::indicator {{ border: 0px solid black; width: 16px; height: 16px; }} QTableWidget::indicator:unchecked {{ image: url({0}/icons/checkbox-unchecked.png); }} QTableWidget::indicator:checked {{ image: url({0}/icons/checkbox-checked.png); }} QTableWidget::indicator:indeterminate {{ image: url({0}/icons/checkbox-indeterminate.png); }} QTableWidget::indicator:hover {{ background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.75, x3: 0, y3: 1, stop: 0 #4080c0, stop: 0.75 #b2ffff, stop: 1 #4080c0); }} QTableWidget::item {{ border: 2px groove #204080; height: 20px; color: #73b0c8; }} QTableWidget::item:hover {{ background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #244872, stop: 1 #00c0ff); color: #b2ffff; border: 2px groove #bfcde4; }} QTableWidget::item:selected {{ border: 3px groove #4080ff; border-radius: 6px; background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.75, x3: 0, y3: 1, stop: 0 #4080c0, stop: 0.75 #0080c0, stop: 1 #4080c0); color: #00ffff; }} QScrollBar::vertical {{ border: 2px solid #204060; background: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #004060, stop: 1 #00b2e4); position: absolute; width: 16px; }} QScrollBar::handle:vertical {{ min-height: 32px; background: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #00c0ff, stop: 1 #102372); margin: 18px; }} QTextEdit {{ border: 2px solid #306090; border-radius: 6px; background: #202040; color: #b2ffff; }} QGroupBox {{ border: 3px groove #204080; border-radius: 6px; background: #002050; color: #b2ffff; }} QGroupBox::title {{ top: 3px; left: 3px; }} QGroupBox::indicator {{ border: 0px solid black; width: 14px; height: 14px; }} QGroupBox::indicator:unchecked {{ image: url({0}/icons/checkbox-unchecked.png); }} QGroupBox::indicator:checked {{ image: url({0}/icons/checkbox-checked.png); }} QGroupBox::indicator:indeterminate {{ image: url({0}/icons/checkbox-indeterminate.png); }} QGroupBox::indicator:hover {{ background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.75, x3: 0, y3: 1, stop: 0 #4080c0, stop: 0.75 #b2ffff, stop: 1 #4080c0); }} QCheckBox {{ color: #8080ff; spacing: 8px; }} QCheckBox::indicator {{ border: 0px solid black; width: 16px; height: 16px; }} QCheckBox::indicator:unchecked {{ image: url({0}/icons/checkbox-unchecked.png); }} QCheckBox::indicator:checked {{ image: url({0}/icons/checkbox-checked.png); }} QCheckBox::indicator:indeterminate {{ image: url({0}/icons/checkbox-indeterminate.png); }} QCheckBox::indicator:hover {{ background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.75, x3: 0, y3: 1, stop: 0 #4080c0, stop: 0.75 #b2ffff, stop: 1 #4080c0); }} QCheckBox:hover {{ color: blue; background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.75, x3: 0, y3: 1, stop: 0 #4080c0, stop: 0.75 #00ffff, stop: 1 #4080c0); }} QCheckBox:pressed {{ color: #00ffff; background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.75, x3: 0, y3: 1, stop: 0 #4080c0, stop: 0.75 #005572, stop: 1 #4080c0); }} QMainWindow {{ background: #202030; }} QPushButton:disabled {{ border: 3px outset #73808d; border-radius: 4px; background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.75, x3: 0, y3: 1, stop: 0 #73808d, stop: 0.75 #5b7d89, stop: 1 #73808d); color: #4c4c73; }} QPushButton {{ border: 3px outset #4080c0; border-radius: 4px; background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.75, x3: 0, y3: 1, stop: 0 #4080c0, stop: 0.75 #00aae4, stop: 1 #4080c0); color: blue; }} QPushButton:hover {{ background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.75, x3: 0, y3: 1, stop: 0 #4080c0, stop: 0.75 #b2ffff, stop: 1 #4080c0); }} QPushButton:pressed {{ border: 3px inset #4080c0; background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 0.75, x3: 0, y3: 1, stop: 0 #4080c0, stop: 0.75 #005572, stop: 1 #4080c0); color: #00ffff; }} &quot;&quot;&quot;.format(DIRECTORY) class Font(QFont): def __init__(self, size): super().__init__() self.setFamily(&quot;Noto Serif&quot;) self.setStyleHint(QFont.StyleHint.Times) self.setStyleStrategy(QFont.StyleStrategy.PreferAntialias) self.setPointSize(size) self.setHintingPreference(QFont.HintingPreference.PreferFullHinting) class Button(QPushButton): def __init__(self, text): super().__init__() font = Font(8) self.setFont(font) self.setFixedSize(60, 20) self.setText(text) class Editor(QTextEdit): doubleClicked = pyqtSignal(QTextEdit) def __init__(self, text): super().__init__() self.setReadOnly(True) font = Font(9) self.setFont(font) self.setText(text) self.setFixedHeight(30) self.setFixedWidth(80) self.setLayoutDirection(Qt.LayoutDirection.LeftToRight) self.setLineWrapMode(QTextEdit.LineWrapMode.WidgetWidth) def mouseDoubleClickEvent(self, e: QMouseEvent) -&gt; None: self.doubleClicked.emit(self) return super().mouseDoubleClickEvent(e) class TextCell(QTextEdit): def __init__(self): super().__init__() self.setReadOnly(True) font = Font(9) self.setFont(font) self.setFixedHeight(30) self.setFixedWidth(200) self.setLayoutDirection(Qt.LayoutDirection.LeftToRight) self.setLineWrapMode(QTextEdit.LineWrapMode.WidgetWidth) class Table(QTableWidget): checkStates = [Qt.CheckState.Unchecked, Qt.CheckState.Checked] def __init__(self): super().__init__() self.setColumnCount(3) font = Font(9) self.setFont(font) self.verticalHeader().setFixedWidth(50) self.horizontalHeader().setFont(font) self.setHorizontalHeaderLabels(['Consonant', 'Frequency', 'Breaked']) self.setColumnWidth(0, 80) self.setColumnWidth(1, 80) self.horizontalHeader().setStretchLastSection(True) self.setAlternatingRowColors(True) self.lastChecked = None self.setSelectionMode(QAbstractItemView.SelectionMode.MultiSelection) for k, v in json.loads(Path('D:/consonant_chunks.json').read_text()).items(): self.addEntry(k, v) self.cellClicked.connect(self.onClick) self.cellChanged.connect(self.onCheck) def addEntry(self, key, val): row = self.rowCount() key = QTableWidgetItem(key) key.setFlags(FLAG.ItemIsEnabled | FLAG.ItemIsSelectable | FLAG.ItemIsUserCheckable) key.setCheckState(Qt.CheckState.Unchecked) self.insertRow(row) self.setItem(row, 0, key) val = QTableWidgetItem(str(val)) val.setFlags(FLAG.ItemIsEnabled | FLAG.ItemIsSelectable) self.setItem(row, 1, val) three = QTableWidgetItem('') three.setFlags(FLAG.ItemIsEnabled | FLAG.ItemIsSelectable) self.setItem(row, 2, three) def onClick(self, row, column): item = self.item(row, 0) state_index = item.checkState() == Qt.CheckState.Checked other = bool(1 - state_index) new_state = Table.checkStates[other] for i in range(3): self.item(row, i).setSelected(other) item.setCheckState(new_state) def onCheck(self, row, column): if column == 0: self.lastChecked = row item = self.item(row, 0) text = item.text() text_lines = textpane.toPlainText().splitlines() if item.checkState() == Qt.CheckState.Checked: text_lines.append(text) else: text_lines.remove(text) textpane.setText('\n'.join(text_lines)) def process(self): pattern = '(' + '|'.join(sorted(textpane.toPlainText().splitlines(), key=lambda x: -len(x))) + ')' for i in range(self.rowCount()): key = self.item(i, 0).text() text = ', '.join(i for i in re.split(pattern, key) if i) self.setItem(i, 2, QTableWidgetItem(text)) def removeSelected(self): row = self.lastChecked if row is not None: key = self.item(row, 0).text() text_lines = textpane.toPlainText().splitlines() if key in text_lines: text_lines.remove(key) textpane.setText('\n'.join(text_lines)) self.removeRow(row) self.lastChecked = None class TextPane(QTextEdit): def __init__(self): super().__init__() self.setReadOnly(True) font = Font(9) self.setFont(font) self.setLayoutDirection(Qt.LayoutDirection.LeftToRight) self.setLineWrapMode(QTextEdit.LineWrapMode.WidgetWidth) class ScrollArea(QScrollArea): def __init__(self, parent): super().__init__() self.setParent(parent) self.setWidgetResizable(True) self.Widget = QWidget() palette = QPalette() brush = QBrush(QColor(0, 32, 64, 255)) brush.setStyle(Qt.BrushStyle.SolidPattern) palette.setBrush(QPalette.ColorGroup.Active, QPalette.ColorRole.Window, brush) palette.setBrush(QPalette.ColorGroup.Inactive, QPalette.ColorRole.Window, brush) self.Widget.setPalette(palette) self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOn) self.Layout = QVBoxLayout(self.Widget) self.Layout.setAlignment(ALIGNMENT) self.Layout.setSizeConstraint(QLayout.SizeConstraint.SetMinimumSize) self.setWidget(self.Widget) self.setAlignment(ALIGNMENT) self.setFrameShape(QFrame.Shape.Box) self.setFrameShadow(QFrame.Shadow.Raised) class Window(QMainWindow): def __init__(self): super().__init__() rect = app.primaryScreen().availableGeometry() self.resize(int(0.9 * rect.width()), int(0.9 * rect.height())) self.setMinimumSize(int(0.67 * rect.width()), int(0.67 * rect.height())) frame = self.frameGeometry() center = self.screen().availableGeometry().center() frame.moveCenter(center) self.move(frame.topLeft()) font = Font(10) self.setFont(font) self.centralwidget = QWidget(self) self.vbox = QVBoxLayout(self.centralwidget) self.table = table self.bottom = QVBoxLayout() self.vbox.addWidget(self.table) self.vbox.addLayout(self.bottom) self.setCentralWidget(self.centralwidget) self.setStyleSheet(MAINSTYLE) if __name__ == '__main__': app = QApplication([]) app.setStyle(&quot;Fusion&quot;) textpane = TextPane() table = Table() window = Window() window.bottom.addWidget(textpane) buttonbar = QHBoxLayout() sort_button = Button('Sort') def sort_text(): textpane.setText('\n'.join(sorted(textpane.toPlainText().splitlines()))) sort_button.clicked.connect(sort_text) export_button = Button('Export') def export(): Path('D:/nonbreaking_consonants.txt').write_text(textpane.toPlainText()) export_button.clicked.connect(export) process_button = Button('Process') process_button.clicked.connect(table.process) delete_button = Button('Delete') delete_button.clicked.connect(table.removeSelected) buttonbar.addWidget(sort_button) buttonbar.addWidget(export_button) buttonbar.addWidget(process_button) buttonbar.addWidget(delete_button) window.bottom.addLayout(buttonbar) window.showMaximized() sys.exit(app.exec()) </code></pre> <p>Screenshot: <a href="https://i.stack.imgur.com/ljL8I.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ljL8I.jpg" alt="enter image description here" /></a></p> <p>Let me explain, the window is organized using a QVBoxLayout, in the upper half of the layout is a QScrollArea, the lower half are a QTextEdit and three buttons: Sort, Export and Process.</p> <p>All textboxs are read-only.</p> <p>The QScrollArea contains exactly 1615 QGroupBoxs, each QGroupBox corresponds to exactly one entry (key-value pair) in the dictionary.</p> <p>Each QGroupBox contains a QVBoxLayout, the QVBoxLayout has two QHBoxLayouts, the upper layout contains three QTextEdits, the first two are on the left and the last one is on the right. The lower layout contains a QPushButton named Delete on the right, initially hidden.</p> <p>The first corresponds to the key, the second corresponds to value, the third is initialy empty. Double clicking either of the first two textboxs reveals the delete button.</p> <p>The groupboxs are checkable, if you check the groupbox, it will highlight itself, and add the text in its first textbox to the big textbox in the lower half, uncheck it dehighlights itself and removes the text. Delete button deletes the groupbox and deletes its key from the big textbox.</p> <p>Sort button sorts the text in the big textbox, export button exports the text in the textbox to a file, and process button composes a regex using the text in the big textbox and processes the keys in each groupbox using inclusive re.split and writes the result to the third textbox in the respective groupbox.</p> <p>How can it be improved?</p> <p>Currently I can think of two improvements: the program is slow to start and uses considerable CPU time on starting, I think it is caused by creating all those QGroupBoxs and I think it will be better implemented as QTableView or QTableWidget but I don't know exactly how to do this, I am very inexperienced in GUI programming.</p> <p>And the groupboxes, currently I can only click precisely the checkbox to change the check status, and I want that to be changed, so that I can click anywhere inside the groupbox to change the checkstatus without having to click the checkbox exactly...</p> <p>Are there any other possible improvements?</p> <hr /> <h2>Update</h2> <p>Icons: checkbox-checked.png <a href="https://i.stack.imgur.com/Vo0Ws.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Vo0Ws.png" alt="enter image description here" /></a></p> <p>checkbox-disabled.png <a href="https://i.stack.imgur.com/2sQOh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2sQOh.png" alt="enter image description here" /></a></p> <p>checkbox-indeterminate.png <a href="https://i.stack.imgur.com/BoZjt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BoZjt.png" alt="enter image description here" /></a></p> <p>checkbox-unchecked.png <a href="https://i.stack.imgur.com/LaLt9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LaLt9.png" alt="enter image description here" /></a></p> <p>Put these icons in a folder named icons at the directory where you put the script (icons folder should be a subdirectory of the parent directory of the script path).</p> <hr /> <h2>Update</h2> <p><a href="https://i.stack.imgur.com/PSW28.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PSW28.jpg" alt="enter image description here" /></a></p> <p>Reimplemented my idea using QTableWidget, it was easier than I originally thought, now the program is much better, I am planning to add more columns and add tabs and add something to the right side, but for now I have done what I originally intended when I wrote the program.</p> <p>However there is still a minor problem that I am unable to solve, I want to highlight the entire rows where the checkbox is checked, not just the cell checked, and mouse hover also highlight entire rows, but dabbling with QStyleSheet only highlights the individual cells and not the rows...</p> <p>I of course have Googled it and simply put Google will never return what you want if you type a keyword that is a sentence, all methods I have found can only highlight the cell and not the row, which I have already used...</p> <p>I have tried to automatically select all cells in a row, that does highlight the entire row, but all rows previously checked are dehighlighted...</p> <p>How can I highlight entire rows?</p> <hr /> <h2>Update</h2> <p>I figured it out all by myself, and Google is of absolutely no use, it turns out I need to set multiselection mode... QTableWidget defaults to extended selection mode (or single selection mode I dunno, what's important is it isn't what I want)...</p> <p><a href="https://i.stack.imgur.com/yXxbb.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yXxbb.jpg" alt="enter image description here" /></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T13:09:17.750", "Id": "532884", "Score": "0", "body": "Side note, the third column's label is not a typo, yes it is nonstandard, but I deliberately chose it because the meaning I tried to express through the past participle isn't the usual meaning associated with broken. A string of letters cannot be broken, it cannot stop being functional or integral, but they can indeed be broken into smaller strings, however the meaning of this broken is different from what broken usually means when it is used alone, for the lack of a better word I chose that \"typo\", I am busy improving my code just so you know..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T19:03:48.253", "Id": "533077", "Score": "0", "body": "This project as a whole sounds complex and wonderful, congratulations. If you are looking into improving the UI or in particular its look and feel, please take look at qt-material. This module can convert the UI elements to resemble the material UI from Android. The XML based stylesheets are supported, making custom themes easy too. https://pypi.org/project/qt-material/" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T08:42:27.283", "Id": "269940", "Score": "2", "Tags": [ "python", "python-3.x", "gui", "pyqt" ], "Title": "Python 3 simple PyQt6 GUI program that helps text processing" }
269940
<p>I am trying to implement the <a href="https://esolangs.org/wiki/Dis" rel="nofollow noreferrer">Dis</a> language as a webpage in order to reproduce Dis programs for <a href="https://codegolf.stackexchange.com">code golfing</a> easily on browser.</p> <p>Since a famous online environment <a href="https://tio.run" rel="nofollow noreferrer">tio.run</a> is not accepting new languages, I decided to implement it by myself.</p> <p>I am <a href="https://github.com/GH-TpaeFawzen/dis.web/tree/2021.11.10.alpha" rel="nofollow noreferrer">publishing</a> just a JavaScript, but am not sure what the appropriate style of accepting inputs from browser (I am thinking a sequence of octets as a hexadecimal or UTF-8 or <code>xargs -n 1 printf</code>-strinf for I/O).</p> <p>Here's some of my <code>dis.js</code>:</p> <pre class="lang-javascript prettyprint-override"><code>class DisVm{ // ... /* * run(). For up to given steps. * Automatically halts when isHalt(). * @steps: integer. * Destructive! * Returns this. **/ run(steps=MAX_STEPS){ if(!Number.isInteger(steps)){ throw new TypeError( '@steps not an integer'); } if(steps&lt;MIN_STEPS||steps&gt;MAX_STEPS){ throw new RangeError( '@steps out of range: must be in '+ `[${MIN_STEPS}, ${MAX_STEPS}]`); } // Now I can run. const vm=this; let mem=vm.memory; let a=vm.registers.A; let c=vm.registers.C; let d=vm.registers.D; let input=( Array.isArray(vm.input)?vm.input:[]); let output=( Array.isArray(vm.output)?vm.output:[]); const getVm=()=&gt;{ this.memory=mem; this.register={A:a,C:c,D:d}; return this; } for(;steps&gt;0;steps-=1){ // TODO. randomized; necessary? if( Number.isInt(mem[c])&amp;&amp; 0&lt;=mem[c]&amp;&amp;mem[c]&lt;=this.maxValue ) ; else{ mem[c]=( Math.floor( Math.random()*this.mod)); } // end TODO. const cmd=mem[c]; if(cmd==33) return getVm(); if(cmd==42) d=mem[d]; if(cmd==62){ const v=mem[d]||0; a=mem[d]=( Math.floor(v/3)+ v%3*(this.mod/3)); } if(cmd==94) c=mem[d]; if(cmd==123) if(a==this.maxValue) return getVm(); else output.push(a); if(cmd==124){ let b=mem[d]||0; let r=0; for(let i=0;i&lt;this.trits;i++){ r=r*3+(a%3-b%3+3)%3 a=Math.floor(a/3); b=Math.floor(a/3); } a=mem[d]=r; } if(cmd==125){ if(!input.hasOwnProperty(0)) a=this.maxValue; else{ let v=input.shift(); if(!Number.isInteger(v)) v=0; a=( v&lt;0||v&gt;this.maxValue?0:v); } } c=(c+1)%this.mod; d=(d+1)%this.mod; } return getVm(); } } </code></pre> <h1>What I've just get it while making this post</h1> <ul> <li>I am missing to clarify some constants such as <code>MAX_STEPS</code> are defined within the class.</li> </ul> <h1>What to implement</h1> <ul> <li>Implement it securely. <ul> <li>This is why <code>run()</code> accepts <code>steps</code> to run.</li> </ul> </li> </ul> <h1>What I am not sure</h1> <ul> <li>I am not sure if it's appropriate if <code>run()</code> and some methods that I documented <code>destructive!</code> should return <code>this</code> or not, or the class should be immutable at all. I think immutable objects are slow.</li> <li>How strict should the code be for types of arguments?</li> <li>Also what I should ask here.</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T13:40:36.210", "Id": "532812", "Score": "0", "body": "Is the code working the way you expect it too?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T14:01:35.443", "Id": "532814", "Score": "0", "body": "This is probably not a good fit. Can you provide code (with a reduced `dis.js` if needed) that calls this VM and perhaps performs printing 'Hello World' or something? In this state, it is super hard to review and while interesting I would probably vote to close." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T11:45:29.233", "Id": "269945", "Score": "0", "Tags": [ "javascript", "object-oriented" ], "Title": "Implementing a programming language with objected-oriented programming in EcmaScript 6" }
269945
<p>So far I have made a class called Deck, to create and shuffle a deck of cards, and a class called Player, which I want to use to create the gambler and the dealer.</p> <p>My Player class inherits from the Deck class, so the players can access the created deck. My problem is that because I create 2 objects from Player class (gambler and dealer), this means 2 decks of cards are also created. Of course it should be that both players are using the same deck, how can I achieve this?</p> <pre><code>class Deck { public: int MinDeckSize = 10; std::vector&lt;int&gt; DeckOfCards; // Deck of cards values - with aces worth 11 void DeckInit() { // All the values in a deck of cards DeckOfCards = { 2,3,4,5,6,7,8,9,10,10,10,10,11, 2,3,4,5,6,7,8,9,10,10,10,10,11, 2,3,4,5,6,7,8,9,10,10,10,10,11, 2,3,4,5,6,7,8,9,10,10,10,10,11 }; // Fisher-Yates algorithm to shuffle the deck for (int i = 51; i &gt; 0; i--) { int r = rand()%(i + 1); std::swap(DeckOfCards[i], DeckOfCards[r]); } } // Pick a card from the deck, and remove the card from DeckOfCards int DrawCard() { int Card = DeckOfCards[0]; DeckOfCards.erase(DeckOfCards.begin()); return Card; } // Check the Deck has enough cards to play BlackJack bool IsDeckBigEnough() { return DeckOfCards.size() &gt;= MinDeckSize; } }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T12:28:12.293", "Id": "532803", "Score": "3", "body": "It's wrong to inherit Player from Deck. Inheritance means you can do with children everything you can do with a parent, e.g. if you can shuffle a Deck, then you also should be able to \"shuffle a player\". This, of course, is wrong. Probably you need a Game object with (at least) two players and a deck." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T12:29:45.223", "Id": "532804", "Score": "2", "body": "Rule of thumb: inheritance means \"is a\" relation. If you inherit Car class from Transport class, then a car is a transport." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T13:16:27.007", "Id": "532807", "Score": "1", "body": "Welcome to the Code Review Community. We only review code that is working as expected, there are other sites that will help you debug your code. Please read [Where can I get help?](https://meta.stackexchange.com/questions/129598/which-computer-science-programming-stack-exchange-sites-do-i-post-on) and [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T13:22:38.933", "Id": "532808", "Score": "0", "body": "The dealer is not actually a player, or at least not completely a player. An Ace can be either 1 or 11 and it depends on the cards in the hand, your implementation doesn't support this. While it doesn't really matter in Black Jack, the cards should have suits associated with them so start with 1 and number up to 52. A player can ask for a card or not ask for a card, the dealer is always the one to draw the card." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T13:23:31.383", "Id": "532809", "Score": "2", "body": "I can't actually write an answer because the question is off-topic." } ]
[ { "body": "<p>It's a nice Deck class that you've made, but allow me to suggest a few changes:</p>\n<ul>\n<li>Make <code>MinDeckSize</code> and <code>DeckOfCards</code> private, for encapsulation.</li>\n<li>Often the code style is such that types such as classes are in <code>PascalCase</code>, - and variables are either in <code>camelCase</code> or <code>snake_case</code>.</li>\n<li>Use a constructor to initialize the class, instead of the <code>DeckInit</code> function.</li>\n<li>Make a distinct function for shuffling, and make it use the vector size instead of a fixed size.</li>\n<li>Rename <code>IsDeckBigEnough</code> to <code>IsBigEnoughForBlackJack</code></li>\n</ul>\n<pre><code>class Deck {\n // Those are now privates\n int minDeckSize = 10;\n std::vector&lt;int&gt; deckOfCards;\n\npublic:\n // Constructor, avoid having to call an Init function\n // Deck of cards values - with aces worth 11\n Deck()\n {\n // All the values in a deck of cards\n deckOfCards = {\n 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11,\n 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11,\n 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11,\n 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11};\n\n FisherYatesShuffle();\n }\n\n void FisherYatesShuffle()\n {\n //Use the current vector size instead of the previously hardcoded 51\n //Prefer --i over i--\n for(int i = deckOfCards.size() - 1; i &gt; 0; --i) {\n int r = rand() % (i + 1);\n std::swap(deckOfCards[i], deckOfCards[r]);\n }\n }\n\n // Pick a card from the deck, and remove the card from DeckOfCards\n int DrawCard()\n {\n int Card = deckOfCards[0];\n deckOfCards.erase(deckOfCards.begin());\n return Card;\n }\n\n // Check the Deck has enough cards to play BlackJack\n bool IsDeckBigEnough()\n {\n return deckOfCards.size() &gt;= minDeckSize;\n }\n};\n</code></pre>\n<p>The Player class could have been included the question to make it easier to answer.</p>\n<p>Regardless, it seems that the needed relationship between Deck and Player is:<br />\nA Player <em>has a</em> Deck, and not<br />\nA Player <em>is a</em> Deck</p>\n<p>Since you would like both players to have a deck, let's use a common IDeck interface.</p>\n<p>The classes could then look like this:</p>\n<pre><code>\n//Interface class, with every functions pure virtual\nclass IDeck {\npublic:\n virtual void FisherYatesShuffle() = 0;\n virtual int DrawCard() = 0;\n virtual bool IsDeckBigEnough() = 0;\n};\n\nclass Deck : public IDeck {\n // Those are now privates\n int minDeckSize = 10;\n std::vector&lt;int&gt; deckOfCards;\n\npublic:\n // Constructor, avoid having to call an Init function\n // Deck of cards values - with aces worth 11\n Deck()\n {\n // All the values in a deck of cards\n deckOfCards = {\n 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11,\n 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11,\n 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11,\n 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11};\n\n FisherYatesShuffle();\n }\n\n virtual void FisherYatesShuffle() override\n {\n //Use the current vector size instead of the previously hardcoded 51\n //Prefer --i over i--\n for(auto i = deckOfCards.size() - 1; i &gt; 0; --i) {\n int r = rand() % (i + 1);\n std::swap(deckOfCards[i], deckOfCards[r]);\n }\n }\n\n // Pick a card from the deck, and remove the card from DeckOfCards\n virtual int DrawCard() override\n {\n int Card = deckOfCards[0];\n deckOfCards.erase(deckOfCards.begin());\n return Card;\n }\n\n // Check the Deck has enough cards to play BlackJack\n virtual bool IsDeckBigEnough() override\n {\n return deckOfCards.size() &gt;= minDeckSize;\n }\n};\n\nclass Player : public IDeck {\n std::shared_ptr&lt;Deck&gt; deck;\n\npublic:\n Player(std::shared_ptr&lt;Deck&gt; deck) :\n deck{deck}\n {\n }\n\n // Implement IDeck\n virtual void FisherYatesShuffle() override\n {\n deck-&gt;FisherYatesShuffle();\n }\n\n // Implement IDeck\n virtual int DrawCard() override\n {\n return deck-&gt;DrawCard();\n }\n\n // Implement IDeck\n virtual bool IsDeckBigEnough() override\n {\n return deck-&gt;IsDeckBigEnough();\n }\n\n //Other player functions\n};\n\nvoid Demo()\n{\n //Initialized and shuffled automatically from the Deck constructor\n auto oneDeck = std::make_shared&lt;Deck&gt;();\n\n //Two players share the same deck\n //Could be a vector&lt;Player&gt; instead\n Player firstPlayer(oneDeck);\n Player secondPlayer(oneDeck);\n\n //Example usage\n if(firstPlayer.IsDeckBigEnough())\n firstPlayer.DrawCard();\n}\n</code></pre>\n<p>All players will share the same deck.<br />\nAll player's Deck can be accessed using the IDeck interface.</p>\n<p>Hopefully this is helpful.<br />\nAlways keep learning :) !</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T20:10:03.593", "Id": "532840", "Score": "0", "body": "You are still deriving `Player` from `Deck` which is nonsensical: `class Player : public IDeck`. The idea of creating an interface is very C#-ish. A better solution would have been to make the necessary items `public` in `Deck` so that it is accessible to `Player`. You could also have used a reference to the deck instead of a shared pointer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T21:17:59.853", "Id": "532843", "Score": "0", "body": "#-ish indeed, but the necessary items are already public in Deck, and already accessible to Player. Did you mean something else? In this case the Deck is created in the same scope as the two players, so making it a reference would work in that scenario. But making a reference also assume that the Deck will not go out of scope and be destroyed before any players using it does. This is why it is a shared_ptr." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T21:22:01.877", "Id": "532844", "Score": "0", "body": "I would rather do something like this: [TIO](https://bit.ly/3bWEN5D)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T21:46:18.017", "Id": "532848", "Score": "0", "body": "You will have to do some really screwed up stuff to allow `Deck` to get out of scope before `Player` but I guess it's possible [TIO](https://tio.run/##hVBNTwMhEL3vr5j0UnDTtJp42V176sWb8WxiCLCWyEIDg6aa/e0rsI2isekc5vO9xwz8cFi9cD5Nb1YJ2MnBElp9VhBtvb43ChXT6kMKYEaA34e@16kIaAeGijOtj9A7OwDuZaTzV@DWeHSBo3VZxrtIJagGSTaUtrn3oNlRuivolfM4F78HXkYZUU7mnZLlV0R07Xer0IE7MPL9JEQSjP7gStmzwDH73jogHkXT@Hj/M4KKhE0bQwc3tzHWNf2zWEZzGxC6DhaPNsQvW6ScKKjhmqZ0@WSW7RlGcUUzE4vOapsiuShSnnhSKVv/y4zVOE1f), I get your point :-)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T18:54:56.627", "Id": "269956", "ParentId": "269946", "Score": "-1" } }, { "body": "<h1>Start variables and member functions with lower case</h1>\n<p>It's quite common in C++ to start type names with an upper case letter, and variable and function names with a lower case letter. This makes it easy to distinguish between the two.</p>\n<h1>Organizing your classes</h1>\n<blockquote>\n<p>My Player class inherits from the Deck class</p>\n</blockquote>\n<p>As mentioned by others in the comments, this is wrong. You should use inheritance primarily for &quot;is-a&quot; relationships. A player is not a deck, so it shouldn't inherit from a deck. A player can <em>have</em> a deck, in which case you would use composition instead of inheritance:</p>\n<pre><code>class Player {\n Deck hand;\n ...\n};\n</code></pre>\n<p>Note that you are already using composition for <code>Deck</code> itself: a <code>Deck</code> is not a card, so you wouldn't inherit from a card. Instead, you have correctly created a member variable that holds the cards in the decks.</p>\n<p>However, instead of using <code>std::vector&lt;int&gt;</code> for this, consider creating a <code>class Card</code> that represents a card, and then write:</p>\n<pre><code>std::vector&lt;Card&gt; cards;\n</code></pre>\n<p>Finally, in real life a deck of cards doesn't know anything about the game it is being used in. So having a member function that checks if the deck is big enough for Blackjack is wrong. Keep the contents of a <code>Deck</code> restricted to the cards it holds and any operations you can do on a deck, like shuffling cards, drawing cards and placing cards back on a deck.</p>\n<h1>Hands versus decks</h1>\n<p>When you say &quot;deck of cards&quot;, you typically think of a set of about 52 cards.\nWhen you play a game, players typically get a few cards of the deck, and that is called their &quot;hand&quot;, and then there typically are the drawing and discard piles. All those things are similar to a deck though, just that they can each have a variable amount of cards. You can use <code>class Deck</code> for all of those things.</p>\n<h1>Add functions to move cards between decks</h1>\n<p>It might be nice to have member functions that allows cards to be moved from one hand/deck/pile to another. Consider having:</p>\n<pre><code>class Deck {\n ...\n void draw_from(Deck &amp;other_deck) {\n Card card = other_deck.draw_card();\n add_card(card);\n }\n ...\n};\n\nclass Player {\n Deck hand;\n ...\n};\n\n...\n\nDeck draw_pile;\nDeck discard_pile;\nstd::vector&lt;Player&gt; players(2);\n\ndraw_pile.init();\n\n// Draw a card from the draw_pile into the first player's hand:\nplayers[0].hand.draw_from(draw_pile);\n</code></pre>\n<h1>Make better use of the standard library</h1>\n<p>The standard library comes with a lot of useful <a href=\"https://en.cppreference.com/w/cpp/header/algorithm\" rel=\"nofollow noreferrer\">algorithms</a>, including one that can shuffle the contents of a container for you: <a href=\"https://en.cppreference.com/w/cpp/algorithm/shuffle\" rel=\"nofollow noreferrer\"><code>std::shuffle()</code></a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T21:32:08.707", "Id": "269962", "ParentId": "269946", "Score": "2" } } ]
{ "AcceptedAnswerId": "269956", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T11:50:47.020", "Id": "269946", "Score": "1", "Tags": [ "c++", "object-oriented", "game", "playing-cards" ], "Title": "Card deck for Blackjack in an OOP style" }
269946
<p>I want to start omxplayer, check if there is the process is up, check if there is internet connection start with play a streaming, if there is not play a local loop, meanwhile try to check if the internet connection is up, if there is internet connection stop local file and play streaming video. I write this... any suggestion? Thanks</p> <pre class="lang-bsh prettyprint-override"><code>#!/bin/bash killall -9 omxplayer.bin SERVICE='omxplayer' while true; do if ps ax | grep -v grep | grep $SERVICE &gt; /dev/null then echo &quot;Running&quot; # sleep 5 else sleep 5 log=log_file_pette.txt # create log file or overrite if already present printf &quot;Log File Streaming- &quot; &gt;&gt; $log # append date to log file date &gt;&gt; $log # send email with date restart echo `date` | mailx -s &quot;Subject: Start streaming Ad&quot; miamail@mia.com # if there is no internet and no ping if ping -q -c 1 -W 1 google.com &gt;/dev/null then killall -9 omxplayer.bin $SERVICE -o alsa https://xxxxxxxxxxxx/playlist.m3u8 &amp; else # create log file or overrite if already present printf &quot;Log File Local- &quot; &gt;&gt; $log # append date to log file date &gt;&gt; $log killall -9 omxplayer.bin $SERVICE -o alsa looptv.mp4 sleep 5 fi fi done <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T21:43:23.670", "Id": "532845", "Score": "0", "body": "If `miamail@mia.com` is a real email address, then I suggest to redact it." } ]
[ { "body": "<h3>Use indentation to make the flow of logic easier to see</h3>\n<p>With indentation added to the original code,\nit's a lot easier to understand the branches of the logic:</p>\n<pre><code>killall -9 omxplayer.bin\nSERVICE='omxplayer'\nwhile true; do\n if ps ax | grep -v grep | grep $SERVICE &gt; /dev/null\n then\n echo &quot;Running&quot; # sleep 5\n else\n sleep 5\n log=log_file_pette.txt\n # create log file or overrite if already present\n printf &quot;Log File Streaming- &quot; &gt;&gt; $log\n\n # append date to log file\n date &gt;&gt; $log\n\n # send email with date restart\n echo `date` | mailx -s &quot;Subject: Start streaming Ad&quot; foo@example.com\n # if there is no internet and no ping\n if ping -q -c 1 -W 1 google.com &gt;/dev/null\n then\n killall -9 omxplayer.bin\n $SERVICE -o alsa https://xxxxxxxxxxxx/playlist.m3u8 &amp;\n else\n # create log file or overrite if already present\n printf &quot;Log File Local- &quot; &gt;&gt; $log\n\n # append date to log file\n date &gt;&gt; $log\n killall -9 omxplayer.bin\n $SERVICE -o alsa looptv.mp4 \n sleep 5\n fi\n fi\ndone\n</code></pre>\n<h3>Use functions to avoid duplicated logic</h3>\n<p>This snippet appears twice, with one word replaced:</p>\n<blockquote>\n<pre><code># create log file or overrite if already present\nprintf &quot;Log File Streaming- &quot; &gt;&gt; $log\n\n# append date to log file\ndate &gt;&gt; $log\n</code></pre>\n</blockquote>\n<p>It would be good to create a helper function for it, with the changing part a variable:</p>\n<pre><code>log_with_label() {\n local label=$1\n echo &quot;Log File $label- $(date)&quot; &gt;&gt; &quot;$log&quot;\n}\n</code></pre>\n<p>Then you can call this with <code>log_with_label &quot;Streaming&quot;</code> and <code>log_with_label &quot;Local&quot;</code>.</p>\n<p>Even the simple <code>killall -9 omxplayer.bin</code> would be good in a helper function:</p>\n<pre><code>kill_player() {\n killall -9 omxplayer.bin\n}\n</code></pre>\n<h3>The comments... are lying...</h3>\n<p>Some of the comments are confusing, because they don't tell the truth.</p>\n<p>No sleeping happens here:</p>\n<blockquote>\n<pre><code>echo &quot;Running&quot; # sleep 5\n</code></pre>\n</blockquote>\n<p>The file will not be overwritten here. This will append to the file if exists:</p>\n<blockquote>\n<pre><code># create log file or overrite if already present\nprintf &quot;Log File Streaming- &quot; &gt;&gt; $log\n</code></pre>\n</blockquote>\n<h3>Use double-quotes around variables in shell commands</h3>\n<p>Instead of these:</p>\n<blockquote>\n<pre><code>if ps ax | grep -v grep | grep $SERVICE &gt; /dev/null\nprintf &quot;Log File Streaming- &quot; &gt;&gt; $log\n$SERVICE -o alsa https://xxxxxxxxxxxx/playlist.m3u8 &amp;\n</code></pre>\n</blockquote>\n<p>write like this:</p>\n<pre><code>if ps ax | grep -v grep | grep &quot;$SERVICE&quot; &gt; /dev/null\nprintf &quot;Log File Streaming- &quot; &gt;&gt; &quot;$log&quot;\n&quot;$SERVICE&quot; -o alsa https://xxxxxxxxxxxx/playlist.m3u8 &amp;\n</code></pre>\n<h3>Avoid deeply nested code</h3>\n<p>Looking at this code:</p>\n<blockquote>\n<pre><code>while true; do\n if ps ax | grep -v grep | grep $SERVICE &gt; /dev/null\n then\n echo &quot;Running&quot; # sleep 5\n else\n\n # ... many, many lines here....\n\n fi\ndone\n</code></pre>\n</blockquote>\n<p>By the time the I reach the <code>fi</code>, I don't remember what the base condition was.\nIt would be good to reduce the nesting with a <code>continue</code> in the <code>if</code> branch.\n(I'm wondering if you wanted to put a <code>sleep 5</code> in there, in code, instead of a comment...)</p>\n<pre><code>while true; do\n if ps ax | grep -v grep | grep $SERVICE &gt; /dev/null\n then\n echo &quot;Running&quot; # sleep 5\n continue\n fi\n\n # ... many, many lines here....\n\ndone\n</code></pre>\n<h3>Use <a href=\"https://www.shellcheck.net/\" rel=\"nofollow noreferrer\">shellcheck.net</a></h3>\n<p>shellcheck.net is a that finds bugs in your shell scripts.\nIt's good to fix all the violations raised by it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T22:09:54.303", "Id": "269964", "ParentId": "269947", "Score": "2" } } ]
{ "AcceptedAnswerId": "269964", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T12:07:53.493", "Id": "269947", "Score": "0", "Tags": [ "bash", "raspberry-pi" ], "Title": "bash loop for checking service and network connection" }
269947
<p>I wrote a Lagrange polynomial interpolation class. It works fine. At the beginning some definitions: <span class="math-container">$$ \begin{align} &amp;nodes:\qquad x_0, \dots, x_n \\ &amp;values:\qquad f(x_0), \dots, f(x_n) \\ &amp;weights:\qquad w_0, \dots, w_n\qquad\text{where}~~~ w_j = \prod_{k=0, k \neq j}^{n}(x_j-x_k)^{-1} \\ &amp;coeff:\qquad f(x_0)w_0, \dots, f(x_n)w_n. \end{align} $$</span></p> <p>Let's denote <span class="math-container">$$c_i = f(x_i)w_i.$$</span> Value of approximation at some point is equal to <span class="math-container">$$ \begin{align} p(x) = l(x) \sum_{i=0}^{n} c_i(x-x_i)^{-1}, \qquad \text{where}~~l(x) = \prod_{i=0}^{n}(x-x_i). \end{align} $$</span></p> <p>Code (firstly <code>lagrange_interpolation.h</code>):</p> <pre><code>#include &lt;vector&gt; #include &lt;valarray&gt; #include &lt;algorithm&gt; #include &lt;iostream&gt; #include &lt;stdexcept&gt; #include &lt;numeric&gt; template&lt;typename T, typename V&gt; int binary_search_find_index(const std::vector&lt;T&gt; &amp;v, V data) { std::size_t index = 0; auto it = std::lower_bound(v.begin(), v.end(), data); if (it == v.end() || *it != data) { return -1; } else { index = std::distance(v.begin(), it); } return index; } class LInter { typedef std::vector&lt;double&gt; vector; public: LInter(vector nodes, vector values) { if (nodes.empty() || values.empty()) { throw std::invalid_argument(&quot;one of the vector is empty&quot;); } std::vector&lt;int&gt; indices(nodes.size()); std::iota(indices.begin(), indices.end(), 0); std::sort(indices.begin(), indices.end(),[&amp;](int a, int b) -&gt; bool { if (nodes[a] == nodes[b]) { throw std::invalid_argument(&quot;nodes are not unique&quot;); } return nodes[a] &lt; nodes[b]; } ); if (nodes.size() != values.size()) { throw std::invalid_argument(&quot;sizes of vectors differ&quot;); } for (int i = 0; i &lt; nodes.size(); i++) { std::swap(nodes[i], nodes[indices[i]]); std::swap(values[i], values[indices[i]]); } nodes_ = nodes; values_ = values; poly_deg_ = nodes_.size() - 1; GenerateWeights(); GenerateCoefficients(); } template&lt;typename T&gt; std::enable_if_t&lt;std::is_arithmetic_v&lt;T&gt;, double&gt; operator()(T); template&lt;typename T&gt; std::enable_if_t&lt;!std::is_arithmetic_v&lt;T&gt;, std::valarray&lt;double&gt;&gt; operator()(T const &amp;); private: vector nodes_; vector values_; vector weights_; vector coeff_; unsigned poly_deg_; void GenerateWeights(void); void GenerateCoefficients(void); }; </code></pre> <p>and <code>lagrange_interpolation.cc</code>:</p> <pre><code>#include &quot;lagrange_interpolation.h&quot; #include &lt;type_traits&gt; void LInter::GenerateWeights(void) { int size = poly_deg_ + 1; weights_.insert(weights_.begin(), size, 1); for (int i = 0; i &lt; size; i++){ for (int j = 0; j &lt; size; j++) { if (i != j) { weights_[i] *= (nodes_[i] - nodes_[j]); } } weights_[i] = 1/weights_[i]; } } void LInter::GenerateCoefficients(void) { int size = poly_deg_ + 1; coeff_.insert(coeff_.begin(), size, 1); std::transform(values_.begin(), values_.end(), weights_.begin(), coeff_.begin(), [](double v, double w) { return v*w;}); } template&lt;typename T&gt; std::enable_if_t&lt;std::is_arithmetic_v&lt;T&gt;, double&gt; LInter::operator()(T x) { auto index = binary_search_find_index(nodes_, x); if (index != -1) { return values_[index]; } double polynomial = 1; for (auto node : nodes_) { polynomial *= (x - node); } double result = std::inner_product(coeff_.begin(), coeff_.end(), nodes_.begin(), 0.0, std::plus&lt;&gt;(),[&amp;](double &amp;a, double &amp;b) { return a/(x - b); }); result *= polynomial; return result; } template&lt;typename T&gt; std::enable_if_t&lt;!std::is_arithmetic_v&lt;T&gt;, std::valarray&lt;double&gt;&gt; LInter::operator()(T const &amp;input) { std::valarray&lt;double&gt; result(input.size()); std::transform(std::begin(input), std::end(input), std::begin(result), [this](double x) { return operator()(x); } ); return result; } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T15:06:57.327", "Id": "532823", "Score": "0", "body": "Could someone edit my post and change coeff to \\text{coeff} (and other) in align enviroment? Unfortunately I can't do this...." } ]
[ { "body": "<h1>binary_search_find_index</h1>\n<p>I'm not sure why you are using different template types for the <code>vector</code> and <code>data</code>.</p>\n<p>It looks like you are trying to find the index of the <b>closest</b> element in the vector but then you discard it if it's not exactly equal to <code>data</code></p>\n<pre><code>if (it == v.end() || *it != data) {\n return -1;\n} else ...\n</code></pre>\n<p>Perhaps this is closer to what you initially intended to do:</p>\n<pre><code>if (it == v.end() || std::abs(*it - data) &gt; someVerySmallNumber {\n return -1;\n} else...\n</code></pre>\n<p>Since I cannot really guess what your intentions were, I will just assume that you are trying to get the index of an element in an array.</p>\n<p>First I would change the return type to <code>std::size_t</code> which is the correct type for array size and indexes. You can also use <code>std::optional&lt;std::size_t&gt;</code> and <code>std::find</code> like the following:</p>\n<pre><code>template&lt;typename T&gt;\nstd::optional&lt;std::size_t&gt; binary_search_find_index(const std::vector&lt;T&gt;&amp; v, T data) {\n auto index = std::find(v.begin(), v.end(), data);\n if (index == v.end())\n return std::nullopt;\n return index - v.begin();\n}\n</code></pre>\n<p>Then you can use <code>binary_search_find_index</code> like so:</p>\n<pre><code>void test() {\n std::vector&lt;int&gt; v = { 1, 2, 3, 4, 5 };\n auto index = binary_search_find_index(v, 3);\n if (index == std::nullopt)\n std::cout &lt;&lt; &quot;item is not in array.\\n&quot;;\n else\n std::cout &lt;&lt; &quot;index = &quot; &lt;&lt; *index &lt;&lt; '\\n';\n}\n</code></pre>\n<p>Since you are only using <code>binary_search_find_index</code> in one location, I think it might be better to actually remove it from the program and rather change <code>::operator()(T x)</code> to the following:</p>\n<pre><code>template&lt;class T&gt;\nstd::enable_if_t&lt;std::is_arithmetic_v&lt;T&gt;, double&gt; LInter&lt;T&gt;::operator()(T x) {\n auto node = std::find(nodes_.begin(), nodes_.end(), x);\n if (node != nodes_.end()) {\n return *node;\n }\n // ...\n return result;\n}\n</code></pre>\n<h1>LInter</h1>\n<p>I would have rather templated the class instead of using <code>typedef std::vector&lt;double&gt; vector;</code>.</p>\n<p>Consider changing to the following:</p>\n<pre><code>template&lt;class T&gt;\nclass LInter {\npublic:\n LInter(std::vector&lt;T&gt; nodes, std::vector&lt;T&gt; values) {\n if (nodes.empty() || values.empty()) {\n throw std::invalid_argument(&quot;one of the vector is empty&quot;);\n }\n }\n // ...\n}\n</code></pre>\n<p>Also note that <code>poly_deg_</code> should be <code>std::size_t poly_deg_</code> instead of simply <code>unsigned poly_deg_</code></p>\n<h1>Test cases</h1>\n<p>Reviewing the code would have been easier and more productive if you included some test cases.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T14:51:06.967", "Id": "269951", "ParentId": "269949", "Score": "3" } } ]
{ "AcceptedAnswerId": "269951", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T13:54:36.190", "Id": "269949", "Score": "2", "Tags": [ "c++", "object-oriented", "mathematics", "c++14" ], "Title": "Simple Lagrange interpolation" }
269949
<p>Rewrite of <a href="https://codereview.stackexchange.com/questions/269903/a-simple-counting-loop-class/269912#269912">A simple counting loop class</a> based on feedback:</p> <p>This version adds a step parameter and better iterator concept support. Counting is always done in a signed integral, and only integers and floats are supported.</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;cmath&gt; #include &lt;ranges&gt; #include &lt;bit&gt; #include &lt;algorithm&gt; #include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;concepts&gt; namespace util { // Getting the right diff_type template&lt;typename T&gt; struct helper; template&lt;std::integral T&gt; struct helper&lt;T&gt; { using diff_type=std::make_signed_t&lt;std::common_type_t&lt;int,T&gt;&gt;; }; template &lt;class T&gt; requires (std::is_same&lt;float, typename std::remove_cv&lt;T&gt;::type&gt;::value) struct helper&lt;T&gt; { using diff_type=int; }; template&lt;std::floating_point T&gt; requires (!std::is_same&lt;float, typename std::remove_cv&lt;T&gt;::type&gt;::value) struct helper&lt;T&gt; { using diff_type=long long; }; } template &lt;typename T&gt; // Only numerics really make sense requires std::is_arithmetic_v&lt;T&gt; class loop { public: using value_type=std::remove_const_t&lt;T&gt;; using difference_type=typename util::helper&lt;value_type&gt;::diff_type; class iterator; // forward refernce using sentinel = difference_type; class iterator { public: using pointer=T; using reference=T; using iterator_category=std::random_access_iterator_tag; using iterator_concept=std::random_access_iterator_tag; using self_type=iterator; // std::weakly_incrementable iterator()=default; iterator(const iterator&amp; it) = default; iterator&amp; operator=(const iterator&amp; it) = default; ~iterator()=default; iterator(value_type v, value_type s) : curr{0}, first_val{v}, step{s} {} // std::random_access_iterator constexpr value_type operator[](difference_type idx) const { return first_val+idx*step; } // std::input_or_output_iterator&lt;I&gt; constexpr value_type operator*() { return operator[](curr); } // std::indirectly_readable&lt;I&gt; friend value_type operator*(const iterator&amp; rhs) { return rhs.operator*(); } // std::weakly_incrementable&lt;I&gt; constexpr iterator&amp; operator++() { // pre // std::cout &lt;&lt; &quot;before: &quot; &lt;&lt; curr; curr++; // std::cout &lt;&lt; &quot; after: &quot; &lt;&lt; curr; // std::cout &lt;&lt; std::endl; return *this; } constexpr iterator operator++(int) { // post iterator tmp=*this; this-&gt;operator++(); return tmp; } // std::bidirectional_iterator&lt;I&gt; constexpr iterator&amp; operator--() { // pre curr--; return *this; } constexpr iterator operator--(int) { // post iterator tmp=*this; this-&gt;operator--(); return tmp; } // std::forward_iterator&lt;I&gt; // In C++20, 'operator==' implies 'operator!=' // This is the sentinel version: // sentinel_for&lt;T&gt; // Note this MUST be `const` constexpr bool operator==(const sentinel&amp; rhs) const { std::cout &lt;&lt; &quot; Comparing sentinel: &quot; &lt;&lt; curr &lt;&lt; &quot; vs &quot; &lt;&lt; rhs &lt;&lt; std::endl; return curr &gt;= rhs; } constexpr bool operator==(const iterator&amp; rhs) const { std::cout &lt;&lt; &quot; Comparing reg equal : &quot; &lt;&lt; curr &lt;&lt; &quot; vs &quot; &lt;&lt; rhs.curr &lt;&lt; std::endl; return curr == curr; } // std::random_access_iterator&lt;I&gt; // std::totally_ordered&lt;I&gt; std::weak_ordering operator&lt;=&gt;(const iterator&amp; rhs) const { return curr &lt;=&gt; rhs.curr; } constexpr difference_type operator-(const iterator&amp; rhs) const { return curr-rhs.curr; } // std::iter_difference&lt;I&gt; operators iterator&amp; operator+=(difference_type diff) { curr += diff; return *this; } iterator&amp; operator-=(difference_type diff) { curr -= diff; return *this; } iterator operator+(difference_type diff) const { iterator tmp=*this; return tmp+=diff; } iterator operator-(difference_type diff) const { iterator tmp=*this; return tmp-=diff; } friend iterator operator+(difference_type diff, const iterator&amp; rhs) { return rhs + diff; } friend iterator operator-(difference_type diff, const iterator&amp; rhs) { return rhs - diff; } // std::contiguous_iterator&lt;I&gt; pointer operator-&gt;() const { return curr; } using element_type = T; // required for std::input_iterator private: difference_type curr; value_type first_val; value_type step; }; using const_iterator=iterator; // back_val is the main concept here // all counting, despite type or step values, is just from 0 to N // iterator::operator* does the mapping from this count to the value static inline difference_type constexpr back_val(T x, T y, T z) { auto dist=y-x; //auto rounding=z/T{2}; auto rounding=z/(y+x); // calculate an epsilon auto slices=(dist+rounding)/z; return static_cast &lt;difference_type&gt; (1+std::floor(slices)); } loop(T x, T y, T z=1) : it{x,z} ,last_val{back_val(x,y,z)} { } constexpr inline iterator begin() const { return it; } constexpr inline sentinel end() const { return last_val; } constexpr inline const_iterator cbegin() const { return begin(); } constexpr inline const sentinel cend() const { return end(); } constexpr inline T front() const{ return *begin(); } constexpr inline T back() const { return *(begin()+(last_val-1)); } private: const iterator it; const sentinel last_val; static_assert(std::weakly_incrementable&lt;iterator&gt;); static_assert(std::input_or_output_iterator&lt;iterator&gt;); static_assert(std::indirectly_readable&lt;iterator&gt;); static_assert(std::input_iterator&lt;iterator&gt;); static_assert(std::incrementable&lt;iterator&gt;); static_assert(std::forward_iterator&lt;iterator&gt;); static_assert(std::bidirectional_iterator&lt;iterator&gt;); static_assert(std::totally_ordered&lt;iterator&gt;); static_assert(std::sized_sentinel_for&lt;iterator, iterator&gt;); static_assert(std::same_as&lt;std::iter_value_t&lt;iterator&gt;, std::remove_cvref_t&lt;std::iter_reference_t&lt;iterator&gt;&gt;&gt;); static_assert(std::random_access_iterator&lt;iterator&gt;); // static_assert(std::is_lvalue_reference_v&lt;std::iter_reference_t&lt;iterator&gt;&gt;); // static_assert(std::contiguous_iterator&lt;iterator&gt;); }; </code></pre> <p>Some example usage:</p> <pre class="lang-cpp prettyprint-override"><code>template&lt;typename T&gt; int tst(T x, T y, T z) { T t=1; std::cout &lt;&lt; &quot;LOOP BEGIN: &quot; &lt;&lt; x &lt;&lt; &quot;, &quot; &lt;&lt; y &lt;&lt; &quot;, &quot; &lt;&lt; z &lt;&lt; std::endl; for (auto i : loop(x,y,z)) { std::cout &lt;&lt; &quot;LOOP: &quot; &lt;&lt; i &lt;&lt; std::endl; t*=i; } std::cout &lt;&lt; std::endl &lt;&lt; &quot;LOOP DONE&quot; &lt;&lt; std::endl &lt;&lt; std::endl &lt;&lt; std::endl; return t; } int tst1(int x, int y, int z) { return tst(x,y,z); } int tst1a(int x, int y) { return tst1(x,y,2); } int tst1a(long double x, long double y) { return tst(x,y,2.0L); } // this can be compiletime resolved to: 636231680 int tst1b() { return tst1(10,100,7); } int main() { tst(1,10,1); tst(91,100, 3); tst(92,100, 3); tst(93,100, 3); tst(1.8, 3.8, .1); tst(1,1,2); tst(2,1,1); tst(-10,-20,-1); } </code></pre> <p>Comparisons to ranges and C style</p> <pre><code>// Simple inclusinve loop [from, to] // Clang is still having issues here: auto inline loop2(std::size_t from, std::size_t to) { //return std::views::iota(from) | std::views::take(to); return std::views::iota(from,to); }// Simple inclusinve loop [from, to] int tst2(int x, int y) { int t=1; for (int i : loop2(x,y)) { t*=i; } return t; } int tst3(int x, int y) { int t=1; for (int i=x; i &lt;=y ; ++i) { t*=i; } return t; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T14:28:39.557", "Id": "532816", "Score": "0", "body": "Available here: https://godbolt.org/z/Px3nfYqPx" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T15:01:38.953", "Id": "532822", "Score": "1", "body": "Mine (with writeup): https://www.codeproject.com/Articles/1245139/DIY-range is a count only (no built-in end) and https://www.codeproject.com/Articles/1245954/DIY-range-the-very-versitile-range-view-iterator-p (simple iterator pair is _not_ limited to counting iterators). You're mixing the two ideas and unnecessarily limiting your class to arithmetic types." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T16:29:38.183", "Id": "532826", "Score": "0", "body": "Very nice write-up, but I'm not sure how that would handle something like `loop(1.8, 3.8, .1)` . The reason this is more complicated than my first version is to support `step` and floating types. I do like the idea of empty(), bool() and !(), so thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T19:04:31.250", "Id": "532834", "Score": "0", "body": "@Glenn_Teitelbaum Yes, that code is as simple as possible to work, and the second version shows what's needed to give metadata to std algorithms. It would be easy to add a step value to the pure counter. The thing is that `end` iterators in STL test for equality and for reliability this should check for exceeding the limit. But if it's typed as a `sentinel` instead, then the `!=` operation could actually mean \"no longer in the bounds to cover\" and comparing two iterators would still mean the actual comparison you stated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T19:05:59.637", "Id": "532836", "Score": "0", "body": "(I'm still thinking of keeping a _pure_ counting iterator (with step), and a general purpose range based on a current/end pair that can be used with anything." } ]
[ { "body": "<h1>Incorrect pointer types</h1>\n<p>When the value type of a range is <code>T</code>, then the following member types look wrong:</p>\n<pre><code>using pointer=T;\nusing reference=T;\n</code></pre>\n<p>A range like this doesn't point to actual objects, so pointers don't make sense. Remove them, and also remove the <code>operator-&gt;()</code> function.</p>\n<h1>Problems in <code>back_val()</code></h1>\n<p>Suppose I use the following:</p>\n<pre><code>loop(-10, 10, 1);\n</code></pre>\n<p>Then in <code>back_val()</code> there will be a division by zero. For integer types, you should not need to calculate an epsilon value. For floating point types, you are almost guaranteed to do it wrong.</p>\n<p>If you want to do rounding, I suggest you just do the naive division:</p>\n<pre><code>difference_type slices = (y - x) / z + 1;\n</code></pre>\n<p>And then look at how close this gets you to the desired end value:</p>\n<pre><code>auto diff = (x + z * slices) - y;\n</code></pre>\n<p>You can normalize the difference by dividing it by <code>z</code>. Note how we now only divide by <code>z</code>, which should always be non-zero anyway for the counting loop to make sense.</p>\n<h1><code>difference_type</code> is not large enough</h1>\n<p>Consider this:</p>\n<pre><code>#include &lt;climits&gt;\n\n// Loop over all the integers\nfor (auto i: loop(INT_MIN, INT_MAX)) {\n std::cout &lt;&lt; i &lt;&lt; &quot;\\n&quot;;\n}\n</code></pre>\n<p><code>T</code> is <code>int</code>, and <code>difference_type</code> is also deduced to be <code>int</code>. However, <code>INT_MAX - INT_MIN</code> is larger than can be stored in an <code>int</code>. You could make it <code>unsigned</code>, but since your counter includes the end value, <code>INT_MAX - INT_MIN + 1</code> is just one too many for an <code>unsigned int</code>. You could try to promote it to the next larger integer type, but of course you will reach a limit at some point.</p>\n<h1>Naming things</h1>\n<p>Almost all variables have good names, except the arguments of the constructor. <code>x</code>, <code>y</code> and <code>z</code>? Is it first, last, step or first, step, last? Make sure the names of the public function arguments are clear and descriptive.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T22:48:57.850", "Id": "269966", "ParentId": "269950", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T14:25:36.523", "Id": "269950", "Score": "3", "Tags": [ "c++", "iterator", "c++20" ], "Title": "A counting loop class v2" }
269950
<p>In my python-based project I have the following problem: I have a list with many entries, with each entry being an object of the same class. This is demonstrated in the code below:</p> <pre><code>#!/usr/bin/env python3 class demo_class: &quot;&quot;&quot;Example class for demonstration&quot;&quot;&quot; def __init__(self, val_a, val_b, val_c): self.val_a = val_a self.val_b = val_b self.val_c = val_c def print_something(self): &quot;&quot;&quot;Foo-function, executed for demonstration&quot;&quot;&quot; print(str(self.val_a) + &quot;, &quot; + str(self.val_b) + &quot;, &quot; + str(self.val_c)) #Data generation list_of_demo_classes = [] for i in range(0, 2): for j in range(0, 2): for k in range(0, 2): local_demo_class = demo_class(val_a = i, val_b = j, val_c = k) list_of_demo_classes.append(local_demo_class) </code></pre> <p>Now I would first select all elements where <code>val_a = 0</code> and <code>val_b = 0</code>, afterwards all elements where <code>val_a = 0</code> and <code>val_b = 1</code>, and so on, until I have called all entries in the list. The current approach is</p> <pre><code>#How can I optimize this? for i in range(0, 2): for j in range(0, 2): for k in range(0, 2): for elem in list_of_demo_classes: if elem.val_a != i: continue if elem.val_b != j: continue if elem.val_c != k: continue elem.print_something() </code></pre> <p>but this approach does look rather brute-force for me. Are there better solutions?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T16:06:59.423", "Id": "532825", "Score": "3", "body": "Hey I'm afraid this is too hypothetical to be reviewed? You might need list comprehensions, maybe? Can't say without the complete code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T17:39:19.817", "Id": "532831", "Score": "0", "body": "@kubatucka: This is my full code broken down to an MWE. What I basically want is: \"Get all elements from list `list_of_demo_classes` for which `val_a == i` and `val_b == j`, and then iterate over all possible entries for `val_a` and `val_b`\". My current approach is shown above, but it looks inefficient to me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T19:20:22.247", "Id": "532837", "Score": "3", "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._\" Minimal Working Examples are for **Stack Overflow**. At **Code Review**, we want actual code, so we can provide a real review. For instance `demo_class` is a horrible class name for several reasons, but creating a review for that is meaningless since it isn't a real class name." } ]
[ { "body": "<p>As best I can tell — based more on your code's behavior than your description of it — you have some objects and you want to print them all in an\norder based on their attribute values. If so, a <a href=\"https://docs.python.org/3/library/dataclasses.html\" rel=\"nofollow noreferrer\">dataclass</a> could help by\neliminating most of the boilerplate code and by supporting attribute-based\nsorting directly (via <code>order = True</code>). Here's a brief demonstration:</p>\n<pre><code>from dataclasses import dataclass\nfrom random import randint\n\n@dataclass(order = True)\nclass Element:\n a: int\n b: int\n c: int\n\nelements = [\n Element(randint(1, 3), randint(0, 2), randint(0, 2))\n for _ in range(10)\n]\n\nfor e in sorted(elements):\n print(e)\n</code></pre>\n<p>Output from one run:</p>\n<pre><code>Element(a=1, b=0, c=1)\nElement(a=1, b=2, c=2)\nElement(a=2, b=2, c=1)\nElement(a=2, b=2, c=1)\nElement(a=2, b=2, c=2)\nElement(a=3, b=0, c=0)\nElement(a=3, b=1, c=1)\nElement(a=3, b=1, c=2)\nElement(a=3, b=2, c=1)\nElement(a=3, b=2, c=1)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T18:38:18.880", "Id": "269955", "ParentId": "269953", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T15:36:26.133", "Id": "269953", "Score": "-1", "Tags": [ "python" ], "Title": "Getting all elements in list with certain attribute value in python - Improved solution compared to loop" }
269953
<p>I coded a little loop that reduces a dataset by computing the mean of X rows every X rows. <br>I'm working with a dataset of a certain size (8 Millions rows for 10 columns) and my code takes too long to compute the whole dataset.<br> I am using Pandas.<br> Is there a way to improve my loop to make it more efficient and faster ?</p> <pre class="lang-py prettyprint-override"><code> # data is the dataset, pd.DataFrame() # # nb_row is the number of rows to collapse # for example : nb_row = 12 would reduce the dataset by x12 # by computing the mean of 12 rows every 12 rows nb_row = 12 raw_columns = [&quot;f1&quot;, &quot;f2&quot;, &quot;f3&quot;, &quot;f4&quot;] # column names for i in range(0, len(data), nb_row): new_df = new_df.append( pd.DataFrame( [[data[elem].iloc[i : i + nb_row].mean() for elem in raw_columns]], columns=raw_columns, ) ) </code></pre> <p>Thanks</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T03:11:13.710", "Id": "532941", "Score": "0", "body": "Is one of those \"x rows\" in the top row supposed to be something else? Otherwise, I think youve pretty much got it covered... : ) 3 out of 3 ain't bad; it's perfect! ...sry, I would've edited, but it's slightly over my head. Didn't want to mess it up." } ]
[ { "body": "<p>Your current code breaks two major pandas antipatterns, explained in depth by <a href=\"https://stackoverflow.com/users/4909087/cs95\">@cs95</a>:</p>\n<ul>\n<li><a href=\"https://stackoverflow.com/a/55557758/13138364\">Avoid iterating a DataFrame</a></li>\n<li><a href=\"https://stackoverflow.com/a/56746204/13138364\">Avoid growing a DataFrame</a></li>\n</ul>\n<p>The more idiomatic approaches are <a href=\"https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.GroupBy.mean.html\" rel=\"nofollow noreferrer\"><code>groupby.mean</code></a> (fastest) and <a href=\"https://pandas.pydata.org/docs/reference/api/pandas.core.window.rolling.Rolling.mean.html\" rel=\"nofollow noreferrer\"><code>rolling.mean</code></a>:</p>\n<p><a href=\"https://i.stack.imgur.com/GZAE1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/GZAE1.png\" width=\"320\"></a></p>\n<hr />\n<h3>1. <a href=\"https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.GroupBy.mean.html\" rel=\"nofollow noreferrer\"><code>groupby.mean</code></a> (fastest)</h3>\n<p>(This is ~5.5x faster than <a href=\"https://pandas.pydata.org/docs/reference/api/pandas.core.window.rolling.Rolling.mean.html\" rel=\"nofollow noreferrer\"><code>rolling.mean</code></a> at 8M rows.)</p>\n<p>Generate pseudo-groups with <code>data.index // nb_row</code> and take the <a href=\"https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.GroupBy.mean.html\" rel=\"nofollow noreferrer\"><code>groupby.mean</code></a>:</p>\n<pre><code>nb_row = 12\nnew_df = data.groupby(data.index // nb_row).mean()\n\n# f1 f2 f3 f4\n# 0 -0.171037 -0.288915 0.026885 -0.083732\n# 1 -0.018497 0.329961 0.107714 -0.430527\n# ... ... ... ... ...\n# 666665 -0.648026 0.232827 0.290072 0.535636\n# 666666 -0.373699 -0.260689 0.122012 -0.217035\n# \n# [666667 rows x 4 columns]\n</code></pre>\n<p>Note that if the real <code>data</code> has a custom index (instead of a default <code>RangeIndex</code>), then use <code>groupby(np.arange(len(df)) // nb_row)</code> instead.</p>\n<hr />\n<h3>2. <a href=\"https://pandas.pydata.org/docs/reference/api/pandas.core.window.rolling.Rolling.mean.html\" rel=\"nofollow noreferrer\"><code>rolling.mean</code></a></h3>\n<p><a href=\"https://codereview.stackexchange.com/a/269965/238890\">rak1507's answer</a> covers <a href=\"https://pandas.pydata.org/docs/reference/api/pandas.core.window.rolling.Rolling.mean.html\" rel=\"nofollow noreferrer\"><code>rolling.mean</code></a> but is missing a key detail.</p>\n<p><code>rolling(nb_row)</code> uses a window size of <code>nb_row</code> <strong>but slides 1 row at a time, not every <code>nb_row</code> rows.</strong></p>\n<ul>\n<li><p>That means slicing with <code>[nb_row-1:]</code> results in the wrong output shape (it's not reduced by a factor of <code>nb_row</code> as described in the OP):</p>\n<pre><code>new_df = data.rolling(nb_row).mean()[nb_row-1:]\nnew_df.shape\n\n# (7999989, 4)\n</code></pre>\n</li>\n<li><p>Instead we should slice with <code>[nb_row::nb_row]</code> to get every <code>nb_row</code><sup>th</sup> row:</p>\n<pre><code>new_df = data.rolling(nb_row).mean()[nb_row::nb_row]\nnew_df.shape\n\n# (666666, 4)\n</code></pre>\n</li>\n</ul>\n<hr />\n<h3>Timings (8M rows*)</h3>\n<pre><code>%timeit data.groupby(data.index // nb_row).mean()\n631 ms ± 56.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n</code></pre>\n<pre><code>%timeit data.rolling(nb_row).mean()[nb_row::nb_row]\n3.47 s ± 274 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n</code></pre>\n<p><sup><em>* <code>data = pd.DataFrame(np.random.random((8_000_000, 4)), columns=['f1', 'f2', 'f3', 'f4'])</code></em></sup></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T09:04:26.347", "Id": "532959", "Score": "1", "body": "Oops yeah you're right I forgot to slice every nth element too. Nice answer - til about groupby" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T00:43:23.983", "Id": "270003", "ParentId": "269957", "Score": "3" } } ]
{ "AcceptedAnswerId": "270003", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T19:05:06.057", "Id": "269957", "Score": "2", "Tags": [ "python", "pandas" ], "Title": "Compute the mean of every X rows of a pandas DataFrame" }
269957
<p>I use asyncio to speed up web scraping. I collect only title, author, tags, datetime, total comments from list view from specific <a href="https://unboxholics.com/news" rel="nofollow noreferrer">website</a>. Also, i collect these from all pages. I would like to improve my code, so any idea i would appreciate it.</p> <p>My code:</p> <pre class="lang-py prettyprint-override"><code>from bs4 import BeautifulSoup, Tag from dataclasses import dataclass from typing import List import aiohttp import asyncio from functools import reduce from operator import iconcat @dataclass class Article: title: str author: str tags: str upload_on: str comments: int link: str @classmethod def from_page_items(cls, item: Tag) -&gt; 'Article': spans = item.find('div', {'class': 'entry__header'}).find_all('span') entry_title = item.find('h2', {'class': 'entry__title'}) anchor = item.find('div', {'class': 'entry__header'}).find_all('a') return cls( title=entry_title.text.strip(), author=anchor[1].text, tags=anchor[2].text, upload_on=spans[0].text, comments=int(spans[1].text) if len(spans) &gt; 1 else 0, link=entry_title.find('a').get('href') ) class Scrape: def __init__(self, url) -&gt; None: self.session = None self.url = url async def __aenter__(self): self.session = aiohttp.ClientSession() return self async def __aexit__(self, *args): await self.session.close() async def fetch_url(self, params: dict = {}) -&gt; BeautifulSoup: &quot;&quot;&quot;Fetch a url and return HTML document Args: params (dict, optional): [description]. Defaults to {}. Returns: BeautifulSoup: HTML document &quot;&quot;&quot; async with self.session.get(self.url, params=params) as response: response.raise_for_status() resp_text = await response.text() soup = BeautifulSoup(resp_text, 'html.parser') return soup async def get_page_articles(self, page: int) -&gt; List[Article]: &quot;&quot;&quot;For each page return all the articles in a list contain details with Article Class Args: page (int): the number of page Returns: List[Article]: List of Article &quot;&quot;&quot; doc = await self.fetch_url(params={'p': page}) articles = [Article.from_page_items(article) for article in doc.findAll( 'article', {'class': 'entry card post-list'})] await asyncio.sleep(1) return articles async def gather_articles(self) -&gt; List[List[Article]]: &quot;&quot;&quot;Gather all pages until the end of pagination `end_page` Returns: List[List[Article]] &quot;&quot;&quot; doc = await self.fetch_url(self.url) end_page_number = doc.select_one( 'ul.pagination li:last-child').find('a')['href'].split('=')[-1] coros = [self.get_page_articles(page) for page in range(1, end_page_number + 1)] return await asyncio.gather(*coros) async def get_all_articles(self) -&gt; List[Article]: &quot;&quot;&quot;Gather all articles and transform to List[Article] Returns: List[Article] &quot;&quot;&quot; result = await self.gather_articles() return reduce(iconcat, result, []) async def main(): async with Scrape(BASE_URL) as scrape: result = await scrape.get_all_articles() print(result) asyncio.run(main()) </code></pre> <p>After that, using this code, i will store all the info into a database and play with pandas library.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T21:31:35.673", "Id": "269961", "Score": "2", "Tags": [ "python", "python-3.x", "web-scraping", "beautifulsoup", "asyncio" ], "Title": "Web scraping articles using asyncio" }
269961
<p>I'm a computer science student, and in 2 of my courses this semester we are writing short C programs to demonstrate the things we are learning about. All of these programs require command-line flags &amp; arguments, so I decided to write a short single-header library for myself to be able to add simple flags, integer, and string arguments without having to write the same <code>getopt</code> patterns over and over again. It's mostly a toy thing but I'm using it as a learning experience :).</p> <hr /> <h2>Header Component</h2> <p>Included in all files that include <code>&quot;opt.h&quot;</code>.</p> <pre class="lang-c prettyprint-override"><code>/* * Jake Grossman &lt;jake.r.grossman@gmail.com&gt; * This is free software released in the public domain. * See LICENSE.txt for more information. */ #ifndef opt_h #define opt_h #include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; #include &lt;getopt.h&gt; </code></pre> <p>These are the definitions for the library:</p> <pre class="lang-c prettyprint-override"><code>// typedefs to help emulate template-like behavior in ADD_OPTION typedef int OPT_INT; typedef int OPT_FLAG; typedef char* OPT_STR; // start an options block with a given argc and argv #define START_OPTIONS(argc, argv) OPT_start_options(argc, argv); // add an option // type is one of FLAG, INT, or STR #define ADD_OPTION(type, flag, varname) \ OPT_##type varname = 0; \ int OPT_has_##varname = 0; \ OPT_add_option(OPT_H_##type, flag, &amp;OPT_has_##varname, &amp;varname); // end the option block #define END_OPTIONS() OPT_process_options(); #define OPT_H_NONE 0 // flag is not defined #define OPT_H_FLAG 1 // flag has no argument #define OPT_H_INT 2 // flag has an integer argument #define OPT_H_STR 3 // flag has a string argument void OPT_start_options(int argc, char** argv); void OPT_add_option(int type, char flag, int* has_data_flag, void* data); void OPT_process_options(); #endif // end header file </code></pre> <p>These are the public facing components of the API. The <code>START_OPTIONS()</code> macro is used to setup the variables used with <code>getopt</code>. <code>ADD_OPTION()</code> registers a single character option (e.g., <code>-v</code>) and creates associated variables. <code>END_OPTIONS()</code> uses <code>getopt</code> and the options registered with <code>ADD_OPTION()</code> to populate the create variables. Each is explained in more detail with it's implementation.</p> <hr /> <h2>Implementation</h2> <p>Included in a <strong>single file</strong> where <code>OPT_H_IMPLEMENTATION</code> is defined.</p> <p>This is exactly like the <a href="https://github.com/nothings/stb" rel="nofollow noreferrer">stb public domain/MIT single-file libraries</a>.</p> <pre class="lang-c prettyprint-override"><code>#ifdef OPT_H_IMPLEMENTATION char OPT_flags[26] = { OPT_H_NONE }; // list of declared flags (a-z only) int OPT_num_flags = 0; // number of flags currently added in option block void* OPT_flag_values[26] = { NULL }; // pointers to flag value variables int* OPT_found_flags[26] = { NULL }; // pointers to `OPT_has_varname` flags // which argc/argv to use for getopt // NOTE: this has all the side // effects for argv that getopt // normally does int OPT_argc; char** OPT_argv; // flag indicating whether we are in an options block int OPT_in_progress = 0; </code></pre> <p>When an option is declared with <code>ADD_OPTION()</code>, it registers:</p> <ul> <li><p>the type of option into <code>OPT_flags</code> (one of <code>OPT_H_FLAG</code>, <code>OPT_H_INT</code>, or <code>OPT_H_STR</code>)</p> </li> <li><p>a pointer to the variable created to store the value of the option in <code>OPT_flag_values</code></p> </li> <li><p>a pointer to the <code>OPT_has_##varname</code> variable used to detect whether options were found in <code>OPT_found_flags</code></p> </li> </ul> <p>as well as incrementing <code>OPT_num_flags</code>.</p> <p><code>OPT_argc</code> and <code>OPT_argv</code> are set by <code>START_OPTIONS()</code> to allow the usage of an arbitrary <code>argc</code> and <code>argv</code>.</p> <pre class="lang-c prettyprint-override"><code> // cleanup any leftover data and prepare to start reading options void OPT_start_options(int argc, char** argv) { // clear all existing data for (int i = 0; i &lt; 26; i++) { OPT_flags[i] = OPT_H_NONE; OPT_flag_values[i] = NULL; OPT_in_progress = 0; } // save argument count and string array pointer OPT_argc = argc; OPT_argv = argv; OPT_in_progress = 1; } </code></pre> <p>This resets all the of stored flag data, but does not make any attempt to clean up allocated memory, since it may be possible that the user wants to keep using a variable after starting a new options block. So, the user is responsible for their own strings.</p> <pre class="lang-c prettyprint-override"><code>void OPT_add_option(int type, char flag, int* has_data_flag, void* data) { if (!OPT_in_progress) { fprintf(stderr, &quot;OPT_add_option(): called outside of an options block\n&quot;); exit(EXIT_FAILURE); } // convert opt character to alphabet index int index = (int)flag % 32; // check that this flag has not been seen before if (OPT_flags[index] != OPT_H_NONE) { fprintf(stderr, &quot;OPT_add_option(): Duplicate declaration -- '%c'\n&quot;, flag); exit(EXIT_FAILURE); } // save pointer to data variable if (data) { if (!type == OPT_H_INT &amp;&amp; !type == OPT_H_STR &amp;&amp; !type == OPT_H_FLAG) { fprintf(stderr, &quot;OPT_add_option(): Unexpected type value: %d\n&quot;, type); exit(EXIT_FAILURE); } // save pointer to data variable OPT_flag_values[index] = data; } // store pointer to indicator flag variable OPT_found_flags[index] = has_data_flag; OPT_num_flags++; // assign appropriate value to flags field OPT_flags[index] = type; } </code></pre> <ul> <li><p><code>int type</code> is created by expanding one of <code>FLAG</code>, <code>INT</code>, or <code>STR</code> to <code>OPT_H_FLAG</code>, <code>OPT_H_INT</code>, or <code>OPT_H_STR</code>. This value is how the data type of the registered option is known.</p> </li> <li><p><code>char flag</code> is the literal character passed to <code>ADD_OPTION()</code>.</p> </li> <li><p><code>int* has_data_flag</code> is a pointer to the <code>OPT_has_##varname</code> variable that indicates the presence of a flag on the command line input.</p> </li> <li><p><code>void* data</code> is a pointer to the created variable that is saved in <code>OPT_flag_values</code> so that <code>END_OPTIONS()</code> knows where to store the data</p> </li> </ul> <p>After checking that <code>OPT_in_progress</code> is set and that this flag has not been declared before, the information about the command is registered in the appropriate table.</p> <pre class="lang-c prettyprint-override"><code>// read and process arguments that the user has specified void OPT_process_options() { int opt; char* arg_string; // eagerly allocate the maximum size // (2 characters for each flag, 'a:') arg_string = malloc(OPT_num_flags * 2 + 1); if (!arg_string) { perror(&quot;OPT_process_options&quot;); exit(EXIT_FAILURE); } memset(arg_string, 0, OPT_num_flags*2+1); char* ptr = arg_string; for (size_t i = 0; i &lt; sizeof(OPT_flags); i++) { int type = OPT_flags[i]; if (type == OPT_H_NONE) // flag not defined continue; *(ptr++) = i + 'a' - 1; // translate alphabet index to lowercase letter if (type == OPT_H_INT || type == OPT_H_STR) *(ptr++) = ':'; // indicate required value } // process argument string while ((opt = getopt(OPT_argc, OPT_argv, arg_string)) != -1) { int index = (int)opt % 32; // convert opt character to alphabet index int type = OPT_flags[index]; switch (type) { case OPT_H_INT: { // integer flag int* ptr = (int*)OPT_flag_values[index]; *ptr = atoi(optarg); break; } case OPT_H_STR: { // string flag char** ptr = (char**)OPT_flag_values[index]; *ptr = malloc(strlen(optarg)+1); if (!(*ptr)) { perror(&quot;OPT_process_options&quot;); exit(EXIT_FAILURE); } strcpy(*ptr, optarg); break; } case OPT_H_FLAG: { // regular flag (no data) int* ptr = (int*)OPT_flag_values[index]; *ptr = 1; break; } default: { // getopt will have already printed an error on stderr exit(EXIT_FAILURE); } } // successfully processed flag if (OPT_found_flags[index]) *(OPT_found_flags[index]) = 1; } free(arg_string); OPT_in_progress = 0; } #endif </code></pre> <p>This first uses the registered information from <code>OPT_flags</code> to create an option string for <code>getopt</code>. It uses <code>OPT_num_flags</code> to eagerly allocate enough memory in the string for every option to have a required argument. So, if <code>a</code>, <code>i</code>, <code>c</code>, and <code>v</code> are registered options, it will allocate enough space for the longest possible optstring <code>&quot;a:i:c:v:&quot;</code>. Then, it constructs the string by assuming flag variables have no arguments, while integers and strings do (<code>&quot;a&quot;</code> v.s. <code>&quot;a:&quot;</code>). Then, it will repeatedly call <code>getopt</code>, using the character value returned as an index to the flag data by converting it to it's alphabetical index (<code>a -&gt; 0</code>, <code>b-&gt;1</code>, ..., <code>z-&gt;25</code>).</p> <p>This way, it is able to <code>switch</code> over the value stored in <code>OPT_flags</code> to appropriately cast the void pointer to the correct type to store in the created variable.</p> <hr /> <p>I'm not too convinced that there isn't a better way to achieve the generic-ish effect from <code>ADD_OPTION</code>. previous, similar implementation used three separate macros to achieve the same goal without typedef.</p> <pre class="lang-c prettyprint-override"><code>// add a flag option #define ADD_FLAG_OPT(flag, varname) \ int varname = 0; \ int OPT_has_##varname = 0; \ OPT_add_option(OPT_H_FLAG, flag, no_argument, &amp;varname, NULL); // add an integer option #define ADD_INT_OPT(flag, varname) \ int varname = 0; \ int OPT_has_##varname = 0; \ OPT_add_option(OPT_H_INT, flag, required_argument, &amp;OPT_has_##varname, &amp;varname); // add a string option #define ADD_STR_OPT(flag, varname) \ char* varname = NULL; \ int OPT_has_##varname = 0; \ OPT_add_option(OPT_H_STR, flag, required_argument, &amp;OPT_has_##varname, &amp;varname); </code></pre> <p>I didn't like how each variant was nearly identical, which is why I changed the interface, but something about the wierd <code>typedef</code>'ing makes me thing I'm using an ineffective solution for this.</p> <hr /> <h2>Usage</h2> <p>This minimal example shows the complete usage:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; #define OPT_H_IMPLEMENTATION #include &quot;opt.h&quot; int main(int argc, char** argv) { START_OPTIONS(argc, argv); ADD_OPTION(FLAG, 'v', is_verbose); ADD_OPTION(INT, 't', time_to_live); ADD_OPTION(STR, 'i', input_filename); END_OPTIONS(); printf(&quot;Verbose: %d\n&quot;, is_verbose); if (OPT_has_time_to_live) { printf(&quot;Time To Live: %d\n&quot;, time_to_live); } if (OPT_has_input_filename) { printf(&quot;Input Filename: %s\n&quot;, input_filename); free(input_filename); // free memory malloced by opt.h } return 0; } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T22:02:37.980", "Id": "269963", "Score": "2", "Tags": [ "c", "console", "macros", "c-preprocessor" ], "Title": "Implement easy CLI options in C using a single-file header" }
269963
<p>I've just started learning rust and have written a basic sudoku solver, however it seems to run much slower than I expected. So I'm looking for any possible performance improvements as well as any other general feedback.</p> <pre class="lang-rust prettyprint-override"><code>fn main() { let initial_grid: [[i8; 9]; 9] = [ [0, 4, 3, 0, 0, 0, 0, 0, 9], [0, 0, 0, 6, 0, 0, 0, 0, 5], [0, 0, 0, 0, 0, 4, 1, 0, 0], [9, 0, 1, 0, 5, 0, 0, 0, 0], [0, 0, 0, 7, 2, 6, 0, 0, 0], [0, 0, 8, 0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 7, 2, 0], [7, 0, 0, 0, 0, 0, 0, 0, 0], [2, 0, 0, 0, 0, 5, 0, 6, 0], ]; solve_sudoku(initial_grid); } fn find_empty(grid: [[i8; 9]; 9]) -&gt; (usize, usize){ for row in 0..9{ for col in 0..9 { if grid[row][col] == 0 { return (row, col) } } } print!(&quot;Done&quot;); return (9,9) } fn solve_sudoku(mut grid: [[i8; 9]; 9]) -&gt; bool{ let l: (usize, usize) = find_empty(grid); if l == (9, 9) { print_grid(grid); return true } for i in 1..10 { if is_location_safe(grid, l.0, l.1, i) { grid[l.0][l.1] = i; if solve_sudoku(grid) { return true; } grid[l.0][l.1] = 0; } } return false } fn is_location_safe(grid: [[i8; 9]; 9], row: usize, col: usize, num: i8) -&gt; bool { return !used_in_col(grid, col, num) &amp; !used_in_row(grid, row, num) &amp; !used_in_box(grid, row, col, num) } fn used_in_box(grid: [[i8; 9]; 9], row: usize, col: usize, num: i8) -&gt; bool { let first_cell_row = row - (row%3); let first_cell_column = col - (col%3); for i in 0..3 { for j in 0..3{ if grid[i+first_cell_row][j+first_cell_column] == num { return true } } } return false } fn used_in_col(grid: [[i8; 9]; 9], col: usize, num: i8) -&gt; bool { for i in 0..8 { if grid[i][col] == num { return true; } } return false; } fn used_in_row(grid: [[i8; 9]; 9], row: usize, num: i8) -&gt; bool{ for i in grid[row] { if i == num { return true; } } return false } fn print_grid(grid: [[i8; 9]; 9]) { println!(); for row in grid { for item in row{ print!(&quot;{:?} &quot;, item); } println!(); } } </code></pre>
[]
[ { "body": "<h2>Goal</h2>\n<p>The goal is to optimize the program. I won't change the backtracking algorithm.</p>\n<h2>General feedback</h2>\n<p>Your code is good, but you should use structs and impls in this program, instead of passing <code>grid: [[i8; 9]; 9]</code> around. I show this in code below.</p>\n<h2>Idea</h2>\n<p>You check cell vacancy with many loops that check multiple cells. How about we kill many birds with one stone? That is, we can use small bitsets and bit operations to do work of a loop in one go.</p>\n<h2>Result</h2>\n<p>The gain is speed improvement by a <strong>factor of 150x</strong>.</p>\n<pre><code>test bench ... bench: 125,889,703 ns/iter (+/- 12,948,648)\ntest bench ... bench: 857,542 ns/iter (+/- 84,678)\n</code></pre>\n<h2>Code</h2>\n<pre class=\"lang-rust prettyprint-override\"><code>#![feature(test)]\nextern crate test;\n\nuse test::Bencher;\n\nfn sudoku() {\n let initial_grid: Grid = Grid::new([\n [0, 4, 3, 0, 0, 0, 0, 0, 9], \n [0, 0, 0, 6, 0, 0, 0, 0, 5], \n [0, 0, 0, 0, 0, 4, 1, 0, 0], \n [9, 0, 1, 0, 5, 0, 0, 0, 0], \n [0, 0, 0, 7, 2, 6, 0, 0, 0], \n [0, 0, 8, 0, 1, 0, 0, 0, 0], \n [0, 1, 0, 0, 0, 0, 7, 2, 0], \n [7, 0, 0, 0, 0, 0, 0, 0, 0], \n [2, 0, 0, 0, 0, 5, 0, 6, 0], \n ]);\n let initial_grid = ::test::black_box(initial_grid);\n let result = initial_grid.solve_sudoku();\n ::test::black_box(result);\n}\n\nconst ALL_EMPTY: u16 = 0b111_111_111_0;\n\n#[derive(Copy, Clone)]\nstruct Grid {\n grid: [[i8; 9]; 9],\n rows: [u16; 9],\n cols: [u16; 9],\n boxes: [[u16; 3]; 3],\n}\n\nimpl Grid {\n fn new(grid: [[i8; 9]; 9]) -&gt; Self {\n let mut result = Grid {\n grid,\n rows: [ALL_EMPTY; 9],\n cols: [ALL_EMPTY; 9],\n boxes: [[ALL_EMPTY; 3]; 3],\n };\n for row in 0..9 {\n for col in 0..9 {\n if result.grid[row][col] != 0 {\n result.set_occupied(row, col, result.grid[row][col]);\n }\n }\n }\n result\n }\n\n fn set_occupied(&amp;mut self, row: usize, col: usize, val: i8) {\n self.grid[row][col] = val;\n self.rows[row] &amp;= !(1 &lt;&lt; val as u8);\n self.cols[col] &amp;= !(1 &lt;&lt; val as u8);\n self.boxes[row / 3][col / 3] &amp;= !(1 &lt;&lt; val as u8);\n }\n\n fn set_vacant(&amp;mut self, row: usize, col: usize) {\n let val = self.grid[row][col];\n self.rows[row] |= 1 &lt;&lt; val as u8;\n self.cols[col] |= 1 &lt;&lt; val as u8;\n self.boxes[row / 3][col / 3] |= 1 &lt;&lt; val as u8;\n self.grid[row][col] = 0;\n }\n\n fn find_empty(&amp;self) -&gt; (usize, usize) {\n for row in 0..9 {\n for col in 0..9 {\n if self.grid[row][col] == 0 {\n return (row, col)\n }\n }\n }\n print!(&quot;Done&quot;);\n return (9,9)\n }\n\n fn solve_sudoku(mut self) -&gt; bool {\n let l: (usize, usize) = self.find_empty();\n if l == (9, 9) {\n self.print();\n return true\n }\n for i in 1..10 {\n if self.is_location_safe(l.0, l.1, i) {\n self.set_occupied(l.0, l.1, i);\n if self.solve_sudoku() {\n return true;\n }\n self.set_vacant(l.0, l.1);\n }\n }\n return false\n }\n\n fn is_location_safe(&amp;self, row: usize, col: usize, num: i8) -&gt; bool {\n let box_vacancy = self.boxes[row / 3][col / 3];\n let row_vacancy = self.rows[row];\n let col_vacancy = self.cols[col];\n box_vacancy &amp; row_vacancy &amp; col_vacancy &amp; (1 &lt;&lt; num as u8) != 0\n }\n\n fn print(&amp;self) {\n println!();\n for row in self.grid {\n for item in row {\n print!(&quot;{:?} &quot;, item);\n }\n println!();\n }\n }\n}\n\n\n#[bench]\nfn bench(b: &amp;mut Bencher) {\n b.iter(|| {\n sudoku();\n });\n}\n\n#[test]\nfn test_sudoku() {\n sudoku();\n}\n</code></pre>\n<h2>Previous code (benched)</h2>\n<pre class=\"lang-rust prettyprint-override\"><code>#![feature(test)]\nextern crate test;\n\nuse test::Bencher;\n\nfn sudoku() {\n let initial_grid: [[i8; 9]; 9] = [\n [0, 4, 3, 0, 0, 0, 0, 0, 9], \n [0, 0, 0, 6, 0, 0, 0, 0, 5], \n [0, 0, 0, 0, 0, 4, 1, 0, 0], \n [9, 0, 1, 0, 5, 0, 0, 0, 0], \n [0, 0, 0, 7, 2, 6, 0, 0, 0], \n [0, 0, 8, 0, 1, 0, 0, 0, 0], \n [0, 1, 0, 0, 0, 0, 7, 2, 0], \n [7, 0, 0, 0, 0, 0, 0, 0, 0], \n [2, 0, 0, 0, 0, 5, 0, 6, 0], \n ];\n let result = solve_sudoku(::test::black_box(initial_grid));\n ::test::black_box(result);\n}\n\nfn find_empty(grid: [[i8; 9]; 9]) -&gt; (usize, usize){\n for row in 0..9{\n for col in 0..9 {\n if grid[row][col] == 0 {\n return (row, col)\n }\n }\n }\n print!(&quot;Done&quot;);\n return (9,9)\n}\n\nfn solve_sudoku(mut grid: [[i8; 9]; 9]) -&gt; bool{\n let l: (usize, usize) = find_empty(grid);\n if l == (9, 9) {\n print_grid(grid);\n return true\n }\n for i in 1..10 {\n if is_location_safe(grid, l.0, l.1, i) {\n grid[l.0][l.1] = i;\n if solve_sudoku(grid) {\n return true;\n }\n grid[l.0][l.1] = 0;\n }\n }\n return false\n}\n\nfn is_location_safe(grid: [[i8; 9]; 9], row: usize, col: usize, num: i8) -&gt; bool {\n return !used_in_col(grid, col, num) &amp; !used_in_row(grid, row, num) &amp; !used_in_box(grid, row, col, num)\n}\n\nfn used_in_box(grid: [[i8; 9]; 9], row: usize, col: usize, num: i8) -&gt; bool {\n let first_cell_row = row - (row%3);\n let first_cell_column = col - (col%3);\n for i in 0..3 {\n for j in 0..3{\n if grid[i+first_cell_row][j+first_cell_column] == num {\n return true\n }\n }\n }\n return false\n}\n\nfn used_in_col(grid: [[i8; 9]; 9], col: usize, num: i8) -&gt; bool {\n for i in 0..8 {\n if grid[i][col] == num {\n return true;\n }\n }\n return false;\n}\n\nfn used_in_row(grid: [[i8; 9]; 9], row: usize, num: i8) -&gt; bool{\n for i in grid[row] {\n if i == num {\n return true;\n }\n }\n return false\n}\n\nfn print_grid(grid: [[i8; 9]; 9]) {\n println!();\n for row in grid {\n for item in row{\n print!(&quot;{:?} &quot;, item);\n }\n println!();\n }\n}\n\n\n#[bench]\nfn bench(b: &amp;mut Bencher) {\n b.iter(|| {\n sudoku();\n });\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-04T06:33:27.727", "Id": "270658", "ParentId": "269967", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T23:44:47.737", "Id": "269967", "Score": "4", "Tags": [ "performance", "beginner", "rust", "sudoku", "backtracking" ], "Title": "Rust based Sudoku solver using backtracking" }
269967
<p>I did research because I want to learn Kruskal's and Prim's MSTs. I did research and after a solid understanding, I went to my textbook and got their libraries:</p> <ul> <li><p><a href="https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/Edge.java.html" rel="nofollow noreferrer">https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/Edge.java.html</a></p> </li> <li><p><a href="https://algs4.cs.princeton.edu/43mst/EdgeWeightedGraph.java.html" rel="nofollow noreferrer">https://algs4.cs.princeton.edu/43mst/EdgeWeightedGraph.java.html</a></p> </li> </ul> <p>Here is my code, I've done some tests and it checks out on my end. I struggled a lot with finding an end point when inputted a start point, since when there is a dead end you kind of back track in the priority queue to the next best option.</p> <pre><code>import edu.princeton.cs.algs4.EdgeWeightedGraph; import edu.princeton.cs.algs4.Edge; import java.util.PriorityQueue; import java.util.Queue; public class MinimumSpanningForest { public static EdgeWeightedGraph g; public static boolean[] visited; public static Queue&lt;Edge&gt; pq = new PriorityQueue&lt;Edge&gt;(); public static void edgeCompareTest() { Edge one = new Edge(1,2,2.0); Edge anotherOne = new Edge(1,3,4.0); Edge seven = new Edge(7,1,2.0); Edge anotherSeven = new Edge(7,4,1.0); System.out.println(&quot;one compared to one: &quot; + one.compareTo(one)); System.out.println(&quot;one compared to another one: &quot; + one.compareTo(anotherOne)); System.out.println(&quot;one compared to seven: &quot; + one.compareTo(seven)); System.out.println(&quot;seven compared to one: &quot; + seven.compareTo(one)); System.out.println(&quot;one compared to null: &quot; + one.compareTo(null)); } public static void main(String[] args) { g = new EdgeWeightedGraph(5,5); // g.addEdge(new Edge(0,1,0.3)); // g.addEdge(new Edge(0,2,0.5)); // g.addEdge(new Edge(2,3,1.2)); // g.addEdge(new Edge(1,4,0.8)); System.out.println(g); prim(g); //Queue&lt;Edge&gt; queue = new PriorityQueue&lt;&gt;((e1 , e2) -&gt; e1.weight().compareTo(e2.weight())); for (int i = 0; i &lt; g.E(); i++) { for(Edge e : g.adj(i)) { pq.add(e); } } } private static void qEdges(int vertex) { visited[vertex] = true; for (Edge edge : g.adj(vertex)) { if(!visited[edge.other(vertex)]) { pq.add(edge); } } } public static void prim(EdgeWeightedGraph g) { visited = new boolean[g.V()]; int e = g.V() - 1; int edgeCount; double mstCost; int otherPt = 0; edgeCount = 0; mstCost = 0; Edge[] mstEdges = new Edge[e]; qEdges(otherPt); while(!pq.isEmpty() &amp;&amp; edgeCount != e) { Edge edge = pq.remove(); otherPt = (!visited[edge.either()]) ? edge.either() : edge.other(edge.either()); if(visited[otherPt]) { continue; } mstEdges[edgeCount++] = edge; mstCost += edge.weight(); qEdges(otherPt); } if (edgeCount != mstEdges.length) { System.out.println(&quot;No MST exists!&quot;); } else { System.out.println(&quot;There is a MST in the following order of edges: &quot;); for(Edge edge : mstEdges) { System.out.println(edge); } System.out.println(&quot;With a cost of &quot; + mstCost); } } public static void kruskal(EdgeWeightedGraph g) { } } </code></pre> <p>I did not do Kruskal's yet, but I figured that it would be best to make sure Prim's doesn't have any glaring fixes y'all would advise before I go ahead to Kruskals. Thanks.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T05:23:18.377", "Id": "532865", "Score": "0", "body": "\"No MST exists!\" - is it possible?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T19:29:35.847", "Id": "532914", "Score": "0", "body": "@vnp yes it is if the graph doesn't use all nodes/vertices. It cannot be disconnected." } ]
[ { "body": "<p>Seeing you hyperlinked Princeton <em>Algorithms, 4th Ed.</em> resources, I assume you know how to view their take of Prim's.<br />\nI do not understand your concern about <em>terse</em>ness.</p>\n<p>There is one striking difference between the code you present for review and that of <code>edu.princeton.cs.algs4.Edge</code> and <code>EdgeWeightedGraph</code> it uses:<br />\nTheirs is documented using the standard mechanism -<br />\n<em>Everything</em> public carries a doc comment. Even accessors.<br />\n→ Follow, or use something better.</p>\n<p>For a class <code>MinimumSpanningForest</code>, a <em>static</em> member graph looks odd.<br />\nAll three static member declarations in combination look state of a single <em>invocation</em>. Seeing <code>kruskal()</code> in addition to <code>prim()</code>, an invocation of some <em>graph algorithm</em> or <em>forest</em>~?<br />\n→ There should probably be an interface both Prim&amp;Kruskal implement, each with its own <em>per instance</em> state.<br />\nA common base class could highlight commonalities.</p>\n<p>(Finding Jarník/Prim/Dijkstra's algorithm the only one spelled out in a class <code>MinimumSpanningForest</code> is odd as it originally constructs a single spanning tree (containing the CC of the the initial node chosen) while <a href=\"https://en.m.wikipedia.org/wiki/Kruskal%27s_algorithm#Algorithm\" rel=\"nofollow noreferrer\">Kruskal's</a> &quot;naturally&quot; arrives at the forest.)</p>\n<p>I find the high-level description of Prim's easier to recognise in your take, while Princeton's may store less elements in the PQ.</p>\n<p>I like names chosen for the purpose of what they name:<br />\n<code>shortestEdges</code> instead of <code>pq</code>,<br />\n<code>vertex</code> or <code>toAdd</code> instead of <code>otherPt</code> (while I can sort of see how it got &quot;other&quot; (would have preferred &quot;unvisited&quot;), what is &quot;Pt&quot; for?)<br />\n<code>qEdges</code> is overdoing <em>terseness</em> - <code>enqueueEdges</code> would do nicely.<br />\n(With a development tool supporting renaming, you don't need to <em>type</em> it that way.)<br />\n(I don't think I'd qualify <em>any</em> name local to <code>prim()</code> with mst.)<br />\nI'd comment <em>why</em> both vertices connected by an edge from the queue may be marked <em>visited</em> when only edges with one unvisited vertex are enqueued.</p>\n<p>I like concerns separated:<br />\nI'd rather have an MST/MSF implementation return sets of edges, and specify&amp;implement printing elsewhere.<br />\nTo this end, and seeing the number of edges might not reach #vertices-1 when <span class=\"math-container\">\\$g\\$</span> is not connected, I'd collect edges in a <code>List</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T20:02:15.147", "Id": "270427", "ParentId": "269968", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T02:36:05.870", "Id": "269968", "Score": "-1", "Tags": [ "java", "algorithm", "tree", "graph" ], "Title": "is my Prim's MST implementation terse enough?" }
269968
<p>I import a list of objects from an JSON file and want to display it in a WPF TreeView Control. The Data looks like this:</p> <pre><code> [ { &quot;Name&quot;: &quot;Name1&quot;, &quot;Ip&quot;: &quot;192.168.1.1&quot;, &quot;Location&quot;: &quot;LocA&quot;, &quot;Group&quot;: &quot;GrpB&quot;, &quot;SubGroup&quot;: &quot;SubGrp1&quot;, &quot;Pin&quot;: false }, { &quot;Name&quot;: &quot;Name2&quot;, &quot;Ip&quot;: &quot;192.168.1.2&quot;, &quot;Location&quot;: &quot;LocA&quot;, &quot;Group&quot;: &quot;GrpA&quot;, &quot;SubGroup&quot;: &quot;SubGrp1&quot;, &quot;Pin&quot;: false }, { &quot;Name&quot;: &quot;Name3&quot;, &quot;Ip&quot;: &quot;192.168.1.3&quot;, &quot;Location&quot;: &quot;LocB&quot;, &quot;Group&quot;: &quot;GrpA&quot;, &quot;SubGroup&quot;: &quot;SubGrp1&quot;, &quot;Pin&quot;: false }, { &quot;Name&quot;: &quot;Name4&quot;, &quot;Ip&quot;: &quot;192.168.1.4&quot;, &quot;Location&quot;: &quot;LocB&quot;, &quot;Group&quot;: &quot;GrpB&quot;, &quot;SubGroup&quot;: &quot;SubGrp1&quot;, &quot;Pin&quot;: false } ] </code></pre> <p>The JSON is deserialized in a list of this Objects:</p> <pre><code>public class Server { public string Name { get; set; } public string Ip { get; set; } public string Location { get; set; } public string Group { get; set; } public string SubGroup { get; set; } public bool Pin { get; set; } } </code></pre> <p>I want to display the data in a Treeview like this: <a href="https://i.stack.imgur.com/jt1Mm.png" rel="nofollow noreferrer">Treeview</a> So I use this Group Class:</p> <pre><code>public class Group { public string Name { get; set; } public List&lt;Group&gt; Groups { get; set; } = new List&lt;Group&gt;(); public List&lt;Server&gt; Servers { get; set; } = new List&lt;Server&gt;(); public IList Children { get { return new CompositeCollection() { new CollectionContainer() { Collection = Servers }, new CollectionContainer() { Collection = Groups } }; } } } </code></pre> <p>And this ugly function is convert the List in a structure with the groups and sub groups which is bound to the Treeview ItemSource:</p> <pre><code> ServerList = new ObservableCollection&lt;Model.Group&gt;(); foreach (Model.Server server in ServerRepo.Servers) { if (! ServerList.Any(w =&gt; w.Name == server.Location)) { ServerList.Add(new Model.Group { Name = server.Location }); } Model.Group Loc = ServerList.Where(w =&gt; w.Name == server.Location).First(); if (! Loc.Groups.Any(x =&gt; x.Name == server.Group)) { Loc.Groups.Add(new Model.Group { Name = server.Group }); } Model.Group Grp = Loc.Groups.Where(w =&gt; w.Name == server.Group).First(); if (! Grp.Groups.Any(x =&gt; x.Name == server.SubGroup)) { Grp.Groups.Add(new Model.Group { Name = server.SubGroup }); } Model.Group SubGrp = Grp.Groups.Where(w =&gt; w.Name == server.SubGroup).First(); SubGrp.Servers.Add(server); } </code></pre> <p>XAML:</p> <pre><code>&lt;TreeView HorizontalAlignment=&quot;Stretch&quot; Margin=&quot;10&quot; VerticalAlignment=&quot;Stretch&quot; ItemsSource=&quot;{Binding ServerList}&quot; Grid.Column=&quot;1&quot;&gt; &lt;TreeView.Resources&gt; &lt;HierarchicalDataTemplate DataType=&quot;{x:Type model:Group}&quot; ItemsSource=&quot;{Binding Children}&quot;&gt; &lt;TextBlock Text=&quot;{Binding Name}&quot; /&gt; &lt;/HierarchicalDataTemplate&gt; &lt;HierarchicalDataTemplate DataType=&quot;{x:Type model:Server}&quot;&gt; &lt;TextBlock&gt; &lt;Run Text=&quot;{Binding Name}&quot;&gt;&lt;/Run&gt; &lt;Run Text=&quot;(&quot;&gt;&lt;/Run&gt; &lt;Run Text=&quot;{Binding Ip}&quot;&gt;&lt;/Run&gt; &lt;Run Text=&quot;)&quot;&gt;&lt;/Run&gt; &lt;/TextBlock&gt; &lt;/HierarchicalDataTemplate&gt; &lt;/TreeView.Resources&gt; &lt;/TreeView&gt; </code></pre> <p>This works only in one way and I have to call the function every time I manipulate the data. Is it possible to do this with a converter in the Data Template? What would be the mvvm approach to do this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T13:56:33.843", "Id": "532873", "Score": "0", "body": "Personally i'd use a `TreeNode : ITreeNode` and `ITreeNode : IList<ITreeNode`, then a node could be an `IServer`, i.e. create an abstract tree in which you could do `OfType<T>` and even implement methods such as `Traverse<T>`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T19:06:34.907", "Id": "532874", "Score": "0", "body": "Ok... I am not sure how this is working. Do you have an example how to use these?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T14:53:55.033", "Id": "532875", "Score": "0", "body": "What I'm talking about is https://en.wikipedia.org/wiki/Tree_(data_structure) that you'd agrement with either https://en.wikipedia.org/wiki/Depth-first_search or https://en.wikipedia.org/wiki/Breadth-first_search depending your needs + a bit of LINQ for easier usage. It isn't terribly difficult to write such thing." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T13:15:44.233", "Id": "269971", "Score": "0", "Tags": [ "c#", "wpf" ], "Title": "Sort Data in Categories to display in Treeview" }
269971
<p>I'm trying to learn and write best practice unittests and practice test driven design. Can you give me some tips and review my code?</p> <pre><code>using System.Threading.Tasks; using Moq; using Xunit; namespace Blockchain.Unittests { public class AccountShould { private static string _webUrl = &quot;https://test.test/test&quot;; [Fact] public async Task ReturnAccountBalance4EthWhenGivenAddress() { // Arrange var address = AccountData.Address; var web3RepositoryMock = new Mock&lt;IWeb3Repository&gt;(); web3RepositoryMock .Setup(web3RepositoryMock =&gt; web3RepositoryMock.GetAccountBalanceInEth(It.IsAny&lt;string&gt;())) .ReturnsAsync(4); var account = new Account(web3RepositoryMock.Object); // Act var balance = await account.GetBalanceInEth(address); // Assert Assert.Equal(4, balance); } } } </code></pre> <p><a href="https://github.com/mnirm/learning-blockchain/blob/feature/test-get-account-balance/Blockchain.Unittests/AccountShould.cs" rel="nofollow noreferrer">https://github.com/mnirm/learning-blockchain/blob/feature/test-get-account-balance/Blockchain.Unittests/AccountShould.cs</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T13:41:49.033", "Id": "532888", "Score": "0", "body": "In your test you are testing moq :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T13:45:41.067", "Id": "532890", "Score": "0", "body": "Normally when we write unit tests then we make assertions against `ClassA`'s functionality, which relies on `ClassB`. We are mocking `ClassB` in order to focus only on `ClassA`'s code by making `ClassB`'s response deterministic and predictable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T13:47:05.397", "Id": "532892", "Score": "0", "body": "In your case `accountStub` is the mocked `ClassB`. But you don't have `ClassA` in your test." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T13:59:05.150", "Id": "532895", "Score": "0", "body": "@PeterCsala so I should moq the Web3 class?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T13:59:41.273", "Id": "532896", "Score": "0", "body": "@PeterCsala what do you recommend me, how should I write this test then? I'm trying to learn and write good unit tests" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T14:30:16.827", "Id": "532901", "Score": "0", "body": "Yes, `Web3` is the dependency (`ClassB` in my analogy) of `Account` (`ClassA` in my analogy). So if you want to test `GetAccountBalanceInEth` then you need to mock `SendRequestAsync` and `FromWei`. Unfortunately your `Account` relies on implementation rather than abstraction. (If `Web3` implements an interface which exposes `SendRequestAsync` then you should rely on that). Also your code relies on a static method (`FromWei`), which is really hard to mock." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T22:35:55.913", "Id": "532927", "Score": "0", "body": "@PeterCsala I refactored my code and made an repository for the web3 object and I mocked the repository then." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T06:40:54.660", "Id": "532947", "Score": "0", "body": "Since no review has been posted yet, you can update your questions code part to show us recent changes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T08:06:00.003", "Id": "532955", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/131376/discussion-between-mounir-mehjoub-and-peter-csala)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T08:06:30.263", "Id": "532956", "Score": "0", "body": "@PeterCsala don, updated my review" } ]
[ { "body": "<p>Your <code>GetBalanceInEth</code> is a wrapper around the <code>GetAccountBalanceInEth</code> call. That's why you can't test too much things.</p>\n<p>But this here are my advices:</p>\n<ul>\n<li>Rename your test to follow the <code>Given-When-Then</code> pattern</li>\n<li>Preserve <code>4</code> in a <code>const</code> so you can express the intent that <code>Account</code> does not modify that value</li>\n</ul>\n<pre><code>public async Task GivenAValidAddressAndAFlawlessRepository_WhenICallGetBalanceInEth_ThenItReturnsTheOutputWithoutModification()\n{\n // Arrange\n const decimal expectedBalance = 4;\n var address = AccountData.Address;\n var web3RepositoryMock = new Mock&lt;IWeb3Repository&gt;();\n\n web3RepositoryMock\n .Setup(web3RepositoryMock =&gt; web3RepositoryMock.GetAccountBalanceInEth(It.IsAny&lt;string&gt;()))\n .ReturnsAsync(expectedBalance);\n\n var account = new Account(web3RepositoryMock.Object);\n \n // Act\n var balance = await account.GetBalanceInEth(address);\n\n // Assert\n Assert.Equal(expectedBalance, balance);\n}\n</code></pre>\n<ul>\n<li>Write a test to make sure that the your <code>GetAccountBalanceInEth</code> does not swallow exception</li>\n</ul>\n<pre><code>public async Task GivenAnInvalidAddressAndAFlaultyRepository_WhenICallGetBalanceInEth_ThenItThrowsUriFormatException()\n{\n // Arrange\n string errorMessage = &quot;The provided url is malformed&quot;;\n UriFormatException toBeThrownException = new UriFormatException(errorMessage);\n var address = AccountData.Address;\n var web3RepositoryMock = new Mock&lt;IWeb3Repository&gt;();\n\n web3RepositoryMock\n .Setup(web3RepositoryMock =&gt; web3RepositoryMock.GetAccountBalanceInEth(It.IsAny&lt;string&gt;()))\n .ThrowsAsync(toBeThrownException);\n\n var account = new Account(web3RepositoryMock.Object);\n \n // Act\n Func&lt;Task&gt; act = () =&gt; account.GetBalanceInEth(address);\n\n // Assert\n UriFormatException ex = await Assert.ThrowsAsync&lt;UriFormatException&gt;(act);\n Assert.Contains(errorMessage, ex.Message);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T14:02:48.227", "Id": "270014", "ParentId": "269972", "Score": "1" } } ]
{ "AcceptedAnswerId": "270014", "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T10:18:42.320", "Id": "269972", "Score": "1", "Tags": [ "c#", ".net", "xunit" ], "Title": "Unittesting in .NET 6 with XUnit" }
269972
<p>I am extracting/processing some data from a netCDF file. It is the first time I am processing the netCDF file. The data processing is super slow, and I would like to learn how to speed up the process.</p> <p>Following is the code:</p> <pre><code>import numpy as np from netCDF4 import Dataset deltaLambdaI = float(input(&quot;deltaLambdaI &quot;)) #magnitude of noise data = Dataset(f&quot;deltaLambdaI={deltaLambdaI:0.2f}/merged.vm.nc&quot;, 'r') n_frames = len(data.groups) time = np.zeros(n_frames) abs_psi6 = np.zeros(n_frames) re_psi6 = np.zeros(n_frames) index = 0 for group in data.groups: nc = data[group] time[index] = int(nc['Network::time'][:]) xPos = nc['Vertex::x'][:] yPos = nc['Vertex::y'][:] xWidth = np.float(nc['Frame::xWidth'][:]) yWidth = np.float(nc['Frame::yWidth'][:]) skew = np.float(nc['Frame::skewVariable'][:]) rightVertices = nc['Bond::rightVertex'][:] conjbonds = nc['Bond::conjBond'][:] leftVertices = rightVertices[conjbonds] xPer = nc['Bond::xPer'][:] yPer = nc['Bond::yPer'][:] nh_pairs = zip(nc['Bond::cell'][:], nc['Bond::cell'][nc['Bond::conjBond'][:]]) hexatic_order_list_randomized= [] for cId in range( len( nc['Cell::xCenter'][:] ) ): nhs = nc['Bond::cell'][nc['Bond::cell'][nc['Bond::conjBond'][:]] == cId] xc = nc['Cell::xCenter'][cId] yc = nc['Cell::yCenter'][cId] hexatic_order = 0. for nh in nhs: xnh = nc['Cell::xCenter'][nh] ynh = nc['Cell::yCenter'][nh] dx = xnh - xc dy = ynh - yc if dy &gt; yWidth/2.: dy -= yWidth dx -= skew*xWidth elif dy &lt; - yWidth/2.: dy += yWidth dx += skew*xWidth if dx &gt; xWidth/2.: dx -= xWidth elif dx &lt; -xWidth/2.: dx += xWidth hexatic_order += np.exp(6*1j*np.arctan2(dy,dx)) #bond avg for cell hexatic_order /= len(nhs) #bond avg for cell hexatic_order_list_randomized.append(hexatic_order) #cell calc. added into frame mean = np.mean(hexatic_order_list_randomized) abs_psi6[index] += np.abs(mean) re_psi6[index] += np.real(mean) #print(f&quot;{time[index]}\t{np.abs(mean)}&quot;) #avg over all cells index += 1 with open(f&quot;data_deltaLambdaI{deltaLambdaI}.dat&quot;, &quot;w&quot;) as fp: fp.write(&quot;##time\tre_psi6\tabs_psi6\n&quot;) for _ in range(n_frames): fp.write(f&quot;{time[_]}\t{re_psi6[_]}\t{abs_psi6[_]}\n&quot;) </code></pre> <p>And here's the source file: <a href="https://drive.google.com/file/d/1aQunWdmwNTkWd8dzoMe9V1CMMkrssIM9/view?usp=sharing" rel="nofollow noreferrer">link redirecting to file.</a></p> <p>File structure is something like: <code>file ('merged.vm.nc') -&gt; groups ('network0001.vm', 'network0011.vm', ...) -&gt; Variables ('Network::time', ...)</code></p> <p>One more note, earlier I had many <code>network????.vm.nc</code> which I merged to form a single file <code>merged.vm.nc</code> to meet disk quota requirement. I merged them using <code>ncecat -4 --gag network????.vm.nc merged.vm.nc</code>. When I am running a similar code on all un-merged files, it is processing data very fast. It could be probably that the new merged file is highly compressed? and it is taking a lot of time? I really don't know what's going on.</p> <p>I have plenty of resources (64GB RAM and 24 Cores), but I do not know how to make good use out of them.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T13:15:08.440", "Id": "269975", "Score": "0", "Tags": [ "performance", "python-3.x" ], "Title": "Optimizing data processing of netCDF file" }
269975
<p>I'm taking a course and I've just completed a challenge. The program runs well and it does everything I told it to, but I would like suggestions as to what can I implement to make it better (ex. pointers, move constructors etc.).</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; using namespace std; class Movie { private: friend class Movies; string name; string rating; int times_watched; public: Movie(string name1, string rating1, int times_watched1) :name{ name1 }, rating{ rating1 }, times_watched{ times_watched1 } {} }; class Movies { private: vector &lt;Movie&gt; list; public: bool check_movie(const Movie &amp;movie1) { for (int i = 0; i &lt; list.size(); i++) if (list.at(i).name == movie1.name) return true; return false; } void add_movie(const Movie movie1) { if (check_movie(movie1) == false) list.push_back(movie1); else cout &lt;&lt; &quot;Movie is already in the list\n&quot;; } void increment_watched_count(Movie &amp;movie1) { if (check_movie(movie1) == true) { for (int i = 0; i &lt; list.size(); i++) if (list.at(i).name == movie1.name) list.at(i).times_watched++; } else cout &lt;&lt; &quot;Movie is not on the list\n&quot;; } void display_list() { for (int i = 0; i &lt; list.size(); i++) cout &lt;&lt; list.at(i).name &lt;&lt; &quot; | &quot; &lt;&lt; list.at(i).rating &lt;&lt; &quot; | &quot; &lt;&lt; list.at(i).times_watched &lt;&lt; endl; } }; int main() { Movies collection; Movie Star_Wars{ &quot;Star Wars&quot;, &quot;E&quot;, 100 }, Anna_Karenina{ &quot;Anna Karenina&quot;,&quot;PG-13&quot;,100 }; collection.add_movie(Movie{ &quot;Dictator&quot;,&quot;PG-13&quot;,3 }); collection.add_movie(Movie{ &quot;Harry Potter&quot;,&quot;E&quot;,1000 }); collection.add_movie(Star_Wars); collection.add_movie(Anna_Karenina); collection.display_list(); collection.increment_watched_count(Anna_Karenina); collection.display_list(); system(&quot;pause&quot;); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T13:44:50.837", "Id": "532889", "Score": "1", "body": "If this is a programming challenge, please quote the text of the challenge itself in the question, add a link to the programming challenge and provided any example input and output. The title of the question should probably be the title of the programming challenge. We need more information to provide a good code review. Please read [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T13:46:23.833", "Id": "532891", "Score": "0", "body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T17:54:24.900", "Id": "533135", "Score": "0", "body": "`The program […] does everything I told it to` Have the program tell everybody (including maintenance programmers and reviewers) what it exists to do." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T17:57:52.803", "Id": "533136", "Score": "0", "body": "(`what can I implement to make [my program] more efficient? ` Tests for continued usefulness, if not correctness. Instrumentation to have a solid base to verify and hunt down efficiency problems - *why* assume there was one?)" } ]
[ { "body": "<p><a href=\"https://stackoverflow.com/questions/1452721\">Don’t</a> write <code>using namespace std;</code>.</p>\n<p>You can, however, in a CPP file (not H file) or inside a function put individual <code>using std::string;</code> etc. (See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#sf7-dont-write-using-namespace-at-global-scope-in-a-header-file\" rel=\"nofollow noreferrer\">SF.7</a>.)</p>\n<hr />\n<pre><code>Movie(string name1, string rating1, int times_watched1)\n :name{ name1 }, rating{ rating1 }, times_watched{ times_watched1 } {}\n</code></pre>\n<p>You are passing the <code>string</code> arguments <em>by value</em> but you are not making use of the <em>sink</em> idiom. I don't know if you made the common mistake of not passing strings by reference (if you came from a language that had all objects be references), or were trying to get fancy and didn't get it right.</p>\n<hr />\n<pre><code>void add_movie(const Movie movie1)\n</code></pre>\n<p><strong>OK</strong>, definitely the former. Print this out on a 4x6 inch card and tape it above your monitor:</p>\n<h1>C++ has value semantics</h1>\n<hr />\n<p>Here, you are telling it to make a complete copy of the entire <code>Movie</code> object, duplicating all the strings it contains.</p>\n<hr />\n<pre><code> void increment_watched_count(Movie &amp;movie1)\n</code></pre>\n<p>Here, you got the <code>&amp;</code> but forgot the <code>const</code>. If you had used <code>const</code> on your data in <code>main</code>, you would have found out!</p>\n<hr />\n<p>The style in C++ is to put the <code>*</code> or <code>&amp;</code> with the <em>type</em>, not the identifier. This is called out specifically near the beginning of Stroustrup’s first book, and is an intentional difference from C style.</p>\n<hr />\n<pre><code>if (check_movie(movie1) == true)\nif (check_movie(movie1) == false)\n</code></pre>\n<p>Don't write explicit tests against <code>true</code> or <code>false</code>. The result of <code>check_movie</code> is already a boolean value. So is the result of <code>operator==</code>. So if you want to go that way, you should write <code>(check_movie(movie1)==true)==true)</code> but now you still have a boolean result; you going to check that to be <code>true</code> too? It would never end!</p>\n<p>The second one should be <code>if (!check_movie(movie1))</code>.</p>\n<hr />\n<pre><code> for (int i = 0; i &lt; list.size(); i++)\n</code></pre>\n<p>Use a range-based <code>for</code> loop. Write:\n<code>for (const auto&amp; m : list) {</code><br />\nand you do not need to do any subscripting. The variable <code>m</code> is available inside the body of the loop ready to use.</p>\n<hr />\n<p><code>check_movie</code> is just doing a search. Don't write code to search a vector from scratch. Use <code>std::find</code> or other standard algorithms. Wose, you duplicate the search code, rather than calling a common function to do this.</p>\n<p>You might want to pass in a string only, rather than an entire Movie object, to be matched.</p>\n<p>Here, you always use the name as the key. So maybe you just want to use a <code>std::map</code> instead?</p>\n<p>The <code>display</code> should not be part of the class. Other code may want to do different things, and displaying to too specific. Rather, provide a general way to go through all the objects. Making the <code>Movie</code> object unusable outside of the list class hinders simply exposing the collection in a standard manner</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T22:28:26.450", "Id": "269995", "ParentId": "269976", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T13:20:01.930", "Id": "269976", "Score": "0", "Tags": [ "c++", "performance" ], "Title": "What do you think about my program and what can I implement to make it more efficient? (ex. runtime wise)" }
269976
<p>I'm learning C++ by implementing a previous project I did in Python. This is a simple stack machine which evaluates mathematical expressions, e.g. pow(9, 12). The code to run this on the stack machine would be an ordered list of constants and instructions: 12 9 POW.</p> <p>In Python, preparing such a list is quite straightforward due to the heterogeneous nature of Python containers. I just make a list of numeric types for the constants and string types for the instructions, e.g. [12, 9, &quot;op_pow&quot;]. Constants get pushed to a data stack, and strings are looked up in a dispatch map for their corresponding functions.</p> <p>I'm a bit stuck on how to do the same thing in C++, due to containers only having a single type. The very inefficient way I'm currently doing it is by passing a program as a vector of strings, and then converting the string constants to doubles with the fast_float library.</p> <p>Is there a more efficient way to do this?</p> <p>Below is what I have so far:</p> <pre><code>#include &lt;vector&gt; #include &lt;cmath&gt; #include &lt;string_view&gt; #include &lt;string&gt; #include &lt;iostream&gt; #include &quot;fast_float/fast_float.h&quot; class Machine { public: std::vector&lt;double&gt; stack ; void add () { if (stack.size() &gt; 1) { double a {stack[stack.size() - 1]} ; double b {stack[stack.size() - 2]} ; stack.pop_back() ; stack.pop_back() ; stack.emplace_back(a+b) ; } } void sub () { if (stack.size() &gt; 1) { double a {stack[stack.size() - 1]} ; double b {stack[stack.size() - 2]} ; stack.pop_back() ; stack.pop_back() ; stack.emplace_back(a-b) ; } } void mul () { if (stack.size() &gt; 1) { double a {stack[stack.size() - 1]} ; double b {stack[stack.size() - 2]} ; stack.pop_back() ; stack.pop_back() ; stack.emplace_back(a*b) ; } } void div () { if (stack.size() &gt; 1 &amp;&amp; !(stack[stack.size() - 1] == 0) &amp;&amp; !(stack[stack.size() - 2] == 0)) { double a {stack[stack.size() - 1]} ; double b {stack[stack.size() - 2]} ; stack.pop_back() ; stack.pop_back() ; stack.emplace_back(a/b) ; } } void mod () { if (stack.size() &gt; 1 &amp;&amp; !(stack[stack.size() - 1] == 0) &amp;&amp; !(stack[stack.size() - 2] == 0)) { double a {stack[stack.size() - 1]} ; double b {stack[stack.size() - 2]} ; stack.pop_back() ; stack.pop_back() ; stack.emplace_back(std::fmod(a,b)) ; } } void flr () { if (stack.size() &gt; 0) { double a {stack[stack.size() - 1]} ; stack.pop_back() ; stack.emplace_back(std::floor(a)) ; } } void cei () { if (stack.size() &gt; 0) { double a {stack[stack.size() - 1]} ; stack.pop_back() ; stack.emplace_back(std::ceil(a)) ; } } void abs () { if (stack.size() &gt; 0) { double a {stack[stack.size() - 1]} ; stack.pop_back() ; stack.emplace_back(std::fabs(a)) ; } } void sqrt () { if (stack.size() &gt; 0 &amp;&amp; stack[stack.size() - 1] &gt; 0) { double a {stack[stack.size() - 1]} ; stack.pop_back() ; stack.emplace_back(std::sqrt(a)) ; } } void pow () { if (stack.size() &gt; 1 &amp;&amp; stack[stack.size() - 1] &gt; 0) { double a {stack[stack.size() - 1]} ; double b {stack[stack.size() - 2]} ; stack.pop_back() ; stack.pop_back() ; stack.emplace_back(std::pow(a, b)) ; } } void log () { if (stack.size() &gt; 0 &amp;&amp; stack[stack.size() - 1] &gt; 0) { double a {stack[stack.size() - 1]} ; stack.pop_back() ; stack.emplace_back(std::log(a)) ; } } void exp () { if (stack.size() &gt; 0) { double a {stack[stack.size() - 1]} ; stack.pop_back() ; stack.emplace_back(std::exp(a)) ; } } void sin () { if (stack.size() &gt; 0) { double a {stack[stack.size() - 1]} ; stack.pop_back() ; stack.emplace_back(std::sin(a)) ; } } void cos () { if (stack.size() &gt; 0) { double a {stack[stack.size() - 1]} ; stack.pop_back() ; stack.emplace_back(std::cos(a)) ; } } void tan () { if (stack.size() &gt; 0) { double a {stack[stack.size() - 1]} ; stack.pop_back() ; stack.emplace_back(std::tan(a)) ; } } double run (const std::vector&lt;std::string&gt; &amp;program) { double num ; for (std::string_view instruction : program) { if (instruction == &quot;op_add&quot;) { add() ; } else if (instruction == &quot;op_sub&quot;) { sub() ; } else if (instruction == &quot;op_mul&quot;) { mul() ; } else if (instruction == &quot;op_div&quot;) { div() ; } else if (instruction == &quot;op_mod&quot;) { mod() ; } else if (instruction == &quot;op_flr&quot;) { flr() ; } else if (instruction == &quot;op_cei&quot;) { cei() ; } else if (instruction == &quot;op_abs&quot;) { abs() ; } else if (instruction == &quot;op_sqrt&quot;) { sqrt() ; } else if (instruction == &quot;op_pow&quot;) { pow() ; } else if (instruction == &quot;op_log&quot;) { log() ; } else if (instruction == &quot;op_exp&quot;) { exp() ; } else if (instruction == &quot;op_sin&quot;) { sin() ; } else if (instruction == &quot;op_cos&quot;) { cos() ; } else if (instruction == &quot;op_tan&quot;) { tan() ; } else { fast_float::from_chars( instruction.data(), instruction.data() + instruction.size(), num); stack.emplace_back(num) ; } } if (stack.size()) { return stack[stack.size() -1] ; } else { return 0 ; } } }; int main(int argc, char *argv[]) { std::vector&lt;std::string&gt; program (argv + 1, argv + argc); double solution ; Machine machine ; machine.stack.reserve(50) ; solution = machine.run(program) ; machine.stack.clear() ; std::cout &lt;&lt; solution &lt;&lt; '\n' ; return 0 ; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T17:36:18.820", "Id": "532907", "Score": "0", "body": "Is your `main()` supposed to be double-spaced like that, or is it a problem of how you copied the code into your question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T19:21:00.667", "Id": "532911", "Score": "1", "body": "@upkajdt I’m not OP but IIRC from_chars was not implemented until recently for gcc (msvc had it since Stephan, the STL, wrote the first one)." } ]
[ { "body": "<p>Here is what I would recommend doing:</p>\n<ol>\n<li>Create an <code>enum class</code> called <code>Operation</code> (or something of that sort) with its values being all of the different operator names (POW, ABS, etc.) Info on <code>enum class</code> <a href=\"https://en.cppreference.com/w/cpp/language/enum\" rel=\"nofollow noreferrer\">here</a>.</li>\n<li>Globally overload the <code>operator&gt;&gt;</code> operator for <code>Operation</code>s This overload should read into a static temporary string of some sort and convert that string into an <code>Operation</code>. This enables you to use switch statements instead of a chain if-else statements.</li>\n<li>Since every instruction must have at least one <code>double</code> before an op, read a double, peek at the next character, if the character is a letter then read an <code>Operation</code>; else repeat.</li>\n<li>Instead of storing the operations and the numbers in a vector of strings, simply have a <code>std::stack&lt;double&gt;</code> for storing the args and calculate values &quot;on the fly&quot;, meaning that operations take place immediately and update the stack accordingly.</li>\n</ol>\n<p>For any questions on how to do any of these things, look them up <a href=\"https://en.cppreference.com/w/cpp\" rel=\"nofollow noreferrer\">here</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T19:20:57.137", "Id": "269988", "ParentId": "269983", "Score": "2" } }, { "body": "<p>I think that the closest that you might get to this in C++ is to:</p>\n<ol>\n<li>Use <code>std::variant</code> for the instructions</li>\n<li>Create lookup list for the function with <code>std::map</code></li>\n<li>Implement your own <code>pop</code> function as suggested by @JDługosz</li>\n</ol>\n<p>Since you are not supposed to take an address of a library function, and using old school function pointer is frowned upon, I have updated it to the following:</p>\n<pre><code>#include &lt;charconv&gt;\n#include &lt;cmath&gt;\n#include &lt;functional&gt;\n#include &lt;iostream&gt;\n#include &lt;map&gt;\n#include &lt;sstream&gt;\n#include &lt;string&gt;\n#include &lt;variant&gt;\n#include &lt;vector&gt;\n\ntypedef std::tuple&lt;std::size_t, std::function&lt;double(double, double)&gt;&gt; funcspec; \ntypedef std::variant&lt;double, funcspec&gt; instruction;\n\nstd::vector&lt;instruction&gt; parse(const std::vector&lt;std::string&gt;&amp; args)\n{\n static std::map&lt;std::string, funcspec&gt; functions{\n { &quot;op_abs&quot;, { 1, [](double a, double) { return std::fabs(a); } } },\n { &quot;op_cos&quot;, { 1, [](double a, double) { return std::cos(a); } } },\n { &quot;op_exp&quot;, { 1, [](double a, double) { return std::exp(a); } } },\n { &quot;op_log&quot;, { 1, [](double a, double) { return std::log(a); } } },\n { &quot;op_sin&quot;, { 1, [](double a, double) { return std::sin(a); } } },\n { &quot;op_tan&quot;, { 1, [](double a, double) { return std::tan(a); } } },\n { &quot;op_flr&quot;, { 1, [](double a, double) { return std::floor(a); } } },\n { &quot;op_sqrt&quot;, { 2, [](double a, double) { return std::sqrt(a); } } },\n { &quot;op_add&quot;, { 2, [](double a, double b) { return a + b; } } },\n { &quot;op_div&quot;, { 2, [](double a, double b) { return a / b; } } },\n { &quot;op_mul&quot;, { 2, [](double a, double b) { return a * b; } } },\n { &quot;op_sub&quot;, { 2, [](double a, double b) { return a - b; } } },\n { &quot;op_pow&quot;, { 2, [](double a, double b) { return std::pow(a, b); } } },\n { &quot;op_mod&quot;, { 2, [](double a, double b) { return std::fmod(a, b); } } }\n };\n\n std::vector&lt;instruction&gt; instructions;\n for (auto arg : args)\n {\n // numbers\n double number;\n auto ret = std::from_chars(arg.data(), arg.data() + arg.size(), number);\n if (ret.ec == std::errc() &amp;&amp; ret.ptr == arg.data() + arg.size())\n {\n instructions.emplace_back(number);\n continue;\n }\n\n // functions\n auto funcion = functions.find(arg);\n if (funcion != functions.end())\n {\n instructions.emplace_back(funcion-&gt;second);\n continue;\n }\n\n std::ostringstream oss;\n oss &lt;&lt; &quot;Error: invalid instruction: &quot; &lt;&lt; arg;\n throw std::runtime_error(oss.str());\n }\n return instructions;\n}\n\ndouble pop(std::vector&lt;double&gt;&amp; stack)\n{\n if (stack.empty())\n throw std::runtime_error(&quot;Error: failed to pop value from an empty stack&quot;);\n double retval = stack.back();\n stack.pop_back();\n return retval;\n}\n\ndouble run(const std::vector&lt;instruction&gt;&amp; instructions)\n{\n std::vector&lt;double&gt; stack;\n double a = 0;\n double b = 0;\n stack.reserve(50);\n for (const auto&amp; inst : instructions)\n {\n if (inst.index() == 0)\n {\n stack.emplace_back(std::get&lt;double&gt;(inst));\n }\n else\n {\n auto funcion = std::get&lt;funcspec&gt;(inst);\n if (std::get&lt;0&gt;(funcion) == 1)\n stack.emplace_back(std::get&lt;1&gt;(funcion)(pop(stack), 0));\n else\n stack.emplace_back(std::get&lt;1&gt;(funcion)(pop(stack), pop(stack)));\n }\n }\n return stack.empty() ? 0 : stack.back();\n}\n\nint main(int argc, char* argv[])\n{\n try\n {\n auto arguments = std::vector&lt;std::string&gt;(argv + 1, argv + argc);\n auto instructions = parse(arguments);\n std::cout &lt;&lt; run(instructions);\n }\n catch (std::exception err)\n {\n std::cerr &lt;&lt; err.what();\n return 1;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T21:16:39.113", "Id": "532920", "Score": "0", "body": "The OP is looking for efficiency, not simplicity." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T20:27:59.780", "Id": "269992", "ParentId": "269983", "Score": "1" } }, { "body": "<blockquote>\n<p>In Python, preparing such a list is quite straightforward due to the heterogeneous nature of Python containers. I just make a list of numeric types for the constants and string types for the instructions, e.g. [12, 9, &quot;op_pow&quot;]. Constants get pushed to a data stack, and strings are looked up in a dispatch map for their corresponding functions.</p>\n</blockquote>\n<p>Use <code>std::variant&lt;double,std::string&gt;</code>. Then use <code>std::visit</code> to perform a different action depending on the type of the element.</p>\n<pre><code>struct instruction_visitor {\n\n void operator() (double x) const \n { stack.push_back(x); }\n\n void operator() (const std::string&amp; cmd) const\n {\n // interpret the command string\n }\n};\n</code></pre>\n<p>On the other hand, it makes sense that if you are treating the commands as strings to be parsed as part of the interpretation, why not treat constants the same way, as strings? That is not an issue with your existing code as presented; that is the way it ought to work if you want to load a text file and run it.</p>\n<p>If you will have numbers as actual numbers already of the right type, then why wouldn't you do the same thing with the commands? You don't need a mapping from command name string to the function! Rather, just put a function pointer directly in the instruction list.</p>\n<pre><code>using command_t = void(*)();\nusing instruction = std::variant&lt;double,command_t&gt;;\n\n\nstruct instruction_visitor {\n\n void operator() (double x) const \n { stack.push_back(x); }\n\n void operator() (command_t cmd) const\n { cmd(); }\n};\n</code></pre>\n<p>But as you show it, you (rightfully) have an instruction list of strings, and you decide whether it's a literal or command (and later, a variable perhaps) as part of the interpretation. There is no need for a variant type anywhere, and your approach is sound. (Though I would suggest a data structure rather than a gang of if/else statements)</p>\n<hr />\n<p>In your implementation:</p>\n<pre><code> double a {stack[stack.size() - 1]} ; \n double b {stack[stack.size() - 2]} ; \n stack.pop_back() ;\n stack.pop_back() ;\n</code></pre>\n<p>You should write a helper function <code>pop</code>, something like:</p>\n<pre><code>double pop()\n{\n double retval= stack.back();\n stack.pop_back();\n return retval;\n}\n</code></pre>\n<p>Then you can write simply</p>\n<pre><code> const double a = pop();\n const double b = pop();\n stack.push_back (a+b);\n</code></pre>\n<p>If you want to get fancier, you could implement a helper that does the argument count check and pops all of them:</p>\n<pre><code> const auto [a,b] = take&lt;2&gt;();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T13:55:05.217", "Id": "532980", "Score": "1", "body": "You are correct as always ;-) for a simple sequential list of instructions like we currently have, there is no benefit to first parse it to vector of variants." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T22:08:12.047", "Id": "269994", "ParentId": "269983", "Score": "1" } }, { "body": "<p>If the program is read from command line arguments or from another external source, then you will have to convert strings to <code>double</code>s at some point.\nIf you only ever run the program once, then what you are doing is fine. However, if you intend to call <code>run()</code> multiple times, then it would indeed be better to convert the input in something that is more efficient to handle. I think upkajdt's answer of using a <code>std::variant</code> that can hold a <code>double</code> or a <code>std::function</code> is a very reasonable way to do it.</p>\n<p>You could go further than this; I explored this myself a bit in this question about creating a <a href=\"https://codereview.stackexchange.com/questions/259045/poor-mans-jit-using-nested-lambdas\">poor man's JIT using lambdas</a>, some of the answers there might be helpful as well. The most extreme way of optimizing it would be to compile the program to machine code. This is certainly possible but has several drawbacks; apart from the fact that compiling the code takes a lot longer than interpreting it, meaning that it only pays of if you call the program a lot, there's also the dependency on a compiler or a library like <a href=\"https://clang.llvm.org/doxygen/group__CINDEX.html\" rel=\"nofollow noreferrer\">libclang</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T10:27:13.313", "Id": "270008", "ParentId": "269983", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T16:34:19.607", "Id": "269983", "Score": "3", "Tags": [ "c++", "performance", "stack" ], "Title": "Passing Programs To A Stack Machine Implemented In C++" }
269983
<p>I am creating an alert system for a game/sim in C# that keeps track of negative actions performed by the user during a training exercise. There are preconfigured alerts that have data, such as UI text and how many times the alert may be triggered before the user fails the exercise. Whenever an alert is triggered, there may or may not also be data bundled with the alert that I refer to as &quot;alert instance&quot; data, such as the user's speed. I am trying to design the system in the most modular way so new alerts can easily be created and added over time and such that it also allows for quick querying.</p> <p>I created an abstract class for an alert so I could create one type of alert that does not require instance data and another one that does. I have also created a separate controller class that manages alerts and provides an API.</p> <p>Below is the code that can run in dotnetfiddle</p> <pre><code>using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Xml; public class Sample { public abstract class BaseAlert { public string ID; public string Message; public int FailCount; public int TriggerCount; } // an alert that does not require instance data public class Alert : BaseAlert { public virtual void Trigger() { TriggerCount += 1; } } // an alert that requires data when triggered public class BundleAlert : BaseAlert { public List&lt;AlertData&gt; InstanceData; public virtual void Trigger(AlertData data) { if(InstanceData == null) { InstanceData = new List&lt;AlertData&gt;(); } TriggerCount += 1; InstanceData.Add(data); } // create a subclass of this to create alert-specific data public abstract class AlertData { } } public class CollisionAlert : BundleAlert { public override void Trigger(AlertData data) { if(!(data is CollisionData)) { throw new Exception(&quot;CollisionAlert requires CollisionData&quot;); } base.Trigger(data); } public class CollisionData : AlertData { public float speed; } } public class AlertController { private Dictionary&lt;string, BaseAlert&gt; _alerts; public AlertController() { _alerts = new Dictionary&lt;string, BaseAlert&gt;(); } // create preconfigured alert public void SetupAlert(BaseAlert alert) { _alerts.Add(alert.ID, alert); } // trigger an alert public void Alert(string id, BundleAlert.AlertData data) { if( _alerts[id] is BundleAlert ) { ((BundleAlert)_alerts[id]).Trigger(data); } else { ((Alert)_alerts[id]).Trigger(); } } // used to demo querying the alerts public void PrintAlerts() { var keys = _alerts.Keys; foreach(var key in keys) { if(_alerts[key] is CollisionAlert) { var speed = ((CollisionAlert.CollisionData)(((CollisionAlert)_alerts[key]).InstanceData[0])).speed; System.Console.WriteLine(&quot;Collision at: &quot; + speed); } else if(_alerts[key] is Alert) { System.Console.WriteLine(&quot;Alert: &quot; + ((Alert)_alerts[key]).ID + &quot;; TriggerCount = &quot; + ((Alert)_alerts[key]).TriggerCount); } } } } public static void Main() { AlertController _alertController = new AlertController(); Alert failedToStop = new Alert() { ID = &quot;FailedToStop&quot;, Message = &quot;Failed to stop&quot;, FailCount = 1 }; _alertController.SetupAlert(failedToStop); CollisionAlert collision = new CollisionAlert() { ID = &quot;WallCollision&quot;, Message = &quot;Wall Collision&quot;, FailCount = 1 }; _alertController.SetupAlert(collision); CollisionAlert.CollisionData collisionData = new CollisionAlert.CollisionData() { speed = 5.0f }; _alertController.Alert(&quot;FailedToStop&quot;, null); _alertController.Alert(&quot;WallCollision&quot;, collisionData); _alertController.PrintAlerts(); } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T17:08:16.877", "Id": "269985", "Score": "1", "Tags": [ "c#", "design-patterns" ], "Title": "Alert system for game or simulator" }
269985
<p>I'm learning about OOP and putting my knowledge into practice. I created a login system in PHP, so I wish someone could tell me if I'm on the right track. I feel like I'm getting better at coding, but it's never good enough, so I want someone more experienced (especially in OOP) to look at my code and tell me if I'm doing it right and what I can improve. <br><br>Just a note, I recognize that the PHP code contained in HTML is not something appropriate, but I just put it to make it easier to understand how the system works. Therefore, I ask you to focus on the login system part, more precisely on OOP.</p> <p><strong>Tree</strong></p> <pre><code>Login(directory):. │ composer.json │ Dashboard.php │ Main.php │ Signin.php │ ├───.idea │ .gitignore │ Login.iml │ modules.xml │ php.xml │ workspace.xml │ ├───src │ HttpTransport.php │ Login.php │ Session.php │ UserAccount.php │ └───vendor │ autoload.php │ └───composer autoload_classmap.php autoload_namespaces.php autoload_psr4.php autoload_real.php autoload_static.php ClassLoader.php LICENSE </code></pre> <p><strong>UserAccount.php</strong></p> <pre><code>&lt;?php declare(strict_types = 1); namespace Login; class UserAccount { private string $email; private string $password; public function setEmail(string $email): void { $this-&gt;email = $email; } public function getEmail(): string { return $this-&gt;email; } public function setPassword(string $password): void { $this-&gt;password = $password; } public function getPassword(): string { return $this-&gt;password; } } </code></pre> <p><strong>Session.php</strong></p> <pre><code>&lt;?php declare(strict_types = 1); namespace Login; class Session { public static function startSession(string $sessionName, string $value) { return $_SESSION[$sessionName] = $value; } } </code></pre> <p><strong>HttpTransport</strong></p> <pre><code>&lt;?php declare(strict_types = 1); namespace Login; class HttpTransport { public static function setFlashMessage(string $message): string { return $message; } public static function redirect(string $path): void { header('Location: ' . $path); exit; } } </code></pre> <p><strong>Login.php</strong></p> <pre><code>&lt;?php declare(strict_types = 1); namespace Login; use \Login\HttpTransport; use \Login\Session; class Login { public function __construct(public \PDO $conn) { } public function login(UserAccount $user) { $sql = &quot;SELECT * FROM users WHERE email = ?&quot;; $statement = $this-&gt;conn-&gt;prepare($sql); $statement-&gt;execute([ $user-&gt;getEmail() ]); if ($statement-&gt;rowCount() &gt; 0) { $rows = $statement-&gt;fetchAll(\PDO::FETCH_ASSOC); foreach ($rows as $row) { $passwordHash = $row['passwordHash']; $hash = password_verify($user-&gt;getPassword(), $passwordHash); if ($hash) { Session::startSession('username', $row['username']); HttpTransport::redirect('/login/dashboard.php'); } else { $flashMessage = HttpTransport::setFlashMessage('&lt;p&gt;Incorrect e-mail or password.&lt;/p&gt;'); Session::startSession('error', $flashMessage); HttpTransport::redirect('/login/signin.php'); } } } else { $flashMessage = HttpTransport::setFlashMessage('&lt;p&gt;Incorrect e-mail or password.&lt;/p&gt;'); Session::startSession('error', $flashMessage); HttpTransport::redirect('/login/signin.php'); } } } </code></pre> <p><strong>Signin.php</strong></p> <pre><code>&lt;?php session_start(); session_regenerate_id(true); if (isset($_SESSION['username'])) { header('Location: dashboard.php'); exit; } ?&gt; &lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;title&gt;Login&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form method=&quot;POST&quot; action=&quot;Main.php&quot;&gt; &lt;?php if (isset($_SESSION['error'])) { echo $_SESSION['error']; unset($_SESSION['error']); } ?&gt; &lt;p&gt;E-mail&lt;/p&gt; &lt;input type=&quot;email&quot; placeholder=&quot;Enter e-mail&quot; name=&quot;email&quot; required autofocus&gt;&lt;br&gt;&lt;br&gt; &lt;p&gt;Password&lt;/p&gt; &lt;input type=&quot;password&quot; placeholder=&quot;Enter password&quot; name=&quot;password&quot; required&gt;&lt;br&gt;&lt;br&gt; &lt;input type=&quot;submit&quot; value=&quot;Login&quot;&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>Dashboard.php</strong></p> <pre><code>&lt;?php session_start(); session_regenerate_id(true); $username = $_SESSION['username']; if (isset($username)) { echo &quot;Logged in!&quot;; echo &quot;&lt;br&gt;&lt;br&gt;&quot;; echo &quot;Welcome, &quot; . htmlentities($username); } else { header('Location: signin.php'); exit; } </code></pre> <p><strong>Main.php</strong></p> <pre><code>&lt;?php declare(strict_types = 1); require_once __DIR__ . '/vendor/autoload.php'; session_start(); try { $username = 'root'; $password = ''; $conn = new \PDO(&quot;mysql:host=localhost;dbname=customers;charset=utf8mb4&quot;, $username, $password, [ \PDO::ATTR_ERRMODE =&gt; \PDO::ERRMODE_EXCEPTION, \PDO::ATTR_EMULATE_PREPARES =&gt; false ]); } catch (\PDOException $e) { throw new \PDOException($e-&gt;getMessage(), (int) $e-&gt;getCode()); } $user = new \Login\UserAccount(); $user-&gt;setEmail(filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL)); $user-&gt;setPassword(filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING)); (new \Login\Login($conn))-&gt;login($user); </code></pre> <p><strong>SQL</strong></p> <pre><code>-- phpMyAdmin SQL Dump -- version 5.1.1 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Nov 11, 2021 at 07:49 PM -- Server version: 10.4.21-MariaDB -- PHP Version: 8.0.12 SET SQL_MODE = &quot;NO_AUTO_VALUE_ON_ZERO&quot;; START TRANSACTION; SET time_zone = &quot;+00:00&quot;; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `customers` -- -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `id` int(11) NOT NULL, `username` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `passwordHash` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `username`, `passwordHash`, `email`) VALUES (1, 'PHP', '$2y$10$sJgO/trlE5Ik1PuIEgzKkuur2V3vpNJ1kQAZfkyjURQD2AWuF3IWK', 'php@mail.com'), (3, 'Warlock', '$2y$10$B3VHrEmkjUUk2yncfQs.V.lR8FXat0tBj.LhxWEU9U5fuXhkYcSAi', 'warlock@mail.com'); -- -- Indexes for dumped tables -- -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `username` (`username`), ADD UNIQUE KEY `email` (`email`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; </code></pre> <p>If you want to make login:<br></p> <p>E-mail: warlock@mail.com<br> Pass: Rptw36VWBU%7DF</p> <p><strong>composer.json</strong></p> <pre><code>{ &quot;autoload&quot;: { &quot;psr-4&quot;: { &quot;Login\\&quot; : &quot;src/&quot; } } } </code></pre> <p><strong>Questions</strong></p> <ol> <li>Is my code clean?</li> <li>Am I following the sole responsibility principle that a class should only do one thing?</li> <li>Regarding naming, do you think I'm naming things correctly?</li> <li>What do you suggest for me to become a better developer?</li> </ol> <p>I appreciate any help, if you can give tips on how to improve the code or how to learn more, something like recommending books, I would be happy to. My goal is to learn, I believe the code is well structured and easy to read, but maybe you have more experience and can find something wrong, however, my goal is to learn, so feel free to criticize and give tips.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T20:39:50.037", "Id": "532919", "Score": "0", "body": "The question I'd ask you is why do you want to use OOP? Just because you read about something doesn't mean it's a good idea. I would think about what exactly you're trying to achieve using it, and if you don't know, try and learn that too rather than focusing on 'best practices' for no clear reason." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T21:34:26.783", "Id": "532921", "Score": "0", "body": "@rak1507 Why OOP? Because it was created for some reason. I don't know if you're suggesting I use procedural programming, but I refuse to believe that. And I don't need to talk about the advantages of OOP, you should understand. The point of the question is: I hope someone more experienced will find inconsistencies in my code, tell me if the relationships between the objects make sense, if the naming is correct, and what I can do to improve it. Also, I'm not limited to PHP either, what I learn with OOP will work in other languages like Java and C#." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T21:34:32.580", "Id": "532922", "Score": "0", "body": "I looked at the \"login.php\" file, and the first thing I noticed was that it has an empty constructor and `$this->conn` was not defined when the `login()` method is used. Can you confirm that this is working code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T21:36:50.610", "Id": "532923", "Score": "1", "body": "@KIKOSoftware Yes, the code works. The constructor method takes a PDO connection, you can check this in the `Main.php` file. Obs: I'm using PHP version 8.0.12" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T21:45:26.623", "Id": "532925", "Score": "3", "body": "Ah, [Constructor Promotion](https://www.php.net/manual/en/language.oop5.decon.php#language.oop5.decon.constructor.promotion). I missed that trick, still working in PHP 7 for now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T23:16:01.380", "Id": "532928", "Score": "0", "body": "@Warlock I'm not suggesting you use any particular paradigm, I'm suggesting you think about what you're actually trying to achieve by doing something. OOP is a means to an end, not the end goal itself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T04:59:09.557", "Id": "532943", "Score": "5", "body": "Personal opinion: class UserAccount should simply have public variables. Classes with only variables which all have getters and setters are useless imo. (Though I feel like a lot of people don't agree with me. @those people: I come from a C++ background, and would make this a struct instead of a class.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T13:27:06.503", "Id": "532979", "Score": "1", "body": "What's the purpose of setFlashMessage?" } ]
[ { "body": "<p>This is a pretty good attempt at a login system. The code looks much better than 99% of code that I see on Stack Overflow. Keep up the good work!</p>\n<p>Your code is almost clean. Your classes do so little that I would consider it too little (more on this later). The naming is almost perfect IMHO. Nonetheless, I have noticed a number of smaller issues that I think you ought to know to become a better developer.</p>\n<h3>Redirects</h3>\n<p>You follow the general rule for 302 redirects: header and exit. Once you switch over to PHP 8.1 I highly recommend using the <code>never</code> type. Take a look at your <code>Login::login()</code> method. You have <code>redirect()</code> followed by <code>else</code> block. That's unnecessary. The code after redirect will never be executed.</p>\n<h3><code>Login::login()</code> needs refactoring</h3>\n<p>It does what it was supposed to do, but the code is overly complex. Despite calling <code>fetchAll()</code> your <code>foreach</code> loop will never iterate more than one row. Either way the code exits due to redirects. <code>password_verify()</code> does not return hash, so you named the variable incorrectly. There's also no reason for the temporary variable. <code>if($statement-&gt;rowCount() &gt; 0</code> is generally considered an antipattern and is unnecessary in this code. <code>SELECT *</code> is also an antipattern you should avoid.</p>\n<p>Consider how it could be simplified and still do the same:</p>\n<pre><code>public function login(UserAccount $user):void\n{\n $sql = &quot;SELECT passwordHash, username FROM users WHERE email = ?&quot;;\n $statement = $this-&gt;conn-&gt;prepare($sql);\n $statement-&gt;execute([\n $user-&gt;getEmail()\n ]);\n\n if ($row = $statement-&gt;fetch(\\PDO::FETCH_ASSOC)) {\n if (password_verify($user-&gt;getPassword(), $row['passwordHash'])) {\n Session::startSession('username', $row['username']);\n HttpTransport::redirect('/login/dashboard.php');\n }\n }\n $flashMessage = HttpTransport::setFlashMessage('&lt;p&gt;Incorrect e-mail or password.&lt;/p&gt;');\n Session::startSession('error', $flashMessage);\n HttpTransport::redirect('/login/signin.php');\n}\n</code></pre>\n<p>I also added <code>void</code> return type, but once you move to PHP 8.1 you should use <code>never</code>.</p>\n<h3>Session class</h3>\n<p>At the moment this class does nothing. You could remove it. However, I think it's a good idea for a class like this with methods to start, regenerate and kill the session. In the start method, you should ensure you use the right storage method, secure cookies, HTTP only. Use <code>session_set_cookie_params()</code> to set these options. You should also set the session name and start it (<code>session_start()</code> should belong in this class).</p>\n<p>Also, <code>session_regenerate_id()</code> after <code>session_start()</code> is not such a good idea. You should regenerate it after successful login and at regular intervals, but not every time the page is loaded.</p>\n<h3>FILTER_SANITIZE_STRING is deprecated in 8.1</h3>\n<p>Do not use this filter. You simply don't need it. Passwords should not be modified in any way. Whatever the value you got from the user, should be the value used in <code>password_verify()</code> without any modification. You can use <code>FILTER_UNSAFE_RAW</code> which leaves the value unchanged.</p>\n<h3>Database credentials are hardcoded</h3>\n<p>Database credentials should never be present in the code. Use config file (do not store it in <a href=\"https://en.wikipedia.org/wiki/Version_control\" rel=\"noreferrer\">VCS</a>). You can use any format you want for the config file, PHP file, JSON, INI, YAML, NEON, etc. <strong>Just do not put it in the code!</strong></p>\n<h3>Document root</h3>\n<p>It looks like your entry points are stored in the main directory. You should create <code>public</code> directory that will be accessible from the internet and store your entry points there. All other code should be inaccessible from the outside.</p>\n<h3>Login does too little</h3>\n<p>This is the last point as this is just an opinion. You don't need to listen to this, but in my opinion the class is too restricted. I would call the class <code>Auth</code> and put all your authentication-related functionality there. There could be a method called <code>logout</code>, a method that rehashes passwords, a method that stores invalid attempts in the database (without passwords) so that you can rate limit or show captcha.</p>\n<p>On the other hand, I would also move all password-related functionality to a separate class. There could be a method that calls <code>https://api.pwnedpasswords.com/range</code> API to check whether the password is compromised. Another method that checks whether the password needs to be rehashed (see. <a href=\"https://www.php.net/manual/en/function.password-needs-rehash.php\" rel=\"noreferrer\"><code>password_needs_rehash()</code></a>). And of course, a method to generate a hash (remember to forbid empty passwords and ones that contain NUL bytes; throw an exception if such password is provided).</p>\n<h3>Conclusion</h3>\n<p>You are very knowledgeable and you are using the latest PHP 8 features. I see you have also read good online resources, e.g. <a href=\"https://phpdelusions.net/\" rel=\"noreferrer\">https://phpdelusions.net/</a>. The code is a very good start. You need a lot more security considerations if this is to become a real login system, e.g. secure sessions/cookies, password rehashing, checking passwords against leaked passwords.</p>\n<p>You have also avoided many pitfalls common to beginners. You don't have SQL injection, you avoid XSS, you catch PDO exception to prevent accidental credential leaks in error logs, you use strict types, <code>utf8mb4</code> in the database, password hashing, and you didn't add arbitrary password restrictions.</p>\n<p>I'd consider you an experienced developer and a valuable asset to any team.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T23:07:57.223", "Id": "269997", "ParentId": "269987", "Score": "18" } }, { "body": "<p>A few other more minor bits not mentioned by Dharman, but agree 100% that the code is very good to start with, the Post - Redirect - Get pattern stands out many login systems do not have that implemented well.</p>\n<p><strong>Consider 2fa</strong></p>\n<p>There are plenty of packages which implement totp or u2f use one of them for an additional security boost</p>\n<p><strong>Structure of file system</strong></p>\n<p>It's hard to be sure, but looking at the structure, that whole structure is exposed to the world.</p>\n<p>This means composer.json for example is exposed to the world, in your case currently, that's not a major issue as there are no dependencies, but imagine you use <code>somePackage</code> later on. <code>somePackage</code> then gets a CVE assigned, you have stated you are using the package and from the version you can see if your server is vulnerable. Vendor is also open.</p>\n<p>Most projects use a <code>public</code> folder in the root and have a single entrypoint php file, which prevents anything like this occurring. Your code is private as its not exposed, and the only public PHP is the index.php file entrypoint which will do things like set up composer and then call the appropriate php functions. Other public assets like images and stylesheets etc would go in this public directory then too.</p>\n<p><strong>The hash chosen</strong></p>\n<p>While there is nothing wrong with bcrypt (it is not mentioned here but clear from the test credentials), for new code I would suggest using Argon2id (<a href=\"https://www.php.net/manual/en/function.password-hash.php\" rel=\"noreferrer\">https://www.php.net/manual/en/function.password-hash.php</a>)</p>\n<p><strong>Too much info? Possibly just a bad user experiance</strong></p>\n<p>Some day, your database will stop responding. When that happens you do have code for it.</p>\n<pre><code>catch (\\PDOException $e)\n{\n throw new \\PDOException($e-&gt;getMessage(), (int) $e-&gt;getCode());\n}\n</code></pre>\n<p>That code will catch and then rethrow, in a prod enviroment where (hopefully) display errors is set to 0, which will only leave this with a blank page. if that variable ever accidentally gets set to 1, your database credentials will likely be part of the output.</p>\n<p>In either case, handling that message with a simple error page to the user is much preferred. Log to a file / some sort of service to alert you, and display an error that you choose, not the standard PHP one.</p>\n<p>There are a few ways you can do this, either wrapping everything in a try catch, or using <code>set_error_handler</code> are common ways to do this.</p>\n<p><strong>Future code duplication</strong></p>\n<pre><code> public function setEmail(string $email): void\n {\n $this-&gt;email = $email;\n }\n\n public function getEmail(): string\n {\n return $this-&gt;email;\n }\n\n</code></pre>\n<p>The above implies that there is no checking at all of email.</p>\n<p>in which case it could / should just be a public attribute, but calling it has this code</p>\n<pre><code>$user-&gt;setEmail(filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL));\n</code></pre>\n<p>In another place in later development, you now need to copy paste this, the validation should really be inside of the method. eg</p>\n<pre><code>public function setEmail(string $email): void\n{\n $email = filter_var($email, FILTER_SANITIZE_EMAIL);\n if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {\n // probably throw some sort of exception here as it's invalid input.\n }\n $this-&gt;email = $email;\n}\n</code></pre>\n<p>This would be picked up by static analysis too as the filter_input command returns <code>mixed</code>, you are passing that output to a function which accepts <code>string</code>.</p>\n<p><a href=\"https://phpstan.org/r/6f7d1925-ddb8-4a42-add3-d1581feed3ef\" rel=\"noreferrer\">https://phpstan.org/r/6f7d1925-ddb8-4a42-add3-d1581feed3ef</a></p>\n<p>phpstan is great and I would recommend running your code though that</p>\n<p>The above code also helps with unit testing, as now your handle code is separate from your input code, so you can test submitting bad input without needing to manipulate the global post variables.</p>\n<p><strong>elses</strong></p>\n<p>The else statement is never necessary and code is always more simple without. Consider guard conditions or similar</p>\n<pre><code>if (isset($username))\n{\n echo &quot;Logged in!&quot;;\n echo &quot;&lt;br&gt;&lt;br&gt;&quot;;\n echo &quot;Welcome, &quot; . htmlentities($username);\n}\nelse\n{\n header('Location: signin.php');\n exit;\n}\n</code></pre>\n<p>Could be</p>\n<pre><code>if (empty($username))\n{\n header('Location: signin.php');\n exit;\n\n}\necho &quot;Logged in!&quot;;\necho &quot;&lt;br&gt;&lt;br&gt;&quot;;\necho &quot;Welcome, &quot; . htmlentities($username);\n</code></pre>\n<p>For example which removes one level of indentation for your &quot;happy path&quot;</p>\n<p>The re written code in the above answer does the same thing, but not mentioning the else removal explicitly.</p>\n<p><strong>Schema</strong></p>\n<pre><code>`passwordHash` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,\n</code></pre>\n<p>You hash will never need that charset, super minor but could use a much more limiting charset there such as latin1 to save some space, if you have millions of users, these things start to make a difference.</p>\n<p><strong>Password in memory</strong></p>\n<p>This really is a minor point (and 99% of systems will not have this), when handling passwords, I prefer to use something like <code>sodium_memzero</code> or just an unset as soon as I have used the secret. This reduces the amount of time in memory which a password lives. The current way lets php decide when to release that memory. This would include the post variable and the <code>UserAccount::$password</code> variable.</p>\n<p><strong>Final words</strong></p>\n<p>As mentioned above, despite the number of small issues here, it's actually good code, I have looked at many login systems in use, and yours even as it was originally posted is ranked high on that list.</p>\n<p>Using tools like phpcs, phpstan, phpmd and phpmnd will help you a huge amount. Get comfortable using them also phpunit for writing tests will be a great thing to learn.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T05:16:34.920", "Id": "270004", "ParentId": "269987", "Score": "7" } } ]
{ "AcceptedAnswerId": "269997", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T19:02:41.590", "Id": "269987", "Score": "10", "Tags": [ "php", "object-oriented", "authentication" ], "Title": "Is my PHP login system following best practices? Is the code really OOP?" }
269987
<p>I have an Enum the encapsulates numeric primitives (u8, i8, u16, i16, u32, i32, u64, i64, f32, f64) into a common type called &quot;Number&quot;. I want to implement a PartialOrd train for the enum based on the encapsulated data allowing different numbers to be compared. I have a solution that uses nested pattern matching and casting, but it seems unwieldy. Is there a better way to do this?</p> <p><a href="https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2021&amp;gist=7edcbe456847fb129475ee40568d21c2" rel="nofollow noreferrer">https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2021&amp;gist=7edcbe456847fb129475ee40568d21c2</a></p> <pre><code>use std::cmp::Ordering; #[derive(PartialEq)] enum Number { U8(u8), I8(i8), U16(u16), I16(i16) } impl PartialOrd for Number { fn partial_cmp(&amp;self, other: &amp;Self) -&gt; Option&lt;Ordering&gt; { // self.height.partial_cmp(&amp;other.height) match self { Number::U8(x) =&gt; { match other { Number::U8(y) =&gt; (*x).partial_cmp(y), Number::I8(y) =&gt; (*x as i16).partial_cmp(&amp;(*y as i16)), Number::U16(y) =&gt; (*x as u16).partial_cmp(y), Number::I16(y) =&gt; (*x as i32).partial_cmp(&amp;(*y as i32)), } }, Number::I8(x) =&gt; { match other { Number::U8(y) =&gt; (*x as i16).partial_cmp(&amp;(*y as i16)), Number::I8(y) =&gt; (*x).partial_cmp(y), Number::U16(y) =&gt; (*x as u16).partial_cmp(y), Number::I16(y) =&gt; (*x as i32).partial_cmp(&amp;(*y as i32)), } }, Number::U16(x) =&gt; { match other { Number::U8(y) =&gt; (*x).partial_cmp(&amp;(*y as u16)), Number::I8(y) =&gt; (*x as i32).partial_cmp(&amp;(*y as i32)), Number::U16(y) =&gt; (*x).partial_cmp(y), Number::I16(y) =&gt; (*x as i32).partial_cmp(&amp;(*y as i32)), } }, Number::I16(x) =&gt; { match other { Number::U8(y) =&gt; (*x).partial_cmp(&amp;(*y as i16)), Number::I8(y) =&gt; (*x).partial_cmp(&amp;(*y as i16)), Number::U16(y) =&gt; (*x as i32).partial_cmp(&amp;(*y as i32)), Number::I16(y) =&gt; (*x).partial_cmp(y), } }, } } } </code></pre>
[]
[ { "body": "<p>You can match on a tuple, which flattens everything:</p>\n<pre><code>impl PartialOrd for Number {\n fn partial_cmp(&amp;self, other: &amp;Self) -&gt; Option&lt;Ordering&gt; {\n match (self, other) {\n (Number::U8(x), Number::U8(y)) =&gt; (*x).partial_cmp(y),\n (Number::U8(x), Number::I8(y)) =&gt; (*x as i16).partial_cmp(&amp;(*y as i16)),\n (Number::U8(x), Number::U16(y)) =&gt; (*x as u16).partial_cmp(y),\n (Number::U8(x), Number::I16(y)) =&gt; (*x as i32).partial_cmp(&amp;(*y as i32)),\n\n (Number::I8(x), Number::U8(y)) =&gt; (*x as i16).partial_cmp(&amp;(*y as i16)),\n (Number::I8(x), Number::I8(y)) =&gt; (*x).partial_cmp(y),\n (Number::I8(x), Number::U16(y)) =&gt; (*x as u16).partial_cmp(y),\n (Number::I8(x), Number::I16(y)) =&gt; (*x as i32).partial_cmp(&amp;(*y as i32)),\n\n (Number::U16(x), Number::U8(y)) =&gt; (*x).partial_cmp(&amp;(*y as u16)),\n (Number::U16(x), Number::I8(y)) =&gt; (*x as i32).partial_cmp(&amp;(*y as i32)),\n (Number::U16(x), Number::U16(y)) =&gt; (*x).partial_cmp(y),\n (Number::U16(x), Number::I16(y)) =&gt; (*x as i32).partial_cmp(&amp;(*y as i32)),\n\n (Number::I16(x), Number::U8(y)) =&gt; (*x).partial_cmp(&amp;(*y as i16)),\n (Number::I16(x), Number::I8(y)) =&gt; (*x).partial_cmp(&amp;(*y as i16)),\n (Number::I16(x), Number::U16(y)) =&gt; (*x as i32).partial_cmp(&amp;(*y as i32)),\n (Number::I16(x), Number::I16(y)) =&gt; (*x).partial_cmp(y),\n }\n }\n}\n</code></pre>\n<p>Whether this is better than nested matches is a matter of taste, I reckon.</p>\n<p>Another way you could simplify your implementation is converting each argument to another (possibly private) enum type with fewer cases (e.g. <code>i64</code>, <code>u64</code> and <code>f64</code> should be enough), then compare pairs of this second enum type (which only yields 2^3 = 8 cases, instead of 2^10 = 1024 cases). In fact, since the size of <code>Number</code> is determined by its largest member, depending on your use case, it might make more sense to only include <code>i64</code>, <code>u64</code> and <code>f64</code> in the public <code>Number</code> enum.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T23:22:11.447", "Id": "269998", "ParentId": "269990", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T19:44:57.960", "Id": "269990", "Score": "1", "Tags": [ "rust", "enum", "pattern-matching" ], "Title": "PartialOrd of Rust Enums based on encapsulated data" }
269990
<p>In this program I've tried the insertion Sort method to execute</p> <pre><code>#include&lt;stdio.h&gt; int main() { int numbers[25]={21,89,98,76,56,4,345,34,53,56,68,68,68,575,7,4,45,45,35,35,35,2,22,52,235}, temp_str, comp_count=0 ; while(comp_count&lt;25) // To ensure sorting completion { for(int comp_loop=0; comp_loop&lt;24; comp_loop++) // To go for every array element { if(numbers[comp_loop]&gt;numbers[comp_loop+1]) // For comparing two successive elements { // Storing smaller number in separate variable temp_str = numbers[comp_loop+1]; // Promoting value addresses by 1 index for(int pro_loop=comp_loop; pro_loop&gt;=0; pro_loop--) { numbers[pro_loop+1]= numbers[pro_loop]; } // Placing smaller number at the top index of array numbers[0]= temp_str; comp_count=0; // reset to 0 if comparison results to true } else { comp_count++; // to count how many compares are false } } } //Printing the sorted list for(int rslt_loop=0; rslt_loop&lt;25; rslt_loop++) { printf(&quot; %d&quot;,numbers[rslt_loop]); } return 0; } </code></pre> <p>To improve this program I would like to know from you, the possibilities.</p>
[]
[ { "body": "<p>First thoughts: all the code is in <code>main()</code>, but we would like to have a reusable function. I'd create a function that accepts an array and its length:</p>\n<pre><code>void insertion_sort(int arr[], size_t len)\n</code></pre>\n<hr />\n<p>Here is a good demonstration of why <em>one declaration per line</em> is a good style to follow:</p>\n<pre><code>int numbers[25]={ … }, temp_str, comp_count=0 ;\n</code></pre>\n<p>In the full line, <code>temp_str</code> and <code>comp_count</code> disappear off the screen and are harder to find.</p>\n<p>Actually, we don't need <code>temp_str</code> up at this level - it can be local to the <code>if</code> test.</p>\n<hr />\n<p>We have a lot of <code>25</code> (and one <code>24</code>) in the code that makes it hard to change for arrays of different length. Everything that depends on the length should get it from the same place (the parameter to the function, once we create that).</p>\n<p>We can derive the array size from the array itself:</p>\n<pre><code>int numbers[] =\n { 21, 89, 98, 76, 56, 4, 345, 34, 53, 56,\n 68, 68, 68, 575, 7, 4, 45, 45, 35, 35,\n 35, 2, 22, 52, 235 };\nconst size_t length = sizeof numbers / sizeof numbers[0];\n</code></pre>\n<hr />\n<p>The outer loop (<code>while(comp_count&lt;25)</code> wouldn't be necessary if we'd implemented insertion sort correctly. A single pass should sort the array.</p>\n<p>The presence of the outer loop suggests we actually have a form of bubble sort, rather than insertion sort. The problem is that we always move values to the front of the array here, instead of in the correct insert position:</p>\n<pre><code> temp_str = numbers[comp_loop+1];\n for(int pro_loop=comp_loop; pro_loop&gt;=0; pro_loop--)\n {\n numbers[pro_loop+1]= numbers[pro_loop];\n }\n numbers[0]= temp_str;\n</code></pre>\n<p>To fix this, it's worth writing a binary search function that can find the insertion position within the the sorted part of the array.</p>\n<hr />\n<p>The copying loop (indexed using <code>pro_loop</code>) can be replaced with the Standard Library <code>memmove()</code> function (from <code>&lt;string.h&gt;</code>):</p>\n<pre><code> int temp = numbers[comp_loop+1];\n memmove(numbers+1, numbers, (comp_loop + 1) * sizeof *numbers);\n numbers[0]= temp;\n</code></pre>\n<hr />\n<p>We write an unfinished line of output. We should terminate it with a newline. The easiest way is to add</p>\n<pre><code> puts(&quot;&quot;);\n</code></pre>\n<hr />\n<h1>Modified program</h1>\n<p>This is completely re-worked, as suggested above:</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n\n/* return index at which value should be inserted */\nstatic size_t find(const int arr[], size_t len, int value)\n{\n size_t a = 0;\n size_t z = len;\n\n if (value &lt; arr[a]) { return 0; }\n while (a + 1 &lt; z) {\n size_t m = a + (z - a) / 2;\n if (value &lt;= arr[m]) {\n z = m;\n } else {\n a = m;\n }\n }\n return z;\n}\n\nstatic void insertion_sort(int arr[], size_t len)\n{\n for (size_t i = 1; i &lt; len; ++i) {\n int value = arr[i];\n size_t new_pos = find(arr, i, value);\n memmove(arr+new_pos+1, arr+new_pos, (i - new_pos) * (sizeof *arr));\n arr[new_pos]= value;\n }\n}\n\nint main(void)\n{\n int numbers[] =\n { 21, 89, 98, 76, 56, 4, 345, 34, 53, 56,\n 68, 68, 68, 575, 7, 4, 45, 45, 35, 35,\n 35, 2, 22, 52, 235 };\n const size_t length = sizeof numbers / sizeof numbers[0];\n\n insertion_sort(numbers, length);\n\n for (size_t i = 0; i &lt; length; ++i) {\n printf(&quot; %d&quot;, numbers[i]);\n }\n puts(&quot;&quot;);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T11:09:54.487", "Id": "270009", "ParentId": "269991", "Score": "2" } }, { "body": "<p>I don't understand what this is doing.</p>\n<p>I see it takes each successive element and if it's not already greater than the previous last element, I <em>expect</em> to insert it into the correct position: that is the definition of Insertion Sort.</p>\n<p>Instead, it appears to move it all the way to the left, to element zero.</p>\n<p>Then the whole sort is inside another <code>while</code> loop that terminates when it discovers that all the elements are already in order.</p>\n<p>This is <em>not</em> an <em>Insertion Sort</em>. I don't know what it is, or if it has a serious name. It works on the principle of &quot;if it's not sorted, <em>change something</em> and check again&quot;. I suppose you could use an induction proof to show that it always works, and add a counter in your code to find out just how inefficient it is.</p>\n<blockquote>\n<p>To improve this program I would like to know from you, the possibilities.</p>\n</blockquote>\n<p>The most important thing would be to implement an actual Insertion Sort algorithm.</p>\n<p>A guess: you tried to write an insertion sort, and when it didn't work, you added the outer loop and then it got the right answer.</p>\n<p>I think that when learning to write sorts and other algorithms, part of the assignment should be to include counters and the testing should not just verify that it got the right result, but chart the performance. Is the number of comparisons you made O(n log n), O(n²), or something unexpectedly higher like O(n³)?</p>\n<hr />\n<p>Also, if you don't mind answering my little survey: why are you writing in C rather than C++?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T22:00:13.483", "Id": "270204", "ParentId": "269991", "Score": "1" } } ]
{ "AcceptedAnswerId": "270009", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T20:25:18.600", "Id": "269991", "Score": "1", "Tags": [ "c", "insertion-sort" ], "Title": "Sorting numbers using Insertion method" }
269991
<p>My solution for the leet code problem to search an array of ints for duplicate values and return a boolean seems quite efficient (&lt; 90% of submissions runtime). However, I am currently reviewing Data Structures and Algorithms and I wonder if there is a more efficient approach to this, since if my counting is correct my solution will run at O(n) for worst case scenarios. I am still new to C# (I mostly code in js).</p> <pre><code>public bool ContainsDuplicate(int[] nums) { HashSet&lt;int&gt; singles = new HashSet&lt;int&gt;(); for(int i = 0; i &lt; nums.Length;i++) { if (singles.Contains(nums[i])) return true; singles.Add(nums[i]); } return false; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T07:24:56.597", "Id": "532948", "Score": "0", "body": "are you sure it's `O(n)` ? because the `Contains` has an iterator as well which puts it `O(n^2)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T07:27:21.767", "Id": "532949", "Score": "0", "body": "https://stackoverflow.com/a/20507592/648075 (note that this is for an older version of .NET, more recent versions might have implemented this differently.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T07:33:30.080", "Id": "532950", "Score": "0", "body": "@BCdotWEB I just checked it here https://referencesource.microsoft.com/#System.Core/System/Collections/Generic/HashSet.cs,188b8f94f8fc999b (it's still valid on 4.8 .NET) have not validate it on .NET Core yet." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T07:53:12.783", "Id": "532953", "Score": "0", "body": "I think your counting is incorrect, because set containment is usually O(log _n_), and I don't see how C# can outperform that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T12:42:26.420", "Id": "533044", "Score": "0", "body": "From a clean code perspective GroupBy is probably the best approach" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T15:06:27.863", "Id": "533059", "Score": "0", "body": "@iSR5 ah i was unaware of this, I am still very new to C# only been really learning it for about a month. Thank you for that!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T13:18:46.410", "Id": "533116", "Score": "0", "body": "If you're going to continue with C#, learning LINQ can unlock a whole new world. LINQ can do this pretty efficiently code-wise (would have to research BIG O) with something like: `myArray.GroupBy(i => i).Any(g => g.Count() > 1);`" } ]
[ { "body": "<p>This can be slightly optimized by not using <code>Contains()</code> but checking the returned value from <code>Add()</code>. If the item is allready contained in the <code>HashSet&lt;T&gt;</code> calling <code>Add()</code> will return <code>false</code>.</p>\n<pre><code>public bool ContainsDuplicate(int[] nums) {\n HashSet&lt;int&gt; singles = new HashSet&lt;int&gt;();\n for(int i = 0; i &lt; nums.Length;i++)\n {\n if (!singles.Add(nums[i]))\n {\n return true;\n }\n }\n return false;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T20:46:43.060", "Id": "533013", "Score": "1", "body": "How about a one liner: `return new HashSet<int>(nums).Count < nums.Length` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T08:19:22.547", "Id": "533035", "Score": "1", "body": "This would add all items first where in my answer it would return at the first duplicate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T15:05:23.100", "Id": "533058", "Score": "0", "body": "ah I like this thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T20:37:17.993", "Id": "533081", "Score": "0", "body": "@Heslacher yes." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T12:27:56.757", "Id": "270012", "ParentId": "270002", "Score": "5" } } ]
{ "AcceptedAnswerId": "270012", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T00:05:53.633", "Id": "270002", "Score": "4", "Tags": [ "c#", "algorithm", "programming-challenge" ], "Title": "Determine whether an array contains duplicate values" }
270002
<p>I'm new to C#. I have created a form that has 5 text boxes and this function checks to see if every text box has text in the box. If not, then it displays a message box saying &quot;Error (Add Text)&quot;.</p> <p>I wanted to see if there was a way to simplify this, or if this is the best way of completing this task :)</p> <pre><code> private bool ValidInput() { bool isValid = true; //Check Title if (string.IsNullOrEmpty(titleText.Text)) { //Message Box Pass Through Title MB(&quot;The Title can't be blank!&quot;, &quot;Error!&quot;, MessageBoxIcon.Error); titleText.Focus(); isValid = false; } //Check Artist else if (string.IsNullOrEmpty(artistText.Text)) { //Message Box Pass Through Artist MB(&quot;The Artist can't be blank!&quot;, &quot;Error!&quot;, MessageBoxIcon.Error); artistText.Focus(); isValid = false; } //Check Genre else if (string.IsNullOrEmpty(genreText.Text)) { //Message Box Pass Through Genre MB(&quot;The Genre can't be blank!&quot;, &quot;Error!&quot;, MessageBoxIcon.Error); genreText.Focus(); isValid = false; } //Check Year else if (string.IsNullOrEmpty(yearText.Text)) { //Message Box Pass Through Year MB(&quot;The Year can't be blank!&quot;, &quot;Error!&quot;, MessageBoxIcon.Error); yearText.Focus(); isValid = false; } //Check URL else if (string.IsNullOrEmpty(urlText.Text)) { //Message Box Pass Through URl MB(&quot;The URL can't be blank!&quot;, &quot;Error!&quot;, MessageBoxIcon.Error); urlText.Focus(); isValid = false; } return isValid; } </code></pre>
[]
[ { "body": "<p>you can use <code>Dictionary</code> to store the <code>TextBox</code>s and their representive name, then just iterate over them, something like this :</p>\n<pre><code>private bool ValidInput()\n{\n Dictionary&lt;string, TextBox&gt; textBoxes = new Dictionary&lt;string, TextBox&gt;\n {\n { &quot;Title&quot;, titleText },\n { &quot;Artist&quot;, artistText },\n { &quot;Genre&quot;, genreText },\n { &quot;Year&quot; , yearText},\n { &quot;URL&quot;, urlText }\n };\n\n foreach(var item in textBoxes)\n {\n var name = item.Key;\n var textbox = item.Value;\n\n if (string.IsNullOrEmpty(textbox.Text))\n {\n MB($&quot;The {name} can't be blank!&quot;, &quot;Error!&quot;, MessageBoxIcon.Error);\n textbox.Focus();\n return false;\n }\n }\n\n\n return true;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T12:47:26.737", "Id": "270013", "ParentId": "270005", "Score": "1" } }, { "body": "<p>Each <code>Control</code> does have a property called <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.control.tag\" rel=\"nofollow noreferrer\"><code>Tag</code></a>. This can contain/hold any kind of information since its type is <code>object</code>.</p>\n<ol>\n<li>Assign the <code>Title</code>, ... ,<code>Url</code> values to the corresponding TextBox's <code>Tag</code>:</li>\n</ol>\n<pre><code>private readonly TextBox[] textBoxes = new [] { titleText, ... , urlText };\npublic Form1()\n{\n InitializeComponent();\n titleText.Tag = &quot;Title&quot;;\n ...\n urlText.Tag = &quot;URL&quot;;\n}\n</code></pre>\n<ol start=\"2\">\n<li>Rewrite your <code>ValidInput</code> like this:</li>\n</ol>\n<pre><code>var textbox = textBoxes.FirstOrDefault(tb =&gt; string.IsNullOrEmpty(tb.Text));\nif (textbox == null) return true;\n\nMB($&quot;The {textbox.Tag} can't be blank!&quot;, &quot;Error!&quot;, MessageBoxIcon.Error);\ntextbox.Focus();\nreturn false;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T14:21:50.350", "Id": "270015", "ParentId": "270005", "Score": "1" } }, { "body": "<p>Try something like this:</p>\n<pre><code>private bool ValidInput()\n{\n bool isValid = true;\n List&lt;string[]&gt; controlList = new List&lt;string[]&gt;(); //Control name, then display name.\n\n controlList.Add(new[] { &quot;titleText&quot;, &quot;Title&quot;});\n controlList.Add(new[] { &quot;artistText&quot;, &quot;Artist&quot; });\n controlList.Add(new[] { &quot;genreText&quot;, &quot;Genre&quot; });\n controlList.Add(new[] { &quot;yearText&quot;, &quot;Year&quot; });\n controlList.Add(new[] { &quot;urlText&quot;, &quot;URL&quot; });\n\n for (int i = 0; i &lt; controlList.Count; i++)\n {\n if (string.IsNullOrEmpty(this.Controls[controlList[i][0]].Text))\n {\n MB(&quot;The &quot; + controlList[i][1] + &quot; can't be blank!&quot;, &quot;Error!&quot;, MessageBoxIcon.Error);\n this.Controls[controlList[i][0]].Focus();\n isValid = false;\n break;\n }\n }\n return isValid;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T18:00:46.853", "Id": "533282", "Score": "1", "body": "You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T19:02:32.497", "Id": "533367", "Score": "0", "body": "This one works amazingly! Because it allows for more then just TextBox's so if I change one of the box's to a ComboBox it still works :D Thank you!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T16:04:55.970", "Id": "270122", "ParentId": "270005", "Score": "1" } } ]
{ "AcceptedAnswerId": "270122", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T08:02:57.413", "Id": "270005", "Score": "1", "Tags": [ "c#", "beginner", "winforms" ], "Title": "Verify that 5 Textboxes have some content" }
270005
<p>I begin a simple app who manipulates a deck of playing card here is my first attempt at modeling it, what do you think ? What could be a potential caveat for the future with that model ?</p> <p>Thanks :)</p> <pre><code>const ALL_VALUES = [1,2,3,4,5,6,7,8,9,10,11,12,13] as const; type ValueTuple = typeof ALL_VALUES; type Value = ValueTuple[number]; const value_symbols: {[K in Value]: string} = { 1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine', 10: 'Ten', 11: 'Jack', 12: 'Queen', 13: 'King' } enum Suit { Clubs = &quot;Clubs&quot;, Diamonds = &quot;Diamonds&quot;, Hearts = &quot;Hearts&quot;, Spades = &quot;Spades&quot;, } interface Card { value: Value suit: Suit } function printCard(card: Card): string { return `${value_symbols[card.value]} of ${card.suit}\n` } type Deck = Card[] const mkDeck = (): Deck =&gt; { const deck = [] as Card[] for (const s of [Suit.Clubs, Suit.Diamonds, Suit.Hearts, Suit.Spades]){ for (const v of ALL_VALUES){ deck.push({ value: v, suit: s }) } } return deck } const deck = mkDeck() deck.map(c =&gt; console.log(printCard(c))) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T12:10:25.933", "Id": "532975", "Score": "0", "body": "You shouldn't use a type assertion to force a value to a const" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T22:45:56.573", "Id": "533019", "Score": "0", "body": "Ace can be both high and low, depending on which game you play. Have you considered that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T11:44:07.047", "Id": "533500", "Score": "0", "body": "Consider using `as const` assertion for `value_symbols` and removing explicit type `{[K in Value]: string}`" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T11:47:34.270", "Id": "270010", "Score": "0", "Tags": [ "typescript" ], "Title": "Simple Deck of playing cards in typescript" }
270010
<p>I'm working with an API that for some strange reason returns star ratings as words, like <code>FIVE,FOUR,THREE,TWO,ONE</code>. As far as I can see, there's no way to just get the numerical rating, so I have to locally convert these into numbers.</p> <p>I went with a <code>switch</code> statement, but honestly whenever I see myself using <code>switch</code> cases I feel like there must be a better way. It's obviously very readable and clear, which is good, but I can't help but wonder, there must be a better way of dealing with something like this right?</p> <p>Current code looks like this</p> <pre class="lang-javascript prettyprint-override"><code>function wordToNumber(word) { switch (word) { case &quot;FIVE&quot;: return 5; case &quot;FOUR&quot;: return 4; case &quot;THREE&quot;: return 3; case &quot;TWO&quot;: return 2; case &quot;ONE&quot;: return 1; default: return &quot;N/A&quot;; } } </code></pre> <p>I'm probably overthinking this honestly, but I just always feel a bit unsure when I reach for switch statements.</p> <p>EDIT:</p> <p>Some of the answers rightfully point out that I'm returning integers in the cases, but then in the default I'm returning a string. In my particular usecase it's fine, since this function is returning it directly into a render function that will convert the ints into strings anyway, and the numbers get used nowhere else either.</p> <p>As such though, I've reformatted it to the below instead, and I instead check whether it returned <code>-1</code> and then print out a different string based on that instead.</p> <pre class="lang-javascript prettyprint-override"><code>default: return -1; </code></pre>
[]
[ { "body": "<p>I'm not a Javascript programmer, but it looks strange that we return a different <em>type</em> of result for the <code>default</code> case. Can't we return a number (e.g. <code>0</code>)? Or a NaN? Or perhaps even throw an exception.</p>\n<p>I guess that without more context of how the function is used, it's hard to say what the default return <em>should</em> be.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T16:02:11.417", "Id": "532985", "Score": "0", "body": "Refer to my comment on @s.alem's answer, but basically this function directly returns the value into text that is rendered to the user in their browser. As suich, when there's no score I want to let them know that particular entry isn't applicable, so I return a string that's saying \"Yeah this one doesn't exist\", the scores aren't used anywhere else so they could be strings as well." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T15:55:51.583", "Id": "270017", "ParentId": "270016", "Score": "2" } }, { "body": "<p>You could use a map or object, but it would be just another way of doing it and I wouldn't call it better tbh.</p>\n<p>One thing you can change is the <code>default</code> block. All the other cases return a number while <code>default</code> returns a string. Depending on the use case, you can either return a value like <code>-1</code>, <code>NaN</code>, <code>undefined</code>, or even throw an exception <code>throw 'Not a valid value!'</code>.</p>\n<p>Also you can make it easily case agnostic:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>function wordToNumber(word) {\n upperCaseWord = word?.toUpperCase();\n switch (upperCaseWord) {\n case &quot;FIVE&quot;:\n return 5;\n case &quot;FOUR&quot;:\n return 4;\n case &quot;THREE&quot;:\n return 3;\n case &quot;TWO&quot;:\n return 2;\n case &quot;ONE&quot;:\n return 1;\n default:\n return NaN;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T15:58:39.217", "Id": "532984", "Score": "0", "body": "I''m using this in a Frontend app that's displaying the score to the user. As such, when there's no Score (the API returns a null field when there's no score), I just return `N/A` to indicate it's not applicable. Agreed that I should rethink how I handle that though, it looks fine in context but it's not the best way of handling things" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T15:55:58.700", "Id": "270018", "ParentId": "270016", "Score": "3" } }, { "body": "<h2>Complexity and performance</h2>\n<p>There are many ways to write this type of function and the best is determined by the number of input states. In your example you have 6 different input states 1-5 and NaN.</p>\n<h2>Complexity</h2>\n<p>The least number of steps to parse the string is 1 and the worst requires 6 steps. The average time, assuming equal distribution of input, is (1 + 2 + 3 + 4 + 5 + 6) / 6 = 21/6 = 3.5</p>\n<p>However you can reduce the number of steps required using a hash map.</p>\n<p>The input <code>word</code> is first converted to a hash value (considered as one step and doen by the JS engine). The hash value is then used to locate the return value. The examples below have an average number of steps = 1</p>\n<pre><code>const STR_TO_NUM = {one: 1, two: 2, three: 3, four: 4, five: 5};\nconst wordToNumber = word =&gt; Number(STR_TO_NUM[word.toLowerCase()]);\n</code></pre>\n<p>or</p>\n<pre><code>const STR_TO_NUM = new Map([[&quot;one&quot;, 1], [&quot;two&quot;, 2], [&quot;three&quot;, 3], [&quot;four&quot;, 4], [&quot;five&quot;: 5]]);\nconst wordToNumber = word =&gt; Number(STR_TO_NUM.get(word.toLowerCase()));\n</code></pre>\n<p><em><sub><sub> <strong>Note:</strong> Assumes word is a string </sub></sub></em></p>\n<h2>Performance</h2>\n<p>The above function requires only 1 step, however it does not mean it will be quicker. The step of converting to a hash can take much more time than the step that compares a string to another string. In your case where there are only 6 states it will be quicker to use the original <code>switch</code>, or conditional search.</p>\n<pre><code>function wordToNumber(word) { /* Note assumes word is a string */\n switch (word.toUpperCase()) {\n case &quot;FIVE&quot;: return 5;\n case &quot;FOUR&quot;: return 4;\n case &quot;THREE&quot;: return 3;\n case &quot;TWO&quot;: return 2;\n case &quot;ONE&quot;: return 1;\n default: return NaN;\n }\n}\n</code></pre>\n<p>or</p>\n<pre><code>function wordToNumber(word) { /* Note assumes word is a string */\n word = word.toUpperCase();\n if (word === &quot;FIVE&quot;) { return 5; }\n if (word === &quot;FOUR&quot;) { return 4; }\n if (word === &quot;THREE&quot;) { return 3; }\n if (word === &quot;TWO&quot;) { return 2; }\n if (word === &quot;ONE&quot;) { return 1; }\n return NaN;\n}\n</code></pre>\n<p>As the number of input states grows the cost of finding the hash value becomes negligible compared to the many conditions to test. If you had 20 input states it would be quicker to use a hash map.</p>\n<h2>Aiming for performance</h2>\n<p>As the function is not a generic solution. ie the number of states is constant you should aim for the best performance, not the least complexity</p>\n<p>You could exploit the uniqueness and similarity of the inputs</p>\n<pre><code>const wordToNumber = word =&gt; { /* Note assumes word is a string */\n const w = word.toLowerCase(word);\n if (w[0] === &quot;t&quot;) { return w[1] === &quot;w&quot; ? 2 : 3; }\n if (w[0] === &quot;f&quot;) { return w[1] === &quot;o&quot; ? 4 : 5; } ​\n ​return w[0] === &quot;o&quot; ? 1 : NaN;\n}\n\n</code></pre>\n<p>Now the average number of steps is (3 + 2 + 2 + 3 + 3 + 3) / 6 = 16 / 6 = 2.666...</p>\n<p>Note that if the input range was 1 - 1000 the above approach will be optimal as you can break the string into parts and parse the parts, rather than have 1000 items in a hash map or 1000 conditional statements.</p>\n<p>If you know the odds of each input you can also change the order of the steps to favor the most likely inputs. If high values are more likely (eg <code>&quot;five&quot;</code> is 10 times more likely than <code>&quot;one&quot;</code>) you would write the function as</p>\n<pre><code>const wordToNumber = word =&gt; { /* Note assumes word is a string */\n const w = word.toLowerCase(word);\n if (w[0] === &quot;f&quot;) { return w[1] === &quot;o&quot; ? 4 : 5; } ​\n if (w[0] === &quot;t&quot;) { return w[1] === &quot;w&quot; ? 2 : 3; }\n ​return w[0] === &quot;o&quot; ? 1 : NaN;\n}\n</code></pre>\n<p>Note that there are more optimizations possible but for such a small input set it may not be worth the effort unless you need to call the function millions of times a second.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T18:49:44.070", "Id": "532996", "Score": "0", "body": "Amazing. This should be the accepted answer. How about if we switch case on `word[1]` since it is distinct in every word in the set?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T19:26:52.177", "Id": "532999", "Score": "2", "body": "@s.alem If you switch on the second character it would be best to switch on the character code as JS handles numbers far quicker than characters eg `switch(word.charCodeAt(1)) { case 110: return 1; ` where 110 is char code for `n`. If you know that the string only contains a-zA-Z chars you can combine the case conversion by adding the 6th bit to convert to lower. Eg `switch(word.charCodeAt(1) | 0b100000) { case 110: return 1; /*etc*/` Will convert A-Z to lower case character code so that case 110 will be true for `\"N\"` and `\"n\"`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T21:36:19.877", "Id": "533016", "Score": "0", "body": "Thanks for explaining it. Maybe you can add this comment to the answer. Just out of pure curiosity, while staying in JS, what is the max optimization you can think for this case?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T17:02:56.570", "Id": "270021", "ParentId": "270016", "Score": "6" } }, { "body": "<p>Super short review,</p>\n<ul>\n<li>as others have said, a function should try to be consistent in the type of data it returns</li>\n<li>your <code>case</code> statement can be replaced with a clever data structure</li>\n<li>I prefer <code>&lt;verb&gt;&lt;subject&gt;</code> for function names, so <code>convertWordToNumber</code></li>\n</ul>\n<p>Personally, after seeing you now return -1 for non found values, I would write this as</p>\n<pre><code>function convertStarCount(starCount) {\n const integers = [&quot;ZERO&quot;, &quot;ONE&quot;, &quot;TWO&quot;, &quot;THREE&quot;, &quot;FOUR&quot;, &quot;FIVE&quot;];\n return integers.indexOf(starCount);\n}\n</code></pre>\n<p>I assumed something can get zero stars ;)</p>\n<p>And I trusted that the API you use will always send upper case strings.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T12:27:31.667", "Id": "270114", "ParentId": "270016", "Score": "0" } } ]
{ "AcceptedAnswerId": "270021", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T15:31:31.657", "Id": "270016", "Score": "3", "Tags": [ "javascript", "parsing", "converting" ], "Title": "Convert number 1-5 from its spelt-out form" }
270016
<p><strong>What the program does:</strong> I have made a program that simulates a ball in an area made of triangles and many optimizations because it's for high-performance ball path simulation (technically ball path prediction).</p> <p><strong>Vec3 and Ball definitions:</strong></p> <pre class="lang-rust prettyprint-override"><code>#[derive(Clone, Copy, Debug)] pub struct Vec3 { pub x: f32, pub y: f32, pub z: f32, } #[derive(Clone, Copy, Debug)] pub struct Ball { pub time: f32, pub location: Vec3, pub velocity: Vec3, pub angular_velocity: Vec3, pub radius: f32, pub collision_radius: f32, pub moi: f32, } </code></pre> <p><strong>How it works right now:</strong> I have a function that takes all of the ball info/game info as well as the desired time to simulate the ball for. It converts the time into the number of game ticks that need to be run to actually simulate the ball for that time. It runs a loop for that number of ticks. For each tick, it calls another function, <code>step(game: &amp;mut Game, dt: f32)</code>. This runs all of the physics that would advance the game that one tick (CPU only, no graphical output whatsoever or GPU involvement.) I then throw the ball data into a <code>Box</code> and throw that into a <code>Vec</code>. This is so, when the <code>Vec</code> is returned, I basically have the predicted path of the ball, from game tick to game tick.</p> <p><strong>The function:</strong></p> <pre class="lang-rust prettyprint-override"><code>pub fn get_ball_prediction_struct_for_time(game: &amp;mut Game, time: &amp;f32) -&gt; BallPrediction { let num_slices = (time / Ball::SIMULATION_DT).round() as usize; let mut slices = Vec::with_capacity(num_slices); for _ in 0..num_slices { Ball::step(game, Ball::SIMULATION_DT); slices.push(Box::new(game.ball)); } BallPrediction { slices, num_slices, } } </code></pre> <p><strong>My question:</strong> Is putting the ball into a box and putting that into a <code>Vec</code> the best, most efficient way to do this? Is it possible for me to rather clone the balls into the stack (I believe <code>Box</code> stores it on the heap?) but then <code>Vec</code> stores stuff on the heap anyway, so does that even matter? How can I minimize moving all the data around?</p> <p>I'm also new-er to Rust, so insight into Rust and its conventions is appreciated! I can share as might insight to the program as needed, this is an open-source hobby project of mine.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T19:35:56.833", "Id": "533000", "Score": "1", "body": "There isn't enough information here to determine “most efficient”. We'll need to see the definition of `Ball` at least; preferably a complete runnable program. It's very likely that you should not be trying to “minimize moving”, and the `Box` is doing you no good, but more details of your data will help determine that. (And in the end, the only way to be _sure_ about performance is to benchmark, not to read the code.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T19:46:03.833", "Id": "533001", "Score": "0", "body": "@KevinReid Sure! Here's the github repo with tests - https://github.com/VirxEC/rl_ball_sym - it's also a crate on crates.io. The closest test to that is `fast_predict_soccar`, where you can really just swap out the functions (line 362) and put in a value for `time`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T19:48:13.660", "Id": "533002", "Score": "0", "body": "I also added type definitions for Ball (and Vec3 in that.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T20:02:18.057", "Id": "533008", "Score": "0", "body": "I actually just added a test called `fast_predict_custom_soccar`, it's in the repo for anyone to run." } ]
[ { "body": "<p>welcome to the Rust community.</p>\n<p>A Vec is a continuous slice of heap memory. A Box is a fixed-size portion of heap memory (except for boxed DSTs). A Box within a Vec is entirely unnecessary (except in extreme cases when you are moving around huge structs). Putting a Box inside a Vec is like wrapping your items in two layers of packaging. This overhead is quite small, though: one heap allocation per item.</p>\n<p>Don't worry about copying things onto the stack. The stack is efficient and Rust/LLVM will optimize moves of your values.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T15:03:29.273", "Id": "270465", "ParentId": "270019", "Score": "1" } } ]
{ "AcceptedAnswerId": "270465", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T16:35:33.963", "Id": "270019", "Score": "1", "Tags": [ "rust", "simulation" ], "Title": "Quickly update, clone, and iterate ball simulation" }
270019
<p>I got this HW question from my freshman year at college - &quot;Create a python function to check whether a string containing only lowercase letters has any repetition in it&quot;.</p> <p>So, I did it a few ways:</p> <ol> <li><p>Brute forced it by checking if a character in the string was present in the substring to the right of it using a nested <code>for</code> loop.</p> </li> <li><p>Created a list and stored every new character in it. Looped through each character in the string and checked if a character was in the list. If so, the string wasn't unique.</p> </li> </ol> <p>Both of these work but I'm looking for another solution. I came up with the following. Can you please tell me how inefficient this one would be?</p> <pre><code>def isUnique(string): ascii_product = 1 for chr in string: ascii_prime = 2 ** (ord(chr) - 95) - 1 if ascii_product % ascii_prime == 0: return False ascii_product *= ascii_prime else: return True </code></pre> <p>If the code is too horrible to understand, here's what I'm trying to do. I loop through each character in the string and with its ASCII value, I create a unique Mersenne prime number associated with it. I then check if the product is divisible by the prime. If it is, the string is not unique. Otherwise, I multiply the product by the prime.</p> <p>This code works as well but I wanted to know how bad it is in terms of efficiency. Also, what's the best way of doing this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T10:46:04.313", "Id": "533105", "Score": "7", "body": "\"I create a unique Mersenne prime number\". No you don't. ;) It's a creative idea, though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T03:29:44.753", "Id": "533237", "Score": "0", "body": "I got the logic wrong too... probably should have tried a few more values before thinking it worked" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T08:15:41.730", "Id": "533250", "Score": "0", "body": "I think that if you indeed used prime numbers and not just `2**i - 1`, the code would work. It would become really slow, e.g. with a long string of unique unicode chars, but it should work as far as I can tell." } ]
[ { "body": "<p>You should use <a href=\"https://docs.python.org/3/tutorial/datastructures.html#sets\" rel=\"noreferrer\">sets</a> which are an unordered collection <em>without duplicates</em>. Sets are <a href=\"https://en.wikipedia.org/wiki/Set_(abstract_data_type)\" rel=\"noreferrer\">a fundamental data structure</a> found in many programming languages.</p>\n<p>You should also strive to be a bit more Pythonic. A more natural solution would be as follows:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def is_unique(string: str) -&gt; bool:\n return len(string) == len(set(string))\n</code></pre>\n<p>I have also used <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"noreferrer\">type hints</a> which can also be omitted. Here, they convey that the argument to the function should be a string and return value a boolean. You can learn about later if you want to get more serious with Python.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T18:09:12.420", "Id": "532988", "Score": "0", "body": "A simple improvement to make this a valid answer would be at least to explain why you've changed `isUnique` to `is_unique`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T18:30:15.527", "Id": "532990", "Score": "0", "body": "This is a cool solution. Thanks for sharing. Quick side question, how do I write more Pythonic code? Will reading other people's code help?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T18:35:10.883", "Id": "532991", "Score": "0", "body": "@AJNeufeld Thanks for the tip, I added some clarification. I hope someone else can chime in with a more deeper review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T18:36:22.770", "Id": "532992", "Score": "0", "body": "@1d10t There are many ways in which you can get better. Reading other people's code, reading good books or other material, writing code & getting feedback... all of that should work more or less." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T18:45:15.040", "Id": "532993", "Score": "0", "body": "@Juho thank you for helping me out. I'm guessing this is probably the most atrocious code you've seen in your life. You think I got any chance as a programmer?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T18:46:49.937", "Id": "532994", "Score": "0", "body": "@1d10t Absolutely - no one's perfect when starting out. If you like it, just keep practicing and feel free to ask more questions here too :-) Good luck!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T18:49:04.287", "Id": "532995", "Score": "2", "body": "@1d10t \"Pythonic\" doesn't have a standardized meaning. However code which follow's [PEP 8](https://www.python.org/dev/peps/pep-0008/) tends to be more Pythonic than other code. Additionally things like Ned Batchelder's \"Loop Like A Native\" advice also makes code more Pythonic, however the idioms are common in other languages now too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T20:37:51.527", "Id": "533227", "Score": "0", "body": "This may be inefficient if `str` contains the full works of Shakespeare or something large. An optimization may be `len(string) < 26 && len(string) == len(set(string))` If then len is greater than the number of available characters then they can't be unique. Assumes: Standard ASCII 0->127" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T17:44:26.270", "Id": "270024", "ParentId": "270022", "Score": "15" } }, { "body": "<h1>Naming</h1>\n<p><a href=\"https://pep8.org/\" rel=\"nofollow noreferrer\">PEP 8: The Style Guide for Python Code</a> has recommendations all Python programs should follow. One of these is function names should be in <code>snake_case</code>. As such, <code>isUnique</code> should actually be named <code>is_unique</code>.</p>\n<h1>Don't shadow built-in function names</h1>\n<p><code>chr</code> is a built-in function. For example, <code>chr(97)</code> returns <code>'a'</code>.</p>\n<p>After executing <code>for chr in string</code>, you no longer have access to the <code>chr</code> function in that scope. <code>ch</code> is commonly used as a variable for extracting characters from a string.</p>\n<h1>for-else</h1>\n<p>The <code>for ... else: ...</code> construct is for use when you use <code>break</code> to terminate a loop early if something is found, executing the <code>else:</code> portion only if the search failed to find a result.</p>\n<p>In this particular case, you are not using <code>break</code>; rather you <code>return</code> from inside the loop. In such as situation, <code>else:</code> is unnecessary, and can cause confusion. Consider:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def example(container):\n for item in container:\n if complicated_test(item):\n return True\n else:\n print(&quot;Point A&quot;)\n print(&quot;Point B&quot;)\n return False\n</code></pre>\n<p>There is no way <code>&quot;Point B&quot;</code> can be reached without also reaching <code>&quot;Point A&quot;</code> first. The <code>else:</code> is an unnecessary control block.</p>\n<h1>Magic numbers</h1>\n<p>What is <code>95</code>? Where did it come from? It is a magic number. My first guess was that it is the ordinal of <code>'a'</code>, but that turned out to be wrong.</p>\n<p>The constant deserves a name. <code>LOWERCASE_TO_MERSENNE_OFFSET</code> comes to mind as a possibility, though it might be a bit long. You might even want to define it with an expression, to help readers see where it comes from:</p>\n<pre class=\"lang-py prettyprint-override\"><code>LOWERCASE_TO_MERSENNE_OFFSET = ord('a') - 2\n</code></pre>\n<h1>Binary numbers</h1>\n<p>You are <em>trying</em> to use prime numbers to store flags in a single integer, to indicate whether or not a lowercase letter has been seen. Using bits to store these flags in a single integer is much simpler.</p>\n<p><span class=\"math-container\">\\$2^0\\$</span> would be the <code>'a'</code> flag, <span class=\"math-container\">\\$2^1\\$</span> would be the <code>'b'</code> flag, ... <span class=\"math-container\">\\$2^{25}\\$</span> would be the <code>'z'</code> flag</p>\n<pre class=\"lang-py prettyprint-override\"><code>def is_unique(string: str) -&gt; bool:\n &quot;&quot;&quot;Determine if a string contains unique lowercase letters\n\n Returns `True` if all lowercase letters are unique, `False` otherwise.\n\n Calling the function with `string` containing anything other than\n lowercase letters results in undefined behaviour.\n &quot;&quot;&quot;\n\n letter_flags = 0\n\n first = ord('a')\n for ch in string:\n flag = 1 &lt;&lt; (ord(ch) - first)\n if letter_flags &amp; flag:\n return False\n letter_flags |= flag\n\n return True\n</code></pre>\n<p>Since larger integers in Python are stored as objects on the heap, and are immutable, bit manipulation requires creating a new object when the bits of the integer are changed. As such, bit manipulation in Python is not as fast as in languages like C, C++, or Java.</p>\n<p>There is a <a href=\"https://pypi.org/project/bitarray/\" rel=\"nofollow noreferrer\"><code>bitarray</code></a> package which can be installed (<code>pip install bitarray</code>) which may be used to create mutable bit arrays. Using a <code>bitarray</code> instead of an integer will be much faster, yet still keeps the memory footprint of the application near its absolute minimum. Since a <code>bitarray</code> can be thought of as the bits of an integer, this can still be thought of as storing your “seen flags” in a single integer.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from bitarray import bitarray\n\ndef is_unique(string: str) -&gt; bool:\n &quot;&quot;&quot;Determine if a string contains unique lowercase letters\n\n Returns `True` if all lowercase letters are unique, `False` otherwise.\n\n Calling the function with `string` containing anything other than\n lowercase letters results in undefined behaviour.\n &quot;&quot;&quot;\n\n letter_flags = bitarray(26)\n letter_flags.setall(False)\n\n first = ord('a')\n for ch in string:\n flag = ord(ch) - first\n if letter_flags[flag]:\n return False\n letter_flags[flag] = True\n\n return True\n</code></pre>\n<p>Finally, bit manipulation will always incur an overhead over direct indexing. Using a <code>bytearray(26)</code> object to hold the twenty-six flags is likely faster than using a <code>bitarray</code>. It is no longer meeting your implied goal of storing the flags inside a single integer. It requires perhaps 22 additional bytes of memory, but does not require installation of an external package.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def is_unique(string: str) -&gt; bool:\n &quot;&quot;&quot;Determine if a string contains unique lowercase letters\n\n Returns `True` if all lowercase letters are unique, `False` otherwise.\n\n Calling the function with `string` containing anything other than\n lowercase letters results in undefined behaviour.\n &quot;&quot;&quot;\n\n letter_flags = bytearray(26)\n\n first = ord('a')\n for ch in string:\n flag = ord(ch) - first\n if letter_flags[flag]:\n return False\n letter_flags[flag] = 1\n\n return True\n</code></pre>\n<h1>Set</h1>\n<p><a href=\"https://codereview.stackexchange.com/a/270024/100620\">Juho's set solution</a> is a simple 1-line solution, but it is <span class=\"math-container\">\\$O(N)\\$</span> in time. With certain inputs, it can take a very long time, failing programming challenges.</p>\n<p>Eg) <code>is_unique('a' * 1_000_000_000)</code> calls the function with a string 1 billion characters long, and then iterates over the entire string to build the set. If you want to use this type of solution, you should include a fast fail to catch these types of degenerate cases:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from string import ascii_lowercase\n\ndef is_unique(string: str) -&gt; bool:\n # Pigeon hole principle: a string longer than 26 characters must have duplicates!\n if len(string) &gt; len(ascii_lowercase):\n return False\n\n return len(string) == len(set(string))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T04:52:28.323", "Id": "533028", "Score": "3", "body": "This site is amazing! I mean, this answer is extremely detailed and I learned a lot. Thank you so much for taking the time to do this. Is it ok to change the accepted answer? Even though I love Juho's solution, this answer is technically more of a review. And one last question - is it better to go with better efficiency or better readability? For example, lets imagine the pigeon hole principle wasn't applicable here and we had to go all the way to 1,000,000,000. So, in production code (not a competitive programming contest), would I use the set solution or the bit solution?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T05:21:47.560", "Id": "533029", "Score": "0", "body": "From [What does it mean when an answer is \"accepted\"?](https://codereview.stackexchange.com/help/accepted-answer): “_Accepting an answer is not meant to be a definitive and final statement indicating that the question has now been answered perfectly. It simply means that the author received an answer that worked for them personally. Not every user comes back to accept an answer, and of those who do, they might not change the accepted answer even if a newer, better answer comes along later._”. a) you love Juho’s solution, so clearly it worked for you, b) you don’t need to accept a newer one" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T05:27:49.037", "Id": "533030", "Score": "1", "body": "Different problems have different solutions. Given up to a billion integers from 1 to a billion, I’d use a `bitarray` to hold flags. Given a list of a few thousand integers from 1 to a billion, a set is better, because most of the range is unused. Given random words, a set is really the only viable solution, since there is no obvious unique mapping of words to numbers. Although the problems are similar, the details can change the preferred solution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T05:52:45.707", "Id": "533032", "Score": "3", "body": "Re: efficiency -vs- readability: “code is usually written once and read many times”, and “premature optimization is the root of all evil”. Write clear, understandable code first. Only if it is not fast enough: profile it, and optimize only the code where the most time is spent. “90% of the time is usually spent in 10% of the code”" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T21:16:48.873", "Id": "533152", "Score": "0", "body": "@1d10t: ORing into an integer is just manually implementing a `set` data structure, plus an early-out on the first duplicate. It's very good for efficiency when your inputs are in a small range. (Although Python interpreter overhead eats up some of the benefit vs. calling one built-in Python function, if you're using the normal CPython implementation. Cython would be even better; it uses an optimizing compiler to compile to native machine code. A C version of this would be excellent.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T23:06:05.710", "Id": "533161", "Score": "0", "body": "@1d10t: For reference, a C version looks like this: https://godbolt.org/z/M37zYsGEK. It compiles fairly efficiently, much better than indexing memory, although hand-written asm could do even better. I used `str[i] % 32` as the shift-count instead of `str[i] - 'a'` because compilers know that shifts on many ISAs (including x86) already mask the shift count to 0..31 for free. Fun fact: this would make it treat upper and lower case characters the same, since they have the same alignment relative to a 32-position boundary in their ASCII codes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T01:24:14.277", "Id": "533162", "Score": "3", "body": "@idmean I disagree. I think my algorithm is actually \\$O(1)\\$. Sure the number of iterations initially increases by 1 for every additional character, but cannot exceed 26, which is a constant. Given a valid input string of 100, 1000, or a billion characters, it will execute in approximately the same time: 26 iterations or less." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T08:40:50.730", "Id": "533175", "Score": "0", "body": "@AJNeufeld Yes, you're right. I confused something when I wrote the initial comment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T17:19:47.997", "Id": "533215", "Score": "0", "body": "Is your `bitarray` solution faster than your `int` solution with `|`? You make it sound like it is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T19:36:03.800", "Id": "533224", "Score": "0", "body": "Could also do `return 26 >= len(string) == len(set(string))`. I don't think `len(ascii_lowercase)` is necessary if you have that pigeonhole comment mentioning 26 letters. Thanks to that comment, 26 is not a magic number anymore." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T19:24:44.863", "Id": "270026", "ParentId": "270022", "Score": "26" } }, { "body": "<p>What is the meaning of “repetition” for this question? Same character used more than once or the same character used more than once sequentially?</p>\n<p>Not that it matters that much as they can be treated almost the same.\nIf the former, then checking if the string is longer than 26 characters (trivially true) and if not sorting the string, puts us into a position to look for the later (sequential appearance).</p>\n<p>Sequential appearance is best handled by simply looping over all the characters in the string and returning true when we find a duplicate…</p>\n<pre class=\"lang-py prettyprint-override\"><code>def is_unique_sq(string):\n if len(string)&gt;26:\n return True\n prior_char = ''\n for current_char in sorted(string):\n if prior_char == current_char:\n return True\n prior_char=current_char\n return False\n\nprint(is_unique_sq(&quot;abcdc&quot;))\n</code></pre>\n<p>While this could be solved in other ways (set, regexs), this is a straightforward solution so I wouldn’t consider it either over-engineering or premature optimization.</p>\n<p>As for your solution, you are basically trying to use an integer as a dictionary, better to simply use a dictionary. For instance if your requirements had been: given a string with both upper and lower case characters, determine if any of the lower case characters appear more than once. Then using a dictionary would work. Some might say you were using it as an array, and if that is how you think of it, then use an array.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T03:34:34.860", "Id": "533238", "Score": "0", "body": "I apologise for the late reply, but it's for same character used more than once anywhere. Thanks for sharing this solution though, it just so happens to be one of the next HW questions :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-21T17:21:35.857", "Id": "533631", "Score": "0", "body": "@1d10t: here’s my own late reply, changing to anywhere is trivial, and won’t have a significant impact because the input will be extremely short." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T14:36:14.130", "Id": "270047", "ParentId": "270022", "Score": "5" } }, { "body": "<p><strong>Your solution is wrong.</strong></p>\n<p>For example, for <code>isUnique('ca')</code> you compute <code>False</code>. Because for <code>'c'</code> you compute <span class=\"math-container\">\\$2^{4}-1 = 15\\$</span>, which is <strong>not</strong> a prime number. It's divisible by <span class=\"math-container\">\\$2^{2}-1 = 3\\$</span> which you compute for <code>'a'</code>.</p>\n<p>If you want a simple formula for computing primes for the alphabet, I suggest <a href=\"https://mathworld.wolfram.com/Prime-GeneratingPolynomial.html\" rel=\"nofollow noreferrer\">Euler's</a> <span class=\"math-container\">\\$n^2-n+41\\$</span> (also see comments below).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T12:24:59.157", "Id": "533186", "Score": "0", "body": "Typo: \\$`` n^2 - n + 41 \". \\$" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T13:58:04.723", "Id": "533204", "Score": "0", "body": "@Nat If you think MathWorld made a typo, tell them, and if they fix it, let me know and I'll update my answer accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T18:42:32.797", "Id": "533221", "Score": "1", "body": "[Here](https://scholarlycommons.pacific.edu/euler-works/461/) ([scanned PDF](https://scholarlycommons.pacific.edu/cgi/viewcontent.cgi?article=1460&context=euler-works); [translated PDF](https://scholarlycommons.pacific.edu/cgi/viewcontent.cgi?filename=0&article=1460&context=euler-works&type=additional)) shows Euler as giving \\$ `` n^2 - n + 41 \" .\\$" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T18:49:26.683", "Id": "533222", "Score": "0", "body": "Admittedly that Mathworld page is a bit confusing. It claims that Legendre, not Euler, gave \\$ `` n^2 - n + 41 \" ,\\$ despite that PDF that seems to show Euler giving it. But then that same Mathworld page has a table in which it credits Euler with \\$ `` n^2 - n + 41 \" .\\$" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T19:12:45.803", "Id": "533223", "Score": "1", "body": "@Nat Thanks. I think in the table they *standardized* the polynomials so that they generate primes *\"when values from 0 to n are plugged in\"*, as they say. So I wouldn't use that table as evidence. But when they initially wrote \\$n^2+n+41\\$, I think they reference the letter you showed, in which Euler wrote \\$41-x+xx\\$. Since \\$n^2-n+41\\$ is closer to that, I switched to that now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T03:24:21.670", "Id": "533236", "Score": "0", "body": "Looks like I messed up the logic too and I was worried about efficiency! Thanks for sharing Euler's formula" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T21:10:38.133", "Id": "270054", "ParentId": "270022", "Score": "10" } }, { "body": "<blockquote>\n<p>This code works as well but I wanted to know how bad it is in terms of efficiency.</p>\n</blockquote>\n<p>Try it with the Python <a href=\"https://docs.python.org/3/library/timeit.html\" rel=\"nofollow noreferrer\">timeit</a> module to measure the runtime of small code samples. It defaults to running the code a million times and tells you how long it takes. I put the string <code>'mchlrivughvm'</code> which is 12 characters and has a dupe after 10 characters into some of the code on this page and got:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>timeit (seconds)</th>\n<th>code</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>6.1</td>\n<td>OP's prime code isUnique</td>\n</tr>\n<tr>\n<td>2.8</td>\n<td>AJNeufeld's bit flag code is_unique (surprisingly slow to me)</td>\n</tr>\n<tr>\n<td>2.7</td>\n<td>A for loop calling string.count(c) on every char in the string.</td>\n</tr>\n<tr>\n<td>1.6</td>\n<td>OP's O(N^2) nested loop</td>\n</tr>\n<tr>\n<td>0.9</td>\n<td>jmoreno's conecutive dupes check is_unique_sq</td>\n</tr>\n<tr>\n<td>0.6</td>\n<td>len(s) != len(set(s))</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>The problem with talking about the 'best way' of doing it in Python is that if you want shortest runtime, Python isn't the best language to do that. &quot;Best&quot; in Python is more likely to mean &quot;clear and readable, performant enough not to be the bottleneck&quot;.</p>\n<p>Code running down in the CPython runtime can be faster, even if it's algorithmically worse. Building a <code>set()</code> involves more conceptual things happening, but doing those in C is faster than doing &quot;less work&quot; of a single loop and using bit flags in Python. On small strings, your O(N^2) nested loop runs faster than the O(N) bit test. And as we've seen there won't be long strings because you can short-circuit any strings longer than 26 as they must contain duplicates.</p>\n<hr />\n<blockquote>\n<p>how bad it is in terms of efficiency.</p>\n</blockquote>\n<p>Take 2; how big might <code>ascii_product *= ascii_prime</code> get?</p>\n<p>I think it could get to around <code>2**27 * 2**26 * 2**25 ... * 2**2</code> [1] which is something like this number:</p>\n<pre><code>4586997231980143023221641790604173881593129978336562247475177678773845752176969616140037106220251373109248\n</code></pre>\n<p>Compared with a typical max value of a 64bit signed integer:</p>\n<pre><code>9223372036854775807\n</code></pre>\n<p>As numbers go above what can fit in a 64 bit integer, Python will switch from hardware math to software math written in C which has huge overhead. Huge is relative, it's still fast enough to be useful on modern computers but compared to the processor working on native ints, it's many many times slower.</p>\n<p>[1] I used 27-2 instead of 25-0 because you can't really have <code>*0</code> or <code>*1</code> in there. Multiplying by zero will reset, multiplying by one will not help.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T16:47:52.740", "Id": "533212", "Score": "0", "body": "I’ve added an explanation why bit manipulation is slow in Python, and added an optimized implementation using `bitarray` you might wish to add to your test results." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T03:40:12.670", "Id": "533239", "Score": "0", "body": "Timeit was very useful, thank you. This is one module I'm keeping for the rest of my life!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T05:11:42.053", "Id": "533240", "Score": "0", "body": "@AJNeufeld I tried; `bitarray` doesn't install because I don't have the right Visual C++ runtime versions, and your bytes() one does not run, throwing `letter_flags[flag] = 1 TypeError: 'bytes' object does not support item assignment`. (Using a list instead comes out about 1.9s)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T06:37:48.137", "Id": "533243", "Score": "0", "body": "You can download precompiled bitarray wheels from https://www.lfd.uci.edu/~gohlke/pythonlibs/#bitarray Agh! I meant `bytearray`, not the read-only `bytes` object. Fixing..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T13:54:16.560", "Id": "533262", "Score": "0", "body": "“if you want shortest runtime, Python isn't the best language to do that.”, gets my +1." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T22:33:54.387", "Id": "533296", "Score": "0", "body": "Ok, I've done some profiling for you. I had to use a longer string `'mchlrizyxwvutsqghvm'` to get similar timing for the OP's version to your 6.1 second starting point. After that, bitarray=1.7, bytearray=1.7, list=1.7, set=0.6 seconds. When I expanded the string with 500 `'a'`'s on the end, set=7.7 seconds, and set_pigeon=0.1 seconds." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T23:40:24.207", "Id": "270082", "ParentId": "270022", "Score": "3" } } ]
{ "AcceptedAnswerId": "270024", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T17:11:10.397", "Id": "270022", "Score": "15", "Tags": [ "python", "python-3.x" ], "Title": "Check whether a lowercase string has any character repetition" }
270022
<p>In my .net core hosted service console application, I am reading a database table, retrieving some values, and based on a status, I am sending emails. It is working as it is expected, I wonder if there are any improvements to make it better. So I would be glad if you can share your comments.</p> <p>Thanks in advance.</p> <h1><strong>Program.cs</strong></h1> <pre><code>using System.IO; using System.Net; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Events; using Serilog.Sinks.Email; namespace SendEmail { class Program { static async Task Main(string[] args) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Information() .Enrich.FromLogContext() .WriteTo.Console() .WriteTo.File(&quot;log-.txt&quot;, rollingInterval: RollingInterval.Day) .WriteTo.Email(new EmailConnectionInfo { FromEmail = &quot;test@gaming.com&quot;, ToEmail = &quot;test@gmail.com&quot;, MailServer = &quot;smtp.yandex.com.tr&quot;, NetworkCredentials = new NetworkCredential { UserName = &quot;test@gaming.com&quot;, Password = &quot;123456&quot; }, EnableSsl = false, Port = 587, EmailSubject = &quot;Send Email Service Error&quot; }, restrictedToMinimumLevel: LogEventLevel.Error, batchPostingLimit: 1) .CreateLogger(); var builder = new HostBuilder() .ConfigureServices((hostContext, services) =&gt; { //Serilog services.AddLogging(loggingBuilder =&gt; loggingBuilder.AddSerilog(dispose: true)); services.AddSingleton&lt;IHostedService, BusinessService&gt;(); //Setting up app settings configuration var config = LoadConfiguration(); services.AddSingleton(config); }); await builder.RunConsoleAsync(); } private static IConfiguration LoadConfiguration() { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile(&quot;appsettings.json&quot;, optional: false, reloadOnChange: true) .AddJsonFile(path: &quot;serilog.json&quot;, optional: false, reloadOnChange: true); return builder.Build(); } } } </code></pre> <h1><strong>BusinessService.cs</strong></h1> <pre><code>using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using MailKit.Net.Smtp; using MailKit.Security; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using MimeKit; namespace SendEmail { public class BusinessService : IHostedService { private readonly IHostApplicationLifetime _applicationLifetime; private readonly IConfiguration _configuration; private readonly ILogger _logger; public BusinessService(IHostApplicationLifetime applicationLifetime, IConfiguration configuration, ILogger&lt;BusinessService&gt; logger) { _applicationLifetime = applicationLifetime; _configuration = configuration; _logger = logger; } public async Task StartAsync(CancellationToken cancellationToken) { _logger.LogInformation(&quot;Application starts: &quot;); await GetData(); //Stop Application _applicationLifetime.StopApplication(); _logger.LogInformation(&quot;Application stops: &quot;); } private async Task SendEmailAsync(string email, string serial, string pin, long id) { var emailMessage = new MimeMessage(); emailMessage.From.Add(new MailboxAddress(&quot;Test&quot;,&quot;test@gmail.com&quot; )); emailMessage.To.Add(new MailboxAddress(&quot;&quot;, email)); emailMessage.Subject = &quot;Test Codes&quot;; emailMessage.Body = new TextPart(&quot;html&quot;) { Text = serial +&quot; &quot; + pin }; try { var client = new SmtpClient(); await client.ConnectAsync(&quot;smtp.gmail.com&quot;, 465, true); await client.AuthenticateAsync(&quot;test@gmail.com&quot;, &quot;12345&quot;); await client.SendAsync(emailMessage); await client.DisconnectAsync(true); //Update Table await UpdateData(id); } catch (Exception ex) { _logger.LogError(&quot;Error: {Error} &quot;, ex.Message); throw; // Throw exception if this exception is unexpected } } private async Task GetData() { var connString = _configuration[&quot;ConnectionStrings:Development&quot;]; await using var sqlConnection = new SqlConnection(connString); sqlConnection.Open(); await using var command = new SqlCommand {Connection = sqlConnection}; const string sql = @&quot;Select ID, Email, Serial, Pin from Orders where status = 1&quot;; command.CommandText = sql; try { await using var reader = await command.ExecuteReaderAsync(); while (reader.Read()) { _logger.LogInformation(&quot;Order {ID} , {Email}, {Serial}, {Pin} &quot;, reader.GetInt32(0).ToString(), reader.GetString(1), reader.GetString(2), reader.GetString(3)); await SendEmailAsync(reader.GetString(1).Trim(), reader.GetString(2).Trim(), reader.GetString(3).Trim(), reader.GetInt32(0)); } } catch (SqlException exception) { _logger.LogError(&quot;Error: {Error} &quot;, exception.Message); throw; // Throw exception if this exception is unexpected } } private async Task UpdateData(long id) { var connString = _configuration[&quot;ConnectionStrings:Development&quot;]; await using var sqlConnection = new SqlConnection(connString); sqlConnection.Open(); await using var command = new SqlCommand {Connection = sqlConnection}; const string sql = @&quot;Update Orders set status = 2, Date = GetDate() where id = @id&quot;; command.CommandText = sql; command.Parameters.Add(new SqlParameter(&quot;id&quot;, id)); try { await command.ExecuteNonQueryAsync(); } catch (SqlException exception) { _logger.LogError(&quot;Error: {Error} &quot;, exception.Message); throw; // Throw exception if this exception is unexpected } } public Task StopAsync(CancellationToken cancellationToken) { return Task.CompletedTask; } } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T17:15:15.093", "Id": "270023", "Score": "0", "Tags": [ "c#", ".net-core" ], "Title": "Sending emails from .net core console hostedservice" }
270023
<p>The problem: I am working with a set of objects in Blender with per-vertex colours. Each object has only two distinct colours. For all objects in a selection, I am choosing only the brighter of those two colours, and increasing its brightness by 10%.</p> <p>Language: Python 3.7</p> <p>About me: I am new to coding in Python, having read through a few tutorials and looked at some example code that other Blender users have created. I have coded extensively in R, but am completely self-taught, so who knows what bad habits I have picked up.</p> <p>Feedback requested: any, but in particular if there are any big efficiency gains that I can make, given that I am working with meshes that have large numbers of vertices.</p> <p>The code:</p> <pre><code>from bpy import context # Iterate over all selected objects selection = context.selected_objects for object in selection: # Get the colour data for the selected object v_col = object.data.vertex_colors[0] color = list(v_col.data[0].color) # Find the colour of the brighter segment all_colours = list() for data in v_col.data: all_colours.append(list(data.color)) segY = max(all_colours) # Assign new colour values to this segment new_colour = [min(x*1.1, 1) for x in segY] for data in v_col.data: if list(data.color) == segY: data.color = new_colour </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T20:45:10.793", "Id": "270028", "Score": "2", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Make selected colours brighter in Blender" }
270028
<p>I made a general smart pointer which fixes the problems of loops between <code>std::shared_ptr</code>'s. While use is simple, I feel that my code is inefficient and clumsy. Here it is:</p> <pre><code>/* * gc.hpp * * Created on: Nov 10, 2021 * Author: lambcoder */ #ifndef GC_HPP_ #define GC_HPP_ #include &lt;any&gt; namespace lambcoder{ template&lt;typename T&gt; class gcpointer; class garbage_collector final{ template&lt;typename T&gt; friend class gcpointer; template&lt;typename T, typename... Ts&gt; friend gcpointer&lt;T&gt; gcnew(Ts&amp;&amp;...); static garbage_collector global_gc; garbage_collector() {} struct Node{ Node() = default; template&lt;typename T, typename... Ts&gt; Node(std::in_place_type_t&lt;T&gt;, Node* prev, Node* next, Ts&amp;&amp;... ts): prev{prev}, next{next}, obj{std::in_place_type&lt;T&gt;, std::forward&lt;Ts&gt;(ts)...}{} Node* prev = nullptr, *next = nullptr; std::any obj{}; std::uint16_t ref_count = 1; template&lt;typename T, typename... Ts&gt; friend gcpointer&lt;T&gt; gcnew(Ts&amp;&amp;...); }; Node* head{nullptr}; static enum class State : std::uint8_t {weak, strong} weak_state; public: ~garbage_collector(){ weak_state = State::weak; Node* tmp = nullptr; while(head){ tmp = head-&gt;next; delete head; head = tmp; } } }; garbage_collector::State garbage_collector::weak_state = garbage_collector::State::strong; garbage_collector garbage_collector::global_gc = {}; template&lt;typename T&gt; class gcpointer{ using node_ptr = garbage_collector::Node*; node_ptr ptr = nullptr; gcpointer(node_ptr ptr) noexcept: ptr{ptr}{} public: constexpr T&amp; operator*(){ return std::any_cast&lt;T&amp;&gt;(ptr-&gt;obj); } constexpr T* operator-&gt;(){ return ptr ? &amp;this-&gt;operator*() : nullptr; } constexpr operator T*(){ return this-&gt;operator-&gt;(); } constexpr gcpointer() noexcept = default; constexpr gcpointer(std::nullptr_t) noexcept {}; constexpr gcpointer(const gcpointer&lt;T&gt;&amp; other) noexcept: ptr{other.ptr} { if(other.ptr != nullptr) ++ptr-&gt;ref_count; } gcpointer(gcpointer&lt;T&gt;&amp;&amp; other) noexcept: ptr{std::exchange(other.ptr, nullptr)} {} gcpointer&lt;T&gt;&amp; operator=(const gcpointer&lt;T&gt;&amp; other) noexcept{ if(other.ptr == this-&gt;ptr) return *this; if(ptr != nullptr &amp;&amp; --ptr-&gt;ref_count == 0){ if(ptr == garbage_collector::global_gc.head) garbage_collector::global_gc.head = garbage_collector::global_gc.head-&gt;next; else if(ptr-&gt;prev) ptr-&gt;prev-&gt;next = ptr-&gt;next; if(ptr-&gt;next) ptr-&gt;next-&gt;prev = ptr-&gt;prev; delete ptr; } ptr = other.ptr; if(ptr != nullptr) ++ptr-&gt;ref_count; return *this; } gcpointer&lt;T&gt;&amp; operator=(gcpointer&lt;T&gt;&amp;&amp; other) noexcept{ if(other.ptr == this-&gt;ptr) return *this; if(ptr != nullptr &amp;&amp; --ptr-&gt;ref_count == 0){ if(ptr == garbage_collector::global_gc.head) garbage_collector::global_gc.head = garbage_collector::global_gc.head-&gt;next; else if(ptr-&gt;prev) ptr-&gt;prev-&gt;next = ptr-&gt;next; if(ptr-&gt;next) ptr-&gt;next-&gt;prev = ptr-&gt;prev; delete ptr; } ptr = std::exchange(other.ptr, nullptr); return *this; } gcpointer&lt;T&gt; release() noexcept{ node_ptr tmp = ptr; ptr = nullptr; return gcpointer&lt;T&gt;(tmp); } ~gcpointer(){ if(garbage_collector::weak_state == garbage_collector::State::strong){ if(ptr != nullptr &amp;&amp; --ptr-&gt;ref_count == 0){ if(ptr == garbage_collector::global_gc.head) garbage_collector::global_gc.head = garbage_collector::global_gc.head-&gt;next; else if(ptr-&gt;prev) ptr-&gt;prev-&gt;next = ptr-&gt;next; if(ptr-&gt;next) ptr-&gt;next-&gt;prev = ptr-&gt;prev; delete ptr; } } } template&lt;typename U, typename... Ts&gt; friend gcpointer&lt;U&gt; gcnew(Ts&amp;&amp;...); }; template&lt;typename U, typename... Ts&gt; gcpointer&lt;U&gt; gcnew(Ts&amp;&amp;... ts){ if(!garbage_collector::global_gc.head) return gcpointer&lt;U&gt;( garbage_collector::global_gc.head = new garbage_collector::Node(std::in_place_type&lt;U&gt;, nullptr, nullptr, std::forward&lt;Ts&gt;(ts)...) ); else{ return gcpointer&lt;U&gt;( garbage_collector::global_gc.head = garbage_collector::global_gc.head-&gt;prev = new garbage_collector::Node(std::in_place_type&lt;U&gt;, nullptr, garbage_collector::global_gc.head, std::forward&lt;Ts&gt;(ts)...) ); } } } </code></pre> <p>Use and test:</p> <pre><code>#include &lt;iostream&gt; #include &quot;gc.hpp&quot; struct cat{ cat(){ std::cout &lt;&lt; &quot;cat default ctor&quot; &lt;&lt; std::endl; } cat(const cat&amp;){ std::cout &lt;&lt; &quot;cat copy ctor&quot; &lt;&lt; std::endl; } cat(cat&amp;&amp;){ std::cout &lt;&lt; &quot;cat move ctor&quot; &lt;&lt; std::endl; } cat&amp; operator=(const cat&amp;){ std::cout &lt;&lt; &quot;cat copy operator=&quot; &lt;&lt; std::endl; return *this;} cat&amp; operator=(cat&amp;&amp;){ std::cout &lt;&lt; &quot;cat move operator=&quot; &lt;&lt; std::endl; return *this;} ~cat(){ std::cout &lt;&lt; &quot;cat dtor&quot; &lt;&lt; std::endl; } }; struct B; struct A{ A(){ std::cout &lt;&lt; &quot;A default ctor&quot; &lt;&lt; std::endl; } A(const A&amp;){ std::cout &lt;&lt; &quot;A copy ctor&quot; &lt;&lt; std::endl; } A(A&amp;&amp;){ std::cout &lt;&lt; &quot;A move ctor&quot; &lt;&lt; std::endl; } A&amp; operator=(const A&amp;){ std::cout &lt;&lt; &quot;A copy operator=&quot; &lt;&lt; std::endl; return *this;} A&amp; operator=(A&amp;&amp;){ std::cout &lt;&lt; &quot;A move operator=&quot; &lt;&lt; std::endl; return *this;} ~A(){ std::cout &lt;&lt; &quot;A dtor&quot; &lt;&lt; std::endl; } lambcoder::gcpointer&lt;B&gt; ptr; }; struct B{ B(){ std::cout &lt;&lt; &quot;B default ctor&quot; &lt;&lt; std::endl; } B(const B&amp;){ std::cout &lt;&lt; &quot;B copy ctor&quot; &lt;&lt; std::endl; } B(B&amp;&amp;){ std::cout &lt;&lt; &quot;B move ctor&quot; &lt;&lt; std::endl; } B&amp; operator=(const B&amp;){ std::cout &lt;&lt; &quot;B copy operator=&quot; &lt;&lt; std::endl; return *this;} B&amp; operator=(B&amp;&amp;){ std::cout &lt;&lt; &quot;B move operator=&quot; &lt;&lt; std::endl; return *this;} ~B(){ std::cout &lt;&lt; &quot;B dtor&quot; &lt;&lt; std::endl; } lambcoder::gcpointer&lt;A&gt; ptr; }; int main(){ auto gcp = lambcoder::gcnew&lt;int&gt;(2); auto gcpcat1 = lambcoder::gcnew&lt;cat&gt;(), gcpcat2 = lambcoder::gcnew&lt;cat&gt;(*gcpcat1); std::cout &lt;&lt; *gcp &lt;&lt; std::endl; auto gcb = lambcoder::gcnew&lt;B&gt;(); auto gca = lambcoder::gcnew&lt;A&gt;(); gcb-&gt;ptr = gca; gca-&gt;ptr = gcb; std::cout &lt;&lt; &quot;Done!\n&quot;; } </code></pre> <p>Output:</p> <pre><code>cat default ctor cat copy ctor 2 B default ctor A default ctor Done! cat dtor cat dtor A dtor B dtor </code></pre> <p>As can be seen from the output, no memory leaks occurred.</p> <p><strong>Pros:</strong></p> <ul> <li>Easy to use.</li> </ul> <p><strong>Cons:</strong></p> <ul> <li>Involves double allocation per element.</li> <li>Doesn't reuse memory space.</li> <li>High overhead (up to 26 bytes per element: three pointers and 2 bytes worth of reference count).</li> <li>Isn't much better (or better at all) than <code>std::shared_ptr</code></li> <li>When in a scenario with two objects (like <code>B</code> and <code>A</code>) that reference each other, deletion of objects is delayed until the end of execution.</li> <li>Finally, custom allocators can't be used.</li> </ul> <p><strong>Questions:</strong></p> <ul> <li><p>Is this use for this implementation of garbage collection? Does it have ANY advantage over <code>std::shared_ptr</code> and <code>std::weak_ptr</code>?</p> </li> <li><p>The garbage collector deallocates <code>Node</code>'s once their object is deallocated. Should the garbage collector instead reuse the <code>Node</code>?</p> </li> <li><p>At the current moment, custom allocators are not allowed because the garbage collector might have to manually deallocate memory, and <code>Node</code>'s are untyped and don't store an allocator. Should the design change so that garbage collectors for certain types (passed a certain allocator type in the template arguments) must be declared and <code>gcpointer</code>'s created from them? With this approach, one allocation could be eliminated (since <code>Node</code>'s would be typed) Usage of this approach would look something like this:</p> <pre><code> lambcoder::garbage_collector&lt;std::allocator&lt;int&gt;&gt; gcint; auto gcpi = gcint.gcnew(2); lambcoder::garbage_collector&lt;std::allocator&lt;cat&gt;&gt; gccat; auto gcpcat1 = gccat.gcnew(), gcpcat2 = gccat.gcnew(*gcpcat1); </code></pre> </li> <li><p>Should I keep my current design, but add the aforementioned?</p> </li> <li><p>Is there any way to allocate the object <em>with</em> its <code>Node</code>? Should I?</p> </li> <li><p>Are there any other design changes that are recommended?</p> </li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T21:57:45.307", "Id": "533017", "Score": "0", "body": "What happens if a loop is unreachable? Because whichever you destroy first, the rest may stumble over." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T23:14:09.170", "Id": "533020", "Score": "0", "body": "@Deduplicator I am not sure what you mean. Have you looked at my code? In the destructor for garbage_collector, I set a flag which basically causes the destructor of the gcpointers to not touch the memory that they point to. Please take a look." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T07:23:32.287", "Id": "533034", "Score": "1", "body": "I wouldn't add garbage collection to C++. Because you take away one of its main strengths : explicit life time managment and predictability. If you need garbage collection there are other more suited languages" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T12:33:44.293", "Id": "533042", "Score": "1", "body": "@Pepijn Kramer, I don't think C++ will ever force you to use a garbage collector, but I suppose it could be useful in some instances. Not that I can really think of any =)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T16:16:56.657", "Id": "533066", "Score": "0", "body": "Could you show a practical use case of these ownership loops? I don’t understand why A needs to own B and B needs to own A. I think any program like this can be rewritten in a more logical and simple way where one of the two doesn’t own the other. In modern C++ we have 3 “types of pointer”: unique, shared, naked. The first two imply ownership, the latter implies non ownership. People are afraid of naked pointers, but I think they should be used when referring to something we don’t own." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T18:58:27.263", "Id": "533075", "Score": "0", "body": "@upkajdt I made this just for the fun and experience." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T19:00:50.870", "Id": "533076", "Score": "0", "body": "@CrisLunengo the point is to get rid of the need for differentiating between shared and weak. Like said, I made this for the fun." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T22:15:18.980", "Id": "533089", "Score": "1", "body": "I'm sorry if my comment seemed concending, it was not the intention. We all learn with experimenting, have fun!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T23:26:54.747", "Id": "533092", "Score": "1", "body": "@upkajdt No, you are correct! Sorry that it seemed that I was misinterpreting your comment. I was simply noting that, while C++ doesn't have much use for my class gcpointer, I made this not for any specific use, but just for a personal challenge." } ]
[ { "body": "<p>First, we need to fix the errors.</p>\n<ul>\n<li>The most obvious one is that the <code>#ifndef GC_HPP_</code> has no matching <code>#endif</code>.</li>\n<li>We're missing an include of <code>&lt;cstdint&gt;</code> for the fixed-width integer types.</li>\n<li>We're missing <code>&lt;utility&gt;</code> for <code>std::exchange</code>, <code>std::forward</code> and <code>std::in_place_type</code>.</li>\n</ul>\n<p>With those addressed, we can inspect the code.</p>\n<p>It's not clear why we need exact-sized types, rather than (e.g. <code>std::uint_fast16_t</code>). Is it important that the ref-count overflows once there's 65536 pointers to an object? I would expect a <code>std::size_t</code> to be a safer choice.</p>\n<p><code>Node</code> should have deleted copy constructor and assignment operator, to prevent unintended double ownership of the raw pointers <code>next</code> and <code>prev</code>.</p>\n<p><code>garbage_collector</code> itself should also be made non-copyable.</p>\n<p>It's better to explicitly default the constructor, rather than provide one with an empty body:</p>\n<pre><code>garbage_collector() = default;\n</code></pre>\n<p>I don't see why <code>weak_state</code> is shared across <em>all</em> the garbage collector instances. Shouldn't it be local to each one?</p>\n<p>No need for <code>this-&gt;</code> in the operator definitions:</p>\n<pre><code>constexpr T* operator-&gt;(){\n return ptr ? &amp;operator*() : nullptr;\n}\nconstexpr operator T*(){\n return operator-&gt;();\n}\n</code></pre>\n<p>The common code to decrement reference count and possibly free a node is written out three times. This should be refactored into a private function.</p>\n<p>Overall, I'd say the biggest design flaw is the assumption of a singleton. Not only does it make it hard to properly unit-test the collector, but it defeats an obvious use case, where a data structure wants to clean up its own members (but only its own) when it is destructed. That's easily fixed, of course, at the expense of having a reference member in each <code>Node</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T11:49:50.763", "Id": "270043", "ParentId": "270029", "Score": "7" } }, { "body": "<p>In addition to Toby's answer:</p>\n<h1>Remove <code>operator T*()</code></h1>\n<p>This is quite dangerous: it allows implicit casts from a garbage collected pointer to a raw pointer to the object. Note that <a href=\"https://en.cppreference.com/w/cpp/memory/shared_ptr\" rel=\"noreferrer\"><code>std::shared_ptr</code></a> doesn't have such a cast operator.</p>\n<h1>Consider making <code>garbage_collector</code> templated as well</h1>\n<p>Instead of having one garbage collector for all objects, it is possible to create individual garbage collectors for each type <code>T</code>, by making <code>garbage_collector</code> a <code>template&lt;typename T&gt;</code> as well. This reduces the size of the global linked lists, which might be handy if you do implement some form of intermediate garbage collection.</p>\n<h1>Cycles are only cleaned up on program exit</h1>\n<p>If you want to be better than <code>std::shared_ptr</code>, you want to be able to detect and clean up cycles while a program is still running. At the moment, cycles are not cleaned up until the global <code>garbage_collector</code> object(s) are destroyed. However, a program might want to ensure at some point that all objects are cleaned up. Consider adding a function to force all objects maintained by a <code>garbage_collector</code> to be destroyed.</p>\n<p>Of course, it would be better to avoid writing a program where such cycles can occur, but then you probably also wouldn't need a garbage collector anymore.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T21:25:59.813", "Id": "533084", "Score": "1", "body": "Just to add to the last section: there have been some interesting research papers out of IBM about how the information that a reference counting garbage collector maintains can be used to speed up tracing collection of cycles. They built a GC based on that, cleverly named the *Recycler*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T23:21:09.803", "Id": "533091", "Score": "0", "body": "@JörgWMittag Indeed, they wrote several papers about it, like [this one](https://researcher.watson.ibm.com/researcher/files/us-bacon/Bacon01Concurrent.pdf)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T12:24:10.633", "Id": "270044", "ParentId": "270029", "Score": "6" } } ]
{ "AcceptedAnswerId": "270043", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T20:47:46.520", "Id": "270029", "Score": "5", "Tags": [ "c++", "memory-management", "c++17", "pointers" ], "Title": "C++ Garbage Collector - Simple Automatic Memory Management" }
270029
<p>I am currently working on a Connect 4 game for a project and it works. We added support so that it can be played by 3 players instead of 2. I know there is multiple instances of repeated code or un-optimized functions or code. I would appreciate any help on that front.</p> <p>Regarding the 3 player connect 4 we pretty much had it act just like normal connect 4 but with 3 players. Player 1 is red, Player 2 is yellow and Player 3 is green. All 3 players are trying to get &quot;Connect 4&quot; like normal and prevent the other players from getting &quot;Connect 4&quot;. We are doing that in hopes of adding some complexity in play and add another variable for players to have to deal with while playing.</p> <pre><code>import sys import numpy as np import pygame import math # Global Values for the Game BLACK = (0, 0, 0) BLUE = (0, 0, 255) RED = (255, 0, 0) WHITE = (255, 255, 255) YELLOW = (255, 255, 0) GREEN = (0, 255, 0) ROW_COUNT = 7 COLUMN_COUNT = 8 SQUARE_SIZE = 75 WIDTH = COLUMN_COUNT * SQUARE_SIZE HEIGHT = (ROW_COUNT + 1) * SQUARE_SIZE RADIUS = int(SQUARE_SIZE / 2 - 5) # Function to Create the Board Full of Zeros def create_board(): board = np.zeros((ROW_COUNT, COLUMN_COUNT)) return board # Function for Dropping the Player Pieces def drop_piece(board, row, col, piece): board[row][col] = piece # Function to See Where the Player Drops is Valid def is_valid(board, col): return board[ROW_COUNT - 1][col] == 0 # Function to See Where the Next Open Row to Place Player Piece def next_open_row(board, col): for r in range(ROW_COUNT): if board[r][col] == 0: return r # Function to Print the Actual Board Because it is Flipped def print_board(board): print(np.flip(board, 0)) # Function to Check the Multiple Winning Move Cases def winning_move(board, piece): # Check Horizontal Locations for c in range(COLUMN_COUNT - 3): for r in range(ROW_COUNT): if board[r][c] == piece and board[r][c + 1] == piece and board[r][c + 2] == piece and board[r][c + 3] == \ piece: return True # Check Vertical Locations for c in range(COLUMN_COUNT): for r in range(ROW_COUNT - 3): if board[r][c] == piece and board[r + 1][c] == piece and board[r + 2][c] == piece and board[r + 3][c] == piece: return True # Check Positive Diagonals for c in range(COLUMN_COUNT - 3): for r in range(ROW_COUNT - 3): if board[r][c] == piece and board[r + 1][c + 1] == piece and board[r + 2][c + 2] == piece and board[r + 3][c + 3] == piece: return True # Check Negative Diagonals for c in range(COLUMN_COUNT - 3): for r in range(3, ROW_COUNT): if board[r][c] == piece and board[r - 1][c + 1] == piece and board[r - 2][c + 2] == piece and board[r - 3][c + 3] == piece: return True # Draws the Graphical Game Board def draw_board(board): # This nested for loop makes the empty starting board for c in range(COLUMN_COUNT): for r in range(ROW_COUNT): pygame.draw.rect(screen, BLUE, (c * SQUARE_SIZE, r * SQUARE_SIZE + SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE)) pygame.draw.circle(screen, BLACK, ( int(c * SQUARE_SIZE + SQUARE_SIZE / 2), int(r * SQUARE_SIZE + SQUARE_SIZE + SQUARE_SIZE / 2)), RADIUS) # This nested for loop is what is used to fill the board in with the player pieces for c in range(COLUMN_COUNT): for r in range(ROW_COUNT): if board[r][c] == 1: # Fill the board with Player 1 pieces pygame.draw.circle(screen, RED, ( int(c * SQUARE_SIZE + SQUARE_SIZE / 2), HEIGHT - int(r * SQUARE_SIZE + SQUARE_SIZE / 2)), RADIUS) if board[r][c] == 2: # Fill the board with Player 2 pieces pygame.draw.circle(screen, YELLOW, ( int(c * SQUARE_SIZE + SQUARE_SIZE / 2), HEIGHT - int(r * SQUARE_SIZE + SQUARE_SIZE / 2)), RADIUS) elif board[r][c] == 3: pygame.draw.circle(screen, GREEN, ( int(c * SQUARE_SIZE + SQUARE_SIZE / 2), HEIGHT - int(r * SQUARE_SIZE + SQUARE_SIZE / 2)), RADIUS) pygame.display.update() # Function to track the mouse movement def track_mouse(): if event.type == pygame.MOUSEMOTION: # Tracks the mouse motion pygame.draw.rect(screen, BLACK, (0, 0, WIDTH, SQUARE_SIZE)) posx = event.pos[0] if turn == 0: pygame.draw.circle(screen, RED, (posx, int(SQUARE_SIZE / 2)), RADIUS) if turn == 1: pygame.draw.circle(screen, YELLOW, (posx, int(SQUARE_SIZE / 2)), RADIUS) elif turn == 2: pygame.draw.circle(screen, GREEN, (posx, int(SQUARE_SIZE / 2)), RADIUS) pygame.display.update() # Graphical representation of dropping the piece def draw_drop_piece(event, turn): game_over = False colors = (RED, YELLOW, GREEN) # Container to Store Colors for easy calling if turn in (0, 1, 2): # Checks to See if its Players Turn posx = event.pos[0] col = int(math.floor(posx / SQUARE_SIZE)) if is_valid(board, col): # Checks Every Turn if Where the Player is Putting Their Piece is Valid row = next_open_row(board, col) drop_piece(board, row, col, turn + 1) if winning_move(board, turn + 1): # Checks Every Turn if the Player Won label = FONT.render(&quot;PLAYER {} WINS!&quot;.format(turn + 1), 1, colors[ turn]) # Format function allows to easily change a string in code depending on values screen.blit(label, (40, 10)) game_over = True else: label = FONT.render(&quot;Enter Valid Spot&quot;, 1, BLUE) screen.blit(label, (40, 10)) game_over = None # If the player made an invalid move it returns a none value print(turn) return game_over def start_menu(screen): click = False while True: label = FONT.render(&quot;Main Menu&quot;, 1, BLUE) screen.blit(label, (WIDTH / 4, 40)) posx, posy = pygame.mouse.get_pos() button_1 = pygame.Rect(WIDTH / 2, 200, 300, 70) button_2 = pygame.Rect(WIDTH / 2, 300, 300, 70) pygame.draw.rect(screen, BLACK, button_1) pygame.draw.rect(screen, BLACK, button_2) start_text = FONT.render(&quot;Start&quot;, 1, WHITE) screen.blit(start_text, (WIDTH / 3, 200)) quit_text = FONT.render(&quot;Quit&quot;, 1, WHITE) screen.blit(quit_text, (WIDTH / 3, 300)) if button_1.collidepoint((posx, posy)): if click: return True if button_2.collidepoint((posx, posy)): if click: sys.exit() for event in pygame.event.get(): if event.type == pygame.QUIT: # Exiting the game sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: click = True pygame.display.update() if __name__ == '__main__': pygame.init() board = create_board() # Creates Board print_board(board) # Prints Board game_over = False # The Game Isn't Over as it Just Started turn = 0 # Player One Starts First total_spaces = ROW_COUNT * COLUMN_COUNT FONT = pygame.font.SysFont(&quot;monospace&quot;, 50) SIZE = (WIDTH, HEIGHT) screen = pygame.display.set_mode(SIZE) start_menu(screen) draw_board(board) pygame.display.update() while not game_over: for event in pygame.event.get(): if event.type == pygame.QUIT: # Exiting the game sys.exit() track_mouse() if event.type == pygame.MOUSEBUTTONDOWN: pygame.draw.rect(screen, BLACK, (0, 0, WIDTH, SQUARE_SIZE)) game_over = draw_drop_piece(event, turn) print_board(board) draw_board(board) # This makes sure the turn indicator alternates between 1 and 0 # Also checks if the player made a valid move and if they didn't it doesn't move to the next turn if game_over is not None: turn = (turn + 1) % 3 total_spaces -= 1 # Checks to see if the total empty spaces are 0 if so that means its a tie if total_spaces &lt;= 0: label = FONT.render(&quot;TIE!&quot;, 1, BLUE) screen.blit(label, (40, 10)) print_board(board) draw_board(board) game_over = True if game_over: pygame.time.wait(5000) <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T18:57:20.953", "Id": "533074", "Score": "0", "body": "At least for me, your code isn't working (Python 3.9.4 on MacOS). It prints out some pygame boilerplate and a grid of zeros to the terminal and opens up a pygame window, but the window is mostly featureless (all black with a small blue rectangle and two small white rectangles). The window doesn't respond to any basic mouse clicks or keyboard presses. Does your program run only on certain kinds of systems? If so, you might want to add those qualifications to your question." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T21:02:36.090", "Id": "270031", "Score": "2", "Tags": [ "python", "pygame", "connect-four" ], "Title": "Connect 4 project for three players with PyGame graphics" }
270031
<p>I want to apply an async function to items retrieved through a stream.<br /> I have found two ways of doing it:</p> <p>Code 1</p> <pre><code>const promises = []; await new Promise(resolve =&gt; { const stream = getStream(); stream.on(&quot;data&quot;, (item) =&gt; { promises.push(handle(item)); }); stream.on(&quot;end&quot;, resolve); }); const res = await Promise.all(promises); </code></pre> <p>Code 2</p> <pre><code>const res = await new Promise(resolve =&gt; { const promises = []; const stream = getStream(); stream.on(&quot;data&quot;, (data) =&gt; { promises.push(handle(data)); }); stream.on(&quot;end&quot;, async () =&gt; { const res = await Promise.all(promises); resolve(res); }); }); </code></pre> <p>Are these correct and equivalent?<br /> Which one has your preference?<br /> Can it be improved?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T23:48:19.100", "Id": "533021", "Score": "1", "body": "Code 2 won't run as shown because the second `await` is not inside an `async` function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T21:23:00.673", "Id": "533083", "Score": "0", "body": "Good catch, thank you, edited accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T01:48:32.510", "Id": "533094", "Score": "0", "body": "Also, I would think you should be listening for the `error` event on the stream and reject your promise in both scenarios." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T16:17:49.963", "Id": "533132", "Score": "0", "body": "There has been at least one vote to close because the code lacks context. Since this is Code Review and not Stack Overflow we need more code that shows us the context of the code, such as how it is used. Another thing to keep in mind is that the code has to work as intended before we review the code, so it really should be tested first before the question is asked. You also might want to add the `comparative review` tag." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-12T23:22:42.197", "Id": "270034", "Score": "0", "Tags": [ "node.js", "async-await", "stream" ], "Title": "Async action on each items from a stream" }
270034
<p>This is a C# program that is a reference implementation, it will be used to make a C version after it is stable and bug free. The programs are supposed to simulate sensor data collection and processing nodes. One node gathers data from a sensor, then distributes the data to all the connected clients. The data gather node should only send the latest data point, and it should only send the data when the required number of clients are available. Also it should only send the next data point when all the clients have finished processing the data.</p> <p>This is the server code. This continually reads data from a sensor. If there are the right number of clients connected then it sends the latest data to each of the clients. It got really long because I kept finding new ways that client disconnects and stuff would break it, so making it simpler without breaking it would be great. The client count is controlled by the <code>ClientCount</code> variable, set to some low number for testing.</p> <pre><code>using System; namespace ServerDistribute { class Program { const int ClientCount = 3; const int BufferSize = 1024 * 1024 * 3; public class ThreadData { public System.Threading.Thread Thread; public System.Threading.AutoResetEvent DataTransferSignal; public System.Threading.AutoResetEvent DataProcessCompleteSignal; public byte[] DataBuffer; public System.Net.Sockets.Socket Socket; } //not sure if stack or queue is better static System.Collections.Generic.Stack&lt;System.Threading.AutoResetEvent&gt; AvailableDataTransferSignals = new System.Collections.Generic.Stack&lt;System.Threading.AutoResetEvent&gt;(ClientCount); static System.Threading.AutoResetEvent[] DataTransferSignals = new System.Threading.AutoResetEvent[ClientCount]; static System.Collections.Generic.List&lt;ThreadData&gt; ClientThreadData = new System.Collections.Generic.List&lt;ThreadData&gt;(); static object ClientThreadDataLock = new object(); static System.Threading.AutoResetEvent ThreadEventMutex = new System.Threading.AutoResetEvent(false); static void ProcessSocket(object state) { var threadData = (ThreadData)state; using var client = threadData.Socket; byte[] recBuffer = new byte[1]; threadData.DataProcessCompleteSignal.Set(); for (; ; ) { try { Console.WriteLine(&quot;Client: Wait for data transfer signal&quot;); threadData.DataTransferSignal.WaitOne(); Console.WriteLine(&quot;Client: Send data to client&quot;); client.Send(threadData.DataBuffer); Console.WriteLine(&quot;Client: Get process complete from client&quot;); client.Receive(recBuffer); threadData.DataProcessCompleteSignal.Set(); // System.Threading.Thread.Sleep(1000); } catch (Exception ex) { Console.WriteLine(&quot;Client: Got ex: &quot; + ex.Message); AvailableDataTransferSignals.Push(threadData.DataProcessCompleteSignal); lock (ClientThreadDataLock) ClientThreadData.Remove(threadData); ThreadEventMutex.Set(); return; } } } static void ListenForClients() { string socketLocation = &quot;C:\\Users\\Public\\Documents\\temp\\distribute.sock&quot;; if (System.IO.File.Exists(socketLocation)) System.IO.File.Delete(socketLocation); Console.WriteLine(&quot;Server: Creating socket&quot;); using var socket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.Unix, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Unspecified); socket.SendBufferSize = 1; Console.WriteLine(&quot;Server: Creating end point&quot;); var socketEndPoint = new System.Net.Sockets.UnixDomainSocketEndPoint(socketLocation); Console.WriteLine(&quot;Server: Binding&quot;); socket.Bind(socketEndPoint); Console.WriteLine(&quot;Server: Listening&quot;); socket.Listen(); ThreadEventMutex.Set(); Console.WriteLine(&quot;Server: Accepting clients&quot;); for (; ; ) { Console.WriteLine(&quot;Server: Waiting for empty slot&quot;); ThreadEventMutex.WaitOne(); Console.WriteLine(&quot;Server: Waiting for new client&quot;); var client = socket.Accept(); Console.WriteLine(&quot;Server: Got a client&quot;); var pts = new System.Threading.ParameterizedThreadStart(ProcessSocket); var t = new System.Threading.Thread(pts); var newTD = new ThreadData() { DataBuffer = null, Thread = t, Socket = client, DataTransferSignal = new System.Threading.AutoResetEvent(false) }; lock (ClientThreadDataLock) { newTD.DataProcessCompleteSignal = AvailableDataTransferSignals.Pop(); ClientThreadData.Add(newTD); if (ClientThreadData.Count &lt; ClientCount) ThreadEventMutex.Set(); } t.Start(newTD); } } static byte[] ActiveCaptureBuffer = new byte[BufferSize]; static byte[] SendableCaptureBuffer = new byte[BufferSize]; static object CaptureBufferLock = new object(); static System.Threading.AutoResetEvent DataCapturedSignal = new System.Threading.AutoResetEvent(false); static void CaptureData() { byte[] tempBuffer; using var rng = System.Security.Cryptography.RandomNumberGenerator.Create(); Console.WriteLine(&quot;Capture: Start capturing data&quot;); for (; ; ) { //simulate read data from sensor rng.GetBytes(ActiveCaptureBuffer); // Console.WriteLine(&quot;Got data&quot;); //simulate read delay // System.Threading.Thread.Sleep(250); //this might make a delay in the capture if the copy thread takes too long to copy data into the local buffer... lock (CaptureBufferLock) { tempBuffer = ActiveCaptureBuffer; ActiveCaptureBuffer = SendableCaptureBuffer; SendableCaptureBuffer = tempBuffer; DataCapturedSignal.Set(); } } } static void CopyData() { for (; ; ) { //I think this might get stuck if a client is removed Console.WriteLine(&quot;Copy: Wait for all clients to be ready to process new data&quot;); System.Threading.AutoResetEvent.WaitAll(DataTransferSignals); Console.WriteLine(&quot;Copy: Wait for new data for clients&quot;); DataCapturedSignal.WaitOne(); lock (ClientThreadDataLock) if (ClientThreadData.Count &lt; ClientCount) continue; //may cause a delay in the capture thread Console.WriteLine(&quot;Copy: Copy data from capture buffer&quot;); byte[] clientDataBuffer = new byte[BufferSize]; lock (CaptureBufferLock) Array.Copy(SendableCaptureBuffer, clientDataBuffer, BufferSize); lock (ClientThreadDataLock) { if (ClientThreadData.Count &lt; ClientCount) continue; Console.WriteLine(&quot;Copy: Signal clients to use new data&quot;); foreach (var td in ClientThreadData) { td.DataBuffer = clientDataBuffer; td.DataTransferSignal.Set(); } } } } static void Main(string[] args) { for (int i = 0; i &lt; DataTransferSignals.Length; ++i) { DataTransferSignals[i] = new System.Threading.AutoResetEvent(false); AvailableDataTransferSignals.Push(DataTransferSignals[i]); } var serverThread = new System.Threading.Thread(ListenForClients); serverThread.Start(); var dataCaptureThread = new System.Threading.Thread(CaptureData); dataCaptureThread.Start(); var dataCopyThread = new System.Threading.Thread(CopyData); dataCopyThread.Start(); Console.ReadLine(); } } } </code></pre> <p>This is the client code. This is supposed to connenct to the server and pull data from it, process the data, and then tell the server that it's ready for new data. Right now it uses the <code>ProcessTime</code> variable to simulate data processing with a thread sleep.</p> <pre><code>using System; namespace ClientDistribute { class Program { const int BufferSize = 1024 * 1024 * 3; const int ProcessTime = 1000; static void Main(string[] args) { string socketLocation = &quot;C:\\Users\\Public\\Documents\\temp\\distribute.sock&quot;; Console.WriteLine(&quot;Creating socket&quot;); using var socket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.Unix, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Unspecified); Console.WriteLine(&quot;Creating end point&quot;); var socketEndPoint = new System.Net.Sockets.UnixDomainSocketEndPoint(socketLocation); Console.WriteLine(&quot;Connecting&quot;); socket.Connect(socketEndPoint); var recBuffer = new byte[BufferSize]; int recLen; for (; ; ) { recLen = socket.Receive(recBuffer); Console.WriteLine($&quot;Got {recLen} bytes, first byte: 0x{recBuffer[0]:X2}&quot;); //simulate processing the data System.Threading.Thread.Sleep(ProcessTime); socket.Send(recBuffer, 0, 1, System.Net.Sockets.SocketFlags.None); } Console.WriteLine(&quot;Leaving main&quot;); } } } </code></pre> <p>Mostly I'm wondering if the implementation is correct and won't break under clients disconnecting and reconnecting or similar. Also performance improvements if they exist would be great. I don't think security is too important since these will all be on a single network that does not have an external connection. I'm not too concerned about style, but if there's any clever ways to simplify the code or make it easier to read without breaking the functionality then that might be good too.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T03:29:08.950", "Id": "533026", "Score": "0", "body": "For testing clients I put copies of the client program in multiple folders and changed the `ProcessTime` variable to different values." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T21:10:51.810", "Id": "533082", "Score": "0", "body": "Just a small thing I've noticed: AvailableDataTransferSignals is protected by ClientThreadDataLock when you create a new listening thread, but it's unprotected in the catch block. If multiple listeners break simultaneously, there might be problems." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T04:30:55.593", "Id": "533098", "Score": "0", "body": "@AndreySarafanov Oh right because it's not a concurrent stack." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T10:01:36.407", "Id": "533178", "Score": "0", "body": "@temp Is there any particular reason why did you implemented in a synchronous way instead of async?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T18:13:54.293", "Id": "533216", "Score": "0", "body": "@PeterCsala I guess the reason would be that I don't know how to use async. Is it a big difference for how it performs?" } ]
[ { "body": "<p>The code looks good as far as I can tell.</p>\n<p>Just a few functional observations.</p>\n<p>I obviously have no clue how the system will operate in real life, but I think the idea of hardcoding the number of clients is a bit odd. I assume that it will go into some sort of limping mode if say only two are connected. Perhaps it would be better to let the sensors identify themselves. As long as you got one <i>fizz</i> sensor, a <i>buzz</i> sensor and a <i>bang</i> sensor you are good to go. Having three <i>buzz</i> sensors will not do =)</p>\n<p>What should happen if more than <code>ClientCount</code> sensors try to connect. Currently, it looks like the connection was successful, but it's not receiving any data.</p>\n<p>Additionally, you may have to consider what should happen if a sensor goes offline and then come back to life. Perhaps you should devise some way to get it back up to speed with all the events it missed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T03:24:44.737", "Id": "533163", "Score": "0", "body": "Old data is not important and needs to be discarded. The number of clients is based on the specific processing that needs to be done on them so that is going to be a fixed number and if I need to change it then it will be easy enough to change the code value. If there are less than the required number of clients then it should pause on sending data because the data is only useful with the required number of clients running their data processing things on it. Basically it's just one sensor and 3 or however many processing nodes for the data from the one sensor." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T03:26:00.797", "Id": "533164", "Score": "0", "body": "Oh also the sensor should not send data to the clients unless they are all done processing the previously sent data." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T12:29:03.057", "Id": "533187", "Score": "0", "body": "Cool. I would perhaps suggest that you split it up, on the design level, into something like a `main controller`, `sensor(s)` and `processing units`. Sensors are generally expected to only measure something." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T22:36:25.197", "Id": "533228", "Score": "0", "body": "The sensor and processing is split up on account of the processing is done in the `ClientDistribute` program and the sensor data capture is done in the `ServerDistribute` program. I'm not sure if I can split it up more, but I guess I could have a program that captures the sensor data and sends it to another program that will then distribute it to clients, but I think the latency might be damaged from that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T14:35:22.640", "Id": "533263", "Score": "0", "body": "@temp It’s your project so you can do whatever you want :-) My head is just currently in the embedded space with loop detectors and rear window washer reservoir level sensors. If your going the C/C++ route it might be worthwhile to have a look at using [MPI](https://en.wikipedia.org/wiki/Message_Passing_Interface)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T19:51:40.453", "Id": "270077", "ParentId": "270038", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T03:22:32.287", "Id": "270038", "Score": "1", "Tags": [ "c#", "thread-safety", "socket" ], "Title": "Time-Sensitive Synchronized Transfer of Data Buffer in C# to Multiple Clients" }
270038
<p>This is my first project in C and I wanted a more experienced person's insight on how I made the whole program. Just looking for feedback it works how I want it to. The Github is <a href="https://github.com/cobb208/logfindAssignment" rel="nofollow noreferrer">here</a>. Thank you so much for the feedback!</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;dirent.h&gt; #include &lt;regex.h&gt; #include &lt;string.h&gt; #include &quot;dbg.h&quot; #define MAX_WORD_SIZE 100 int get_file_char_count(FILE *f, char *filename); int searchForKeyword(char *keyword, char *check_string); int findLogFilename(char *filename); int setIsOr(int argc, char *argv[]); char** logFileNames(); int main(int argc, char *argv[]) { check((argc == 0), &quot;Arguements required, please enter the search terms you want to look for in the log\nUse the -o to search for terms in one file.&quot;); unsigned int is_or = setIsOr(argc, argv); // set the and/or operator from -o flag FILE *fp; // Gets all file names in the log folder that end with .log char **logfile = logFileNames(); check(logfile == NULL, &quot;Failed to open directory and find log files!&quot;); int i = 0; while(logfile[i] != NULL) { char f_path[100]; strcpy(f_path, &quot;./log/&quot;); strcat(f_path, logfile[i]); fp = fopen(f_path, &quot;r&quot;); int file_length = get_file_char_count(fp, logfile[i]); rewind(fp); char *file_contents = malloc(sizeof(char) * file_length); // dynamically allocated because of file size fgets(file_contents, file_length, fp); // write the stream to the variable if(is_or) { int j = 1; for(j = 1; j &lt; argc; j++) { int result = searchForKeyword(argv[j], file_contents); if(result == 0) { printf(&quot;Match has been found in file: %s\n&quot;, logfile[i]); break; } } } else { int j = 1; int found_all = 0; // bool to hold if all words were found in file for(j = 1; j &lt; argc; j++) { int result = searchForKeyword(argv[j], file_contents); if(result == 0) { found_all = 1; } else { found_all = 0; break; } } if(found_all) printf(&quot;Match has been found, for all words, in file: %s\n&quot;, logfile[i]); } free(file_contents); fclose(fp); i++; } free(logfile); return 0; error: return -1; } int get_file_char_count(FILE *f, char *filename) { int returnVal = 0; char cursor = ' '; while(cursor != EOF) { cursor = fgetc(f); returnVal++; } return returnVal; } int searchForKeyword(char *keyword, char *check_string) { regex_t regex; int reg_setup; int reg_return_result; reg_setup = regcomp(&amp;regex, keyword, 0); reg_return_result = regexec(&amp;regex, check_string, 0, NULL, 0); return reg_return_result; } int findLogFilename(char *filename) { regex_t regex; int reg_setup; int reg_return_result; reg_setup = regcomp(&amp;regex, &quot;.log&quot;, 0); reg_return_result = regexec(&amp;regex, filename, 0, NULL, 0); return reg_return_result; } int setIsOr(int argc, char *argv[]) { int i = 0; int ret_int = 0; for(i = 0; i &lt; argc; i++) { if(strcmp(argv[i], &quot;-o&quot;) == 0) { ret_int = 1; // sets the or flag to true } } return ret_int; } char** logFileNames() { DIR *d; struct dirent *dir; int isLog = 1; char** retArr; d = opendir(&quot;./log&quot;); check(d, &quot;Could not open&quot;); int fileCount = 0; if(d) { while ((dir = readdir(d)) != NULL) { isLog = findLogFilename(dir-&gt;d_name); if(isLog == 0) { fileCount++; } } retArr = malloc(sizeof(*retArr) * fileCount); check_mem(retArr); rewinddir(d); int logFilePos = 0; while((dir = readdir(d)) != NULL) { isLog = findLogFilename(dir-&gt;d_name); if(isLog == 0) { retArr[logFilePos] = dir-&gt;d_name; logFilePos++; } } closedir(d); retArr[logFilePos + 1] = NULL; return retArr; } return NULL; error: closedir(d); return NULL; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T10:36:18.373", "Id": "533037", "Score": "1", "body": "Some things are missing from this question. First, what is this code supposed to *do*, and what do the program arguments mean? Secondly, what's in `\"dbg.h\"`? It would be very helpful to have the definitions available, for reviewers who wish to test the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T10:44:40.357", "Id": "533039", "Score": "0", "body": "There's a github link in the question that contains the source. dbg.h is the `check` macro, mostly." } ]
[ { "body": "<h1>Pick a style</h1>\n<p>You write:</p>\n<pre><code>int get_file_char_count(FILE *f, char *filename);\nint searchForKeyword(char *keyword, char *check_string);\n</code></pre>\n<p>You are mixing <code>snake_case</code> with <code>camelCase</code> names for your functions. I suggest that you stick with a single naming case for categories of names, so that all functions will use the same style. Pick one and use it everywhere.</p>\n<h1>Parse your args</h1>\n<p>Instead of writing a function to look for a single command line arg, write a function to parse and configure all the args. Ideally, you will use an argument-parsing library, even if it's just <code>getopt</code>.</p>\n<h1>Add a command line arg <code>-d DIR</code> to specify the log directory</h1>\n<p>This shouldn't be hard once you've picked an arg parsing library.</p>\n<h1>Don't throw away work you've already done</h1>\n<p>You write:</p>\n<pre><code>char **logfile = logFileNames();\n...\nwhile(logfile[i] != NULL)\n{\n char f_path[100];\n strcpy(f_path, &quot;./log/&quot;);\n strcat(f_path, logfile[i]);\n</code></pre>\n<p>But you have already computed the log file paths in your <code>logFileNames</code> function. Instead of repeating this work, have that function do it for you. Find a log file, construct the path, allocate memory using <code>malloc</code> or <code>strdup</code>, and pass that to the user. (This is in keeping with your <strong>functional-programming</strong> tag, as well.</p>\n<h1>Keep all the code in a single function at the same level of abstraction</h1>\n<p>You write:</p>\n<pre><code> fp = fopen(f_path, &quot;r&quot;);\n int file_length = get_file_char_count(fp, logfile[i]);\n rewind(fp);\n\n char *file_contents = malloc(sizeof(char) * file_length); // dynamically allocated because of file size\n fgets(file_contents, file_length, fp); // write the stream to the variable\n</code></pre>\n<p>I think you'll be disappointed with how that comes out. But ignoring that, you're doing operations at a low level (<code>fopen, rewind</code>) and at a high level (<code>get_file_char_count</code>). Don't do that.</p>\n<p>Instead, write nice high-level functions to do <em>all</em> the work. If you want to know the size of a file, pass in the name and expect a <code>size_t</code> result to come back. Let the function do the <code>fopen</code> (if it needs to, which it does not).</p>\n<p>Also, have a look at the <code>stat()</code> function. (Which may be some variant of <code>_stat</code> on Windows. <a href=\"https://duckduckgo.com/\" rel=\"nofollow noreferrer\">Ask the Duck.</a>)</p>\n<p>Similar suggestions apply to getting the file's contents - once you have the contents, you don't need the file pointer, so leave that inside the function. In fact, getting the file size is part of getting the contents. So <code>main</code> should not know about the size at all:</p>\n<pre><code>#include &lt;stdbool.h&gt;\n\nbool match_all_search_words = ... parse command line ...\nconst char ** search_words = ... parse command line ...\n\nconst char ** log_files = list_log_files(log_dir);\n\nfor (int i = 0; log_files[i] != NULL; ++i) {\n const char * log_file = log_files[i];\n const char * text = read_file_contents(log_file);\n\n if (match_all_search_words) {\n if (all_words_in_text(search_words, text)) {\n report_match(log_file);\n }\n else {\n report_failure(log_file);\n }\n }\n else {\n if (any_words_in_text(search_words, text)) {\n report_match(log_file);\n }\n else {\n report_failure(log_file);\n }\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T10:44:50.493", "Id": "270042", "ParentId": "270040", "Score": "2" } }, { "body": "<p><strong>Bug: failure to read entire file</strong></p>\n<p><code>fgets(file_contents, file_length, fp);</code> only reads up to a <em>line</em>. Research <code>fread()</code>.</p>\n<p><strong>Bug: insufficient allocation</strong></p>\n<p><code>fileCount</code> does not account for the appended <code>NULL</code>.</p>\n<pre><code>// retArr = malloc(sizeof(*retArr) * fileCount);\nretArr = malloc(sizeof *retArr * (fileCount + 1));\n...\nretArr[logFilePos + 1] = NULL;\n</code></pre>\n<p><strong>Bug: 257 vs 256</strong></p>\n<p><code>int fgetc()</code> returns 257 different values. Saving that into a <code>char cursor</code> will lose information. Use <code>int cursor;</code></p>\n<p><strong>Avoid buffer overflow</strong></p>\n<p><code>strcat(f_path, logfile[i])</code> risks overflowing the buffer.</p>\n<pre><code> char f_path[100];\n //strcpy(f_path, &quot;./log/&quot;);\n //strcat(f_path, logfile[i]);\n\n // Pedantic alternate\n int len = snprintf(f_path, sizeof f_path, &quot;%s%s&quot;, &quot;./log/&quot;, logfile[i]);\n check(len &gt;= 0 &amp;&amp; len &lt; sizeof f_path, &quot;Log file too big&quot;);\n</code></pre>\n<p><strong>File length + 1?</strong></p>\n<p><code>int get_file_char_count()</code> returns the file length plus one. Not a problem as the allocation needed that +1 anyways for <code>fgets()</code> to append a <em>null character</em>.</p>\n<p>File length may exceed <code>INT_MAX</code>. Perhaps use <code>unsigned long long</code> or <code>uintmax_t</code>?</p>\n<p><strong>Looking for option</strong></p>\n<p>Why check <code>argv[0]</code>, the program name?</p>\n<p>Why continue checking if found?</p>\n<p>Alternate:</p>\n<pre><code>int setIsOr(int argc, char *argv[]) {\n for (int i = 1; i &lt; argc; i++) {\n if (strcmp(argv[i], &quot;-o&quot;) == 0) {\n return 1;\n }\n }\n return 0;\n}\n</code></pre>\n<hr />\n<p><strong>Alternate <code>get_file_char_count()</code></strong></p>\n<p>For expediency, read a chunk at a time.</p>\n<pre><code>#define CHAR_COUNT_BUF_N 1024\nintmax_t get_file_char_count(FILE *f) {\n if (f == NULL) {\n return -1;\n }\n rewind(f); // Let us start at the beginning, clear error flag\n intmax_t char_count = 0; \n char buf[CHAR_COUNT_BUF_N];\n size_t length;\n while((length = fread(buf, 1, CHAR_COUNT_BUF_N, f) &gt; 0) {\n char_count += length;\n }\n if (ferror(f)) {\n char_count = -1;\n }\n rewind(f);\n return char_count;\n}\n</code></pre>\n<p>Usage</p>\n<pre><code>intmax_t file_length = get_file_char_count(fp);\ncheck(file_length &gt;= 0 &amp;&amp; file_length &lt; SIZE_MAX, &quot;File length trouble&quot;);\n\nsize_t file_length_size = (size_t) file_length; \nchar *file_contents = malloc(file_length_size + 1);\ncheck(file_contents, &quot;Out of memory&quot;);\n\nsize_t length = fread(file_contents, 1, file_length_size, fp);\nfile_contents[file_length_size] = '\\0'; // Append a 0 to form a string\ncheck(length == file_length_size, &quot;Read problem&quot;);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T11:28:44.983", "Id": "270061", "ParentId": "270040", "Score": "1" } }, { "body": "<h1><code>malloc()</code> can return a null pointer</h1>\n<p>This code hides Undefined Behaviour:</p>\n<blockquote>\n<pre><code> char *file_contents = malloc(sizeof(char) * file_length); // dynamically allocated because of file size\n fgets(file_contents, file_length, fp); // write the stream to the variable\n</code></pre>\n</blockquote>\n<p>We need to ensure that <code>file_contents</code> isn't a null pointer before we pass it into <code>fgets</code>.</p>\n<p>Also, multiplying by <code>sizeof (char)</code> is pointless, as that cannot be anything other than 1 (<code>sizeof</code> gives results in units of <code>char</code>).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T12:28:16.017", "Id": "270062", "ParentId": "270040", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T04:53:42.247", "Id": "270040", "Score": "2", "Tags": [ "c", "programming-challenge", "functional-programming" ], "Title": "Finds Keywords in Log Files" }
270040
<p>I am new to react, I tried to build login form and Code is as follows:</p> <p><strong>LoginForm.js</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>import React from "react"; import "./index.scss"; export default function LoginForm({ onSubmit }) { const [username, setUsername] = React.useState(""); const [password, setPassword] = React.useState(""); const [isDisabled, setIsDisabled] = React.useState(true); React.useEffect(() =&gt; { setIsDisabled(username === "" || password === ""); }, [username, password]); return ( &lt;fieldset className="loginForm"&gt; &lt;label className="loginForm__label" htmlFor="username-input"&gt; &lt;span className="loginForm__text"&gt;Username&lt;/span&gt; &lt;input className="loginForm__input" id="username-input" data-testid="username" value={username} type="text" onChange={evt =&gt; { setUsername(evt.target.value); }} /&gt; &lt;/label&gt; &lt;label className="loginForm__label" htmlFor="password-input"&gt; &lt;span className="loginForm__text"&gt;Password&lt;/span&gt; &lt;input className="loginForm__input" id="password-input" data-testid="password" value={password} type="password" onChange={evt =&gt; { setPassword(evt.target.value); }} /&gt; &lt;/label&gt; &lt;button className="loginForm__button" data-testid="login-button" disabled={isDisabled} onClick={() =&gt; { onSubmit(username, password); }} &gt; Submit &lt;/button&gt; &lt;/fieldset&gt; ); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.2.0/umd/react.production.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.2.0/umd/react-dom.production.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <p>Code might need to change based on the below rules:</p> <ul> <li>cause bugs open</li> <li>security vulnerabilities</li> <li>break tests</li> <li>weaken the performance of the application</li> <li>not be up to current coding standards in React and ES6</li> <li>not follow the coding patterns set up in the previous code</li> </ul> <p><strong>LoginForm.test.js</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>import { render, fireEvent } from "@testing-library/react"; import LoginForm from "./"; const callbackMock = jest.fn(); const setup = () =&gt; { const component = render(&lt;LoginForm onSubmit={callbackMock} /&gt;); const usernameInput = component.getByTestId("username"); const passwordInput = component.getByTestId("password"); const loginButton = component.getByTestId("login-button"); return { loginButton, usernameInput, passwordInput, ...component }; }; describe("Login Form", () =&gt; { it("disables the button when the form is not filled", () =&gt; { const { loginButton } = setup(); fireEvent.click(loginButton); expect(callbackMock).toHaveBeenCalledTimes(0); expect(loginButton).toHaveAttribute("disabled"); }); it("login button is disabled when only the username input is filled", () =&gt; { const { usernameInput, loginButton } = setup(); fireEvent.change(usernameInput, { target: { value: "Max Mustermann" } }); fireEvent.click(loginButton); expect(callbackMock).toHaveBeenCalledTimes(0); expect(loginButton).toHaveAttribute("disabled"); }); it("login button is disabled when only the password input is filled", () =&gt; { const { passwordInput, loginButton } = setup(); fireEvent.change(passwordInput, { target: { value: "secret" } }); fireEvent.click(loginButton); expect(callbackMock).toHaveBeenCalledTimes(0); expect(loginButton).toHaveAttribute("disabled"); }); it("login button is enabled when the password and username are filled", () =&gt; { const { usernameInput, passwordInput, loginButton } = setup(); fireEvent.change(usernameInput, { target: { value: "Max Mustermann" } }); fireEvent.change(passwordInput, { target: { value: "secret" } }); fireEvent.click(loginButton); expect(loginButton).toHaveProperty("disabled", false); expect(callbackMock).toHaveBeenCalled(); }); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.1.1/umd/react.production.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.1.1/umd/react-dom.production.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <p>How to refactor this?. Any help it so appreciated</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T10:38:12.267", "Id": "533038", "Score": "3", "body": "Welcome to Code Review! We need to know *what the code is intended to achieve*. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](//codereview.meta.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](//codereview.meta.stackexchange.com/q/2436), rather than your concerns about the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T12:12:53.493", "Id": "533041", "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. The rest of your question is unclear as well, so your question risks getting closed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T18:59:42.773", "Id": "533144", "Score": "0", "body": "The last \"rule\" is particularly enigmatic: *not follow the coding patterns set up in the previous code* - how would reviewers know about *previous code*? Did some sort of specification previously exist? Currently?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T10:20:52.447", "Id": "270041", "Score": "0", "Tags": [ "javascript", "react.js" ], "Title": "Refactoring the login form in React based on some rules" }
270041
<p>I know the vectors that describe two lines, <span class="math-container">$$\mathbf{a} + \lambda\mathbf{d}$$</span> and <span class="math-container">$$\mathbf{b} + \mu\mathbf{d'}$$</span> I've written a JavaScript function to get the coordinates of the point of intersection of two such lines. It is guaranteed that they will intersect, since in my case the lines are perpendicular. (Perhaps I could reduce the number of arguments by 1 since <strong>d'</strong> is just a perpendicular direction vector to <strong>d</strong>?)</p> <p>I solved the system of equations via substitution</p> <p><span class="math-container">$$ \left(\begin{array}{r}\mathbf{a}_x\\\mathbf{a}_y\end{array}\right) + \lambda\left(\begin{array}{r}\mathbf{d}_x\\\mathbf{d}_y\end{array}\right) = \left(\begin{array}{r}\mathbf{b}_x\\\mathbf{b}_y\end{array}\right) + \mu\left(\begin{array}{r}\mathbf{d'}_x\\\mathbf{d'}_y\end{array}\right) $$</span></p> <p><span class="math-container">$$ \lambda = \frac{\mathbf{b}_x+\mu\mathbf{d'}_x-\mathbf{a}_x}{\mathbf{d'}_x} $$</span></p> <p><span class="math-container">$$ \mu = \frac{\mathbf{a}_y\mathbf{d}_x+\mathbf{b}_x\mathbf{d}_y-\mathbf{a}_x\mathbf{d}_y-\mathbf{b}_y\mathbf{d}_x}{\mathbf{d'}_y\mathbf{d}_x-\mathbf{d}_y\mathbf{d'}_x} $$</span></p> <p>And directly implemented this in JavaScript.</p> <p>The function I've written looks like:</p> <pre><code>function getIntersection(a, d, b, d_) { const [ax, ay] = a; const [dx, dy] = d; const [bx, by] = b; const [d_x, d_y] = d_; const µ = (ay*dx + bx*dy - ax*dy - by*dx) / (d_y*dx - dy*d_x); return [bx + µ*d_x, by + µ*d_y]; } </code></pre> <p>How can I improve this function?</p> <p>Especially worried about:</p> <ul> <li>making it easier to read/maintain</li> <li>better algorithms for solving the problem</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T08:27:51.077", "Id": "533251", "Score": "0", "body": "Just make sure your code does not lie ;) If your function only solves for perpendicular lines then that should be reflected in the function name or there should at least be a comment stating that." } ]
[ { "body": "<p>If the lines are truly perpendicular then you don't need <strong>d_</strong> since it is either <code>[dy, -dx]</code> or <code>[-dy, dx]</code>.</p>\n<p>If I choose the first one and replace <strong>d_x</strong> by <strong>-dy</strong> and <strong>d_y</strong> by <strong>dx</strong> and substitube this into your function I get:</p>\n<pre><code>function getIntersection(a, d, b) {\n const [ax, ay] = a;\n const [dx, dy] = d;\n const [bx, by] = b;\n const µ = (ay*dx + bx*dy - ax*dy - by*dx) / (dx*dx + dy*dy);\n return [bx - µ*dy, by + µ*dx];\n}\n</code></pre>\n<p>Which is slightly shorter and less redundant. One final step I can see is:</p>\n<pre><code>function getIntersection(a, d, b) {\n const [ax, ay] = a;\n const [dx, dy] = d;\n const [bx, by] = b;\n const µ = (dx*(ay - by) + dy*(bx - ax)) / (dx*dx + dy*dy);\n return [bx - µ*dy, by + µ*dx];\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T15:40:35.517", "Id": "533272", "Score": "0", "body": "@theonlygusti I agree with the comment of \"konijn\" on your question. Perhaps the function should be renamed to `getProjection()` or `getPointProjectionOntoLine()`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T14:03:10.400", "Id": "270094", "ParentId": "270045", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T13:37:20.443", "Id": "270045", "Score": "2", "Tags": [ "javascript", "mathematics", "vectors" ], "Title": "Intersection of 2D vector equation straight lines" }
270045
<p>I am trying to fetch data from 7000 URLs and save the scrapped info into csv. Rather then go through all the 7000 URLs and save into one file. how can I break the csv into several files. for example 1000 URLs per csv.</p> <p>Below is an example of my current code. I have change the total to index 7000 = 20 and per csv = 4 URL.</p> <pre><code>import requests from bs4 import BeautifulSoup import pandas as pd import os import time import datetime as dt from random import randint path =r'C:\Users\mrfau\Documents\python\stock_screener_001\crypto_project' # urls= pd.read_csv(os.path.join(path,r'all_coin_link.csv')) urls_2 = ['https://coinmarketcap.com/currencies/bitcoin/','https://coinmarketcap.com/currencies/ethereum/','https://coinmarketcap.com/currencies/binance-coin/','https://coinmarketcap.com/currencies/tether/' ,'https://coinmarketcap.com/currencies/solana/','https://coinmarketcap.com/currencies/cardano/','https://coinmarketcap.com/currencies/xrp/','https://coinmarketcap.com/currencies/polkadot-new/' ,'https://coinmarketcap.com/currencies/dogecoin/','https://coinmarketcap.com/currencies/usd-coin/','https://coinmarketcap.com/currencies/shiba-inu/','https://coinmarketcap.com/currencies/terra-luna/' ,'https://coinmarketcap.com/currencies/litecoin/','https://coinmarketcap.com/currencies/avalanche/','https://coinmarketcap.com/currencies/uniswap/','https://coinmarketcap.com/currencies/chainlink/' ,'https://coinmarketcap.com/currencies/wrapped-bitcoin/','https://coinmarketcap.com/currencies/binance-usd/','https://coinmarketcap.com/currencies/algorand/','https://coinmarketcap.com/currencies/bitcoin-cash/'] ranks = [] names = [] prices = [] count = 0 row_start_loc = 0 i = 1 while i &lt; 5: for url in urls_2[row_start_loc:row_start_loc+4]: r = requests.get(url) soup = BeautifulSoup(r.text, 'html.parser') count += 1 print('Loop', count, f'started for {url}') rank = [] name = [] price = [] # loop for watchlist for item in soup.find('div', class_ = 'sc-16r8icm-0 bILTHz'): item = item.text rank.append(item) ranks.append(rank) # loop for ticker name for ticker in soup.find('h2', class_ = 'sc-1q9q90x-0 jCInrl h1'): ticker = ticker.text name.append(ticker) names.append(name) # loop for price for price_tag in soup.find('div', class_ = 'sc-16r8icm-0 kjciSH priceTitle'): price_tag = price_tag.text price.append(price_tag) prices.append(price) sleep_interval = randint(1, 2) print('Sleep interval ', sleep_interval) time.sleep(sleep_interval) df = pd.DataFrame(ranks) df2 = pd.DataFrame(names) df3 = pd.DataFrame(prices) final_table = pd.concat([df, df2, df3], axis=1) final_table.columns=['rank', 'type', 'watchlist', 'name', 'symbol', 'price', 'changes'] final_table.to_csv(os.path.join(path,fr'summary_{row_start_loc}.csv')) row_start_loc += 4 i += 1 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T15:36:36.517", "Id": "533131", "Score": "0", "body": "Welcome to the Code Review Community. We only review code that is working as expected, there are other sites that will help you debug your code. We do not help you write new code. Please read [Where can I get help?](https://meta.stackexchange.com/questions/129598/which-computer-science-programming-stack-exchange-sites-do-i-post-on) and [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T22:05:46.353", "Id": "533159", "Score": "0", "body": "(Why touch something *scrapped*, ten-feet pole or not?)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T16:22:50.490", "Id": "270049", "Score": "-3", "Tags": [ "python", "beautifulsoup" ], "Title": "Python Loop - Output divide into several files" }
270049
<p>In a previous question that I asked: <a href="https://codereview.stackexchange.com/questions/269644/get-image-value-total">Get image value total</a>, I learned to use <a href="https://docs.microsoft.com/en-us/dotnet/api/system.drawing.bitmap.lockbits?view=windowsdesktop-5.0" rel="nofollow noreferrer">LockBits</a> to speed up my code execution's time. Since then I have changed my code to Ham the distance instead of just getting the total value of the image. Here is my code:</p> <pre><code>private double GetImageValue(Bitmap Image, Size ImageSize) { double ImageValue = 0; List&lt;double&gt; Location = new List&lt;double&gt;(); Image = new Bitmap(Image, ImageSize); for (int X = 0; X &lt; Image.Width; X++) { for (int Y = 0; Y &lt; Image.Height; Y++) { Color PixelColor = Image.GetPixel(X, Y); int PixelValue = PixelColor.A + PixelColor.B + PixelColor.G + PixelColor.R; while (Location.Count &lt;= PixelValue) { Location.Add(0); } Location[PixelValue] += 1; } } for (int i = 0; i &lt; Location.Count; i++) { ImageValue += i + Location[i]; } return ImageValue; } </code></pre> <p>I do not know how to use LockBits to get the image value. Is it possible to use LockBits to get the image value? Thanks for any help.</p>
[]
[ { "body": "<p>The following helper class should be useful if you need to compare images:</p>\n<pre><code>class LockedBitmap : IDisposable\n{\n public LockedBitmap(Bitmap image)\n {\n bmp = image;\n rect = new Rectangle(0, 0, image.Width, image.Height);\n bmpData = image.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb);\n stride = Math.Abs(bmpData.Stride);\n var ptr = bmpData.Scan0;\n var bytes = stride * image.Height;\n data = new byte[bytes];\n System.Runtime.InteropServices.Marshal.Copy(ptr, data, 0, bytes);\n }\n\n public Color GetPixel(int x, int y)\n {\n int offset = y * stride + x * 3;\n int r = data[offset + 2];\n int g = data[offset + 1];\n int b = data[offset + 0];\n return Color.FromArgb(r, g, b);\n }\n\n public void SetPixel(int x, int y, Color col)\n {\n int offset = y * stride + x * 3;\n data[offset + 2] = col.R;\n data[offset + 1] = col.G;\n data[offset + 0] = col.B;\n }\n\n public int Stride { get { return stride; } }\n\n public void Dispose()\n {\n bmp.UnlockBits(bmpData);\n }\n\n public byte[] data;\n\n private int stride;\n private Bitmap bmp;\n private BitmapData bmpData;\n private Rectangle rect;\n}\n</code></pre>\n<p>This can be used like so:</p>\n<pre><code>long HamImages(Bitmap img1, Bitmap img2)\n{\n if (img1.Width != img2.Width || img1.Height != img2.Height)\n return long.MaxValue;\n\n using var lbm1 = new LockedBitmap(img1);\n using var lbm2 = new LockedBitmap(img2);\n\n long total = 0;\n for (int y = 0; y&lt;img1.Height; y++)\n {\n for (int x = 0; x &lt; img1.Width; x++)\n {\n Color col1 = lbm1.GetPixel(x, y);\n Color col2 = lbm2.GetPixel(x, y);\n total += Math.Abs(col1.R - col2.R) + Math.Abs(col1.G - col2.G) + Math.Abs(col1.B - col2.B);\n }\n }\n return total;\n}\n</code></pre>\n<p>The problem with this is that you are missing out on some of the benefits of locking the bitmap in the first case. It would be more efficient to work on the raw values than converting them to a <code>Color</code>:</p>\n<pre><code>long HamImages(Bitmap img1, Bitmap img2)\n{\n if (img1.Width != img2.Width || img1.Height != img2.Height)\n return long.MaxValue;\n\n using var lbm1 = new LockedBitmap(img1);\n using var lbm2 = new LockedBitmap(img2);\n long total = 0;\n for (int y = 0; y&lt;img1.Height; y++)\n {\n int offset1 = y * lbm1.Stride;\n int offset2 = y * lbm2.Stride;\n for (int x = 0; x &lt; img1.Width; x++)\n {\n int r1 = lbm1.data[offset1 + x * 3 + 2];\n int g1 = lbm1.data[offset1 + x * 3 + 1];\n int b1 = lbm1.data[offset1 + x * 3 + 0];\n\n int r2 = lbm2.data[offset2 + x * 3 + 2];\n int g2 = lbm2.data[offset2 + x * 3 + 1];\n int b2 = lbm2.data[offset2 + x * 3 + 0];\n\n total += Math.Abs(r1 - r2) + Math.Abs(g1 - g2) + Math.Abs(b1 - b2);\n }\n }\n return total;\n}\n</code></pre>\n<p>You can look here to find better ideas for comparing two colors: <a href=\"https://stackoverflow.com/questions/3968179/compare-rgb-colors-in-c-sharp\">https://stackoverflow.com/questions/3968179/compare-rgb-colors-in-c-sharp</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T18:35:37.770", "Id": "270074", "ParentId": "270052", "Score": "0" } }, { "body": "<p>Just to give you some additional suggestions.</p>\n<p>this part :</p>\n<pre><code>while (Location.Count &lt;= PixelValue)\n{\n Location.Add(0);\n}\n</code></pre>\n<p>can be replaced with this :</p>\n<pre><code>if (Location.Count &lt;= PixelValue)\n{\n Location.AddRange(new double[PixelValue - Location.Count + 1]);\n}\n</code></pre>\n<p>for this part :</p>\n<pre><code>for (int i = 0; i &lt; Location.Count; i++)\n{\n ImageValue += i + Location[i];\n}\n</code></pre>\n<p>you can totally replaced it with simple calculation. So, what you need is just to know is the max value of <code>pixelValue</code> along with the total count of repeated <code>pixelValue</code> to be added to the calculation.</p>\n<p>So, if you have a serious of numbers to be cumulated like :</p>\n<pre><code>1+2+3+4+5+6+7+...etc \n</code></pre>\n<p>you can take the minimum and the maximum numbers, add them together, then divide them by 2 then multiply the result by the maximum number. This would give you the final result directly.</p>\n<p>So, you would end-up doing something like this :</p>\n<pre><code>var sumTotalCount = Location.Sum(); // sum all the values\n\nImageValue = (maxPixelValue * ((maxPixelValue + 1) / 2)) + (sumTotalCount) + Location.Count;\n</code></pre>\n<p>doing this, would also give you advantage to avoid using <code>List&lt;double&gt;</code> as well, and use variables to store the total <code>pixelValue</code> count and the max value of <code>pixelValue</code>.</p>\n<p>Example :</p>\n<pre><code>var counter = 0;\nvar maxValue = 0;\n \nfor (int y = 0, offset = 0; y &lt; image.Height; y++, offset += bmpData.Stride)\n{\n for (int x = 0, index = offset; x &lt; image.Width; x++, index += 4)\n {\n\n byte blue = values[index];\n byte green = values[index + 1];\n byte red = values[index + 2];\n byte alpha = values[index + 3];\n\n Color color = Color.FromArgb(alpha, red, green, blue);\n\n int pixelValue = (color.A + color.B + color.G + color.R) - 1;\n \n if(pixelValue &gt; maxValue)\n {\n maxValue = pixelValue;\n }\n\n counter++;\n }\n}\n\nvar imageValue = (maxValue * ((maxValue + 1) / 2)) + counter + maxValue + 1;\n</code></pre>\n<p>I haven't test it, but theoretically should return the same result.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T06:45:43.577", "Id": "270089", "ParentId": "270052", "Score": "0" } } ]
{ "AcceptedAnswerId": "270089", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-13T20:00:15.510", "Id": "270052", "Score": "1", "Tags": [ "c#", "algorithm" ], "Title": "Getting the total image value" }
270052
<p>I am currently working on a problem that involves multiple producers and a single consumer through a queue object. The following list is about a few things that's special about this problem:</p> <ol> <li>One producer is conditional, meaning that it only produces data to the queue under certain condition.</li> <li>I'd like the problem to be as robust as possible, including graceful termination on <code>ctrl-c</code>.</li> <li>A particular simplification I did is to run one of the producer in the main thread, just so that I don't have too much code here.</li> <li>There are two type of data(job) that's got put into the queue, integer 1 and integer 2. Integer 1 is generated by the main thread(one producer) and integer 2 is generated less frequent(which I call it snapshot because that's what it is in my real-life project).</li> </ol> <p>I pasted the full toy program below. I could have used <code>logging</code> package but this is what I did so I left it unchanged.</p> <pre><code>import threading import time import queue import datetime def process_job(evt, q, cond): while not evt.is_set(): try: print(f'{datetime.now()} worker: getting a job from the queue') job = q.get(timeout=2) except: print(f'{datetime.now()} worker: q.get timed-out. continue...') continue if job == 1: print(f'{datetime.now()} worker: processing job == 1') q.task_done() elif job == 2: # job 2 is snapshot print(f'{datetime.now()} worker: processing job == 2') q.task_done() else: print(f'{datetime.now()} worker: bad job {job}') q.task_done() def get_snapshot_long(): print(f'{datetime.now()} get_snapshot: start...') time.sleep(10) print(f'{datetime.now()} get_snapshot: returning snapshot') return 2 def fetch_snapshot(evt, q, cond, flag): while not evt.is_set(): with cond: print(f'{datetime.now()} fetcher: waiting for cond') ret = cond.wait_for(lambda : flag[0], timeout=5) if not ret: # timed-out print(f'{datetime.now()} fetcher: wait_for timed-out. continue...') continue ss = get_snapshot_long() q.put(ss) flag[0] = False if __name__ == '__main__': stop_worker_thread_evt = threading.Event() stop_snapshot_thread_evt = threading.Event() flag_lock = threading.Lock() cond = threading.Condition(flag_lock) run_snapshot = [False] # just so I can modify in other threads q = queue.Queue() # ------------------------------------------------------- work_thread = threading.Thread( target=process_job, args=(stop_worker_thread_evt, q, cond)) snapshot_thread = threading.Thread( target=fetch_snapshot, args=(stop_snapshot_thread_evt, q, cond, run_snapshot)) work_thread.start() snapshot_thread.start() # -------------------------------------------------------- count = 0 # every 5 count, put in a request for snapshot print(f'{datetime.now()} main: start...') while True: try: time.sleep(5) q.put(1) count += 1 if count % 5 == 0: print(f'{datetime.now()} main: trying to notify snapshot thread...') with cond: run_snapshot[0] = True cond.notify() print(f'{datetime.now()} main: snapshot notified') except KeyboardInterrupt: print(f'{datetime.now()} main: user terminating...') break # ------------------------------------------------------- # terminate snapshot thread before terminating the consumer thread stop_snapshot_thread_evt.set() print(f'{datetime.now()} main: marked events set') snapshot_thread.join() print(f'{datetime.now()} main: snapshot thread joined') stop_worker_thread_evt.set() work_thread.join() print(f'{datetime.now()} main: work thread joined') print(f'{datetime.now()} main: q size={q.qsize()}') #q.join() I don't think we can join the q here. #because the stop of threads are controlled by event variables #instead of sentinel job in the queue. You just can't guarantee #an empty queue at this point print(f'{datetime.now()} main: q joined. DONE') </code></pre> <p>Please review and provide critical suggestions. In addition, I have a few specific questions about this program:</p> <ol> <li>I used <code>threading.Event</code> object to control the termination of non-main threads. Is that the best way to go about it? One issue I had with that is, we could potentially mark the consumer thread done where there are still jobs in it. I used to use a sentinel job in the queue to control that to ensure an empty queue.</li> <li>Is it a good idea to have a snapshot thread? Right now I am using an extra <code>threading.Condition</code> object to communicate to this thread. Is that a good solution?</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T09:46:24.700", "Id": "533102", "Score": "1", "body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T11:33:51.343", "Id": "533106", "Score": "0", "body": "What exact version of Python are you targeting?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T21:43:50.610", "Id": "533155", "Score": "0", "body": "@Mast, I am targeting python 3.6+." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T21:48:37.647", "Id": "533157", "Score": "0", "body": "@TobySpeight I updated the title. I hope it is more descriptive about the issue I am trying to solve." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T09:27:48.410", "Id": "533177", "Score": "0", "body": "I've further edited to simplify to just what the code does, rather than your concerns about it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T18:40:05.827", "Id": "533220", "Score": "0", "body": "@TobySpeight, I completely update the question with a more concise program." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T02:14:21.680", "Id": "270056", "Score": "1", "Tags": [ "python", "multithreading", "queue" ], "Title": "Multi-producer/single-consumer queue in Python" }
270056
<p>This is my solution for evaluating postfix expression using a stack. It does work on multidigit numbers, the problem I was struggling with last time. Now it works completely fine.</p> <p>This is the stack that I'm using:</p> <pre><code>class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): self.items.pop() def peek(self): try: return self.items[-1] except: return False def value_at_index(self, value): try: return self.items[value] except: return False def all_items(self): return self.items </code></pre> <p>And here is my code:</p> <pre><code>def result(data): &quot;&quot;&quot;Evaluating postfix expression&quot;&quot;&quot; stack = Stack() if data != False: for element in data: try: if type(float(element)) == float: stack.push(element) except: method = &quot;float(stack.value_at_index(-2))&quot; + element + &quot;float(stack.value_at_index(-1))&quot; method = eval(method) stack.pop() stack.pop() stack.push(method) return stack.peek() else: return &quot;Check your formula&quot; data = ['20', '10', '+', '75', '45', '-', '*'] print(result(data)) </code></pre> <p>Output:</p> <pre><code>900.00 </code></pre> <p>It works perfectly fine, but to be completely honest i would like to get rid of <code>eval</code> because of the negative opinions on this built-in function I heard. I want some reviews from you guys and advices how to generally improve it.</p> <p>Using Python 3.6.7.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T13:50:46.047", "Id": "533121", "Score": "0", "body": "isn't `index_of_element` actually `value_at_index`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T13:54:04.073", "Id": "533122", "Score": "0", "body": "@hjpotter92 well probably yeah, my bad at naming." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T15:17:52.527", "Id": "533129", "Score": "0", "body": "I'm curious: For what value of `element` have you observed `type(float(element)) == float` to be false?" } ]
[ { "body": "<ul>\n<li><p>Python's lists are stacks.<br />\nYour <code>Stack</code> class is making your code harder to read because it's not using Python's idioms.</p>\n</li>\n<li><p>Don't use bare excepts, as all exceptions are silenced.<br />\nYou shouldn't be silencing <a href=\"https://docs.python.org/3/library/exceptions.html#SystemExit\" rel=\"nofollow noreferrer\"><code>SystemExit</code></a> or <a href=\"https://docs.python.org/3/library/exceptions.html#KeyboardInterrupt\" rel=\"nofollow noreferrer\"><code>KeyboardInterrupt</code></a>. Only handle the exceptions you need to handle.</p>\n</li>\n<li><p><code>type(float(element)) == float</code><br />\nYou should default to using <code>isinstance</code>.\nYou'll be building a habit of supporting child types, rather than fighting bad habits later.</p>\n</li>\n<li><p>I'd suggest splitting normalizing your tokens away from evaluating the tokens.\nBasically move <code>float(element)</code> out of the function.</p>\n</li>\n<li><p>We can then change your type check to check if the number is a <code>numbers.Number</code>.</p>\n</li>\n<li><p>I'd recommend preferring storing numbers as <code>int</code>s rather than <code>float</code>s to avoid floating point issues.</p>\n</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>import numbers\nfrom typing import Union, Iterable, Iterator\n\nAToken = Union[str, numbers.Number]\n\n\ndef to_numbers(tokens: Iterable[str]) -&gt; Iterator[AToken]:\n for token in tokens:\n for cast in (int, float, complex):\n try:\n yield cast(token)\n break\n except ValueError:\n pass\n else:\n yield token\n\n\ndef evaluate(data: Iterable[AToken]) -&gt; numbers.Number:\n stack: list[numbers.Number] = []\n for token in data:\n if isinstance(token, numbers.Number):\n stack.append(token)\n else:\n rhs = stack.pop()\n lhs = stack.pop()\n stack.append(eval(f&quot;{lhs}{token}{rhs}&quot;))\n return stack[0]\n\n\ndata = ['20', '10', '+', '75', '45', '-', '*']\nprint(evaluate(to_numbers(data)))\n</code></pre>\n<p>We can remove the need for using <code>eval</code> by calling the appropriate dunder method.</p>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; getattr(1, &quot;__add__&quot;)(2)\n3\n</code></pre>\n<p>So we can just pass in a dictionary of {op: dunder}.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def evaluate(data: Iterable[AToken], ops: dict[str, str]) -&gt; numbers.Number:\n stack: list[numbers.Number] = []\n for token in data:\n if isinstance(token, numbers.Number):\n stack.append(token)\n else:\n rhs = stack.pop()\n lhs = stack.pop()\n stack.append(getattr(lhs, ops[token])(rhs))\n return stack[0]\n\n\nOPS = {\n &quot;+&quot;: &quot;__add__&quot;,\n &quot;-&quot;: &quot;__sub__&quot;,\n &quot;*&quot;: &quot;__mul__&quot;,\n}\n\ndata = ['20', '10', '+', '75', '45', '-', '*']\nprint(evaluate(to_numbers(data), OPS))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T15:04:39.537", "Id": "533127", "Score": "0", "body": "Now if im trying use the second part of your code without eval, im getting TypeError: 'type' object is not subscriptable" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T15:14:28.827", "Id": "533128", "Score": "1", "body": "@KermitTheFrog You're probably not on Python 3.9+. Put `from __future__ import annotations` at the top of the file and the issues will disappear. Alternately change `dict[str, str]` to `\"dict[str, str]\"` and `list[numbers.Number]` to `\"list[numbers.Number]\"`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T22:09:01.940", "Id": "533160", "Score": "0", "body": "Gotcha, i have one more question, how would it be possible to have input f.e not as splitted strings but a one input: ['20 10 + 75 45 - *']" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T14:14:16.363", "Id": "533205", "Score": "0", "body": "i meant ('20 10 + 75 45 - *')" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T22:46:29.267", "Id": "533229", "Score": "0", "body": "@KermitTheFrog you've probably used a poor example because you can just `'20 10 + 75 45 - *'.split()`. There are two ways you can parse the string otherwise; build a tokenizer or use *BNF (EBNF and ABNF are far nicer than BNF). You can build a parser quite easily by 1. `if char in \"0123456789\": token.append(char)` `else: yield \"\".join(token); if char in \"+-*\": yield char`." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T14:02:55.097", "Id": "270066", "ParentId": "270063", "Score": "1" } } ]
{ "AcceptedAnswerId": "270066", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T12:47:49.600", "Id": "270063", "Score": "2", "Tags": [ "python", "python-3.x", "object-oriented", "stack", "postfix" ], "Title": "Evaluating postfix expression on multidigit numbers" }
270063
<p>I am trying to use Java8 for a piece of code which I had written in Java6 and am able to achieve the result using both the version of java but I am thinking there could be more better way to write the code which I written in Java8</p> <pre><code>// Find vowels count in each given country names // return map of country name and vowel count //Given -- ['New Zealand', 'Australia'] //Result -- {New Zealand=4, Australia=5} List&lt;String&gt; countryNames = new ArrayList&lt;&gt;(); countryNames.add(&quot;New Zealand&quot;); countryNames.add(&quot;Australia&quot;); List&lt;String&gt; VOWELS = Arrays.asList(&quot;a&quot;, &quot;e&quot;, &quot;i&quot;, &quot;o&quot;, &quot;u&quot;); Map&lt;String, Integer&gt; countryWithVowelCount = new HashMap&lt;String, Integer&gt;(); //Using Java6 for (String name : countryNames) { int j = 0; for (int i = 0; i &lt; name.length(); i++) { if (VOWELS.contains(&quot;&quot; + name.toLowerCase().charAt(i))) { if (countryWithVowelCount.containsKey(name)) { j = countryWithVowelCount.get(name); countryWithVowelCount.put(name, ++j); } else { countryWithVowelCount.put(name, 1); } } } } // Using Java8 Map&lt;Object, String&gt; result = countryNames.stream() .collect(Collectors.groupingBy(cname -&gt; cname, Collectors.mapping(cname -&gt; { int j = 0; for (int i = 0; i &lt; cname.length(); i++) { if (VOWELS.contains(&quot;&quot; + cname.toLowerCase().charAt(i))) { ++j; } } return &quot;&quot; + j; }, Collectors.joining(&quot;&quot;)))); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T05:18:08.357", "Id": "533170", "Score": "1", "body": "Since we are in code review, it is necessary to remind that the definition of a vowel varies from language to language. It seems that you are working with english language, so it should be mentioned in the names of relevant classes and/or methods." } ]
[ { "body": "<p>Welcome to Stack Review, the first thing I see in the code is the following:</p>\n<pre><code>List&lt;String&gt; VOWELS = Arrays.asList(&quot;a&quot;, &quot;e&quot;, &quot;i&quot;, &quot;o&quot;, &quot;u&quot;);\n</code></pre>\n<p>This is correct, but from the uppercase <code>VOWELS</code> name you chose for the variable it seems me you meant this as a constant, so you could declare it :</p>\n<pre><code>private static final String VOWELS = &quot;aeiou&quot;;\n</code></pre>\n<p>I chose to modify the type to <code>String</code> from <code>List</code> because it seems me more easy to use, so for example you can isolate your code counting the vowels in a separate function like below :</p>\n<pre><code>private static int countVowels(String cname) {\n final char[] arr = cname.toLowerCase().toCharArray();\n int j = 0;\n for (char c : arr) {\n if (VOWELS.indexOf(c) != -1) {\n ++j;\n }\n }\n return j;\n}\n</code></pre>\n<p>I just substituted your <code>VOWELS.contains(&quot;&quot; + cname.toLowerCase().charAt(i))</code> line with the <code>indexOf</code> string function because I'm seeing that the char is present or not in the <code>VOWELS</code> string.</p>\n<p>The more important part in your code is the part about when you streams the list and convert it to a <code>Map</code> : you can avoid the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#groupingBy-java.util.function.Function-java.util.stream.Collector-\" rel=\"nofollow noreferrer\"><code>Collectors.groupingBy</code></a> and stream it directly like below :</p>\n<pre><code>Map&lt;String, Integer&gt; result = countryNames.stream()\n .collect(Collectors.toMap(Function.identity(), cname -&gt; countVowels(cname)));\n</code></pre>\n<p>Or directly delete the <code>countVowels</code> function and the <code>VOWELS</code> constant and do all the process in <em>one line</em> :</p>\n<pre><code>Map&lt;String, Integer&gt; result = countryNames.stream()\n .collect(Collectors.toMap(Function.identity(), cname -&gt; cname.toLowerCase().replaceAll(&quot;[^aeiou]&quot;,&quot;&quot;).length()));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T04:30:02.720", "Id": "533168", "Score": "1", "body": "I think one typo is there in the line\n `.collect(Collectors.toMap(Function.identity(), cname -> countVowels(VOWELS)));`\ninstead of passing `VOWELS` it should be passed `cname`,\n Thanks for the review and provided a alternate and better solution" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T07:08:55.213", "Id": "533172", "Score": "0", "body": "@AbdullahQayum You are welcome and thank you for your observation about the typo, I haven't noticed it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T18:33:45.877", "Id": "270073", "ParentId": "270064", "Score": "4" } }, { "body": "<h2>Functions...</h2>\n<p>When you're writing code, even when you're just playing about, it's usually a good idea to put the code into a function. This helps you to think about what the interface to the code should be, what it's dependencies are and what it should be called. Based on the code, I'd go with a function declaration something like:</p>\n<pre><code>Map&lt;String, Integer&gt; getVowelCounts(List&lt;String&gt; countryNames) {\n</code></pre>\n<h2>Version difference</h2>\n<p>Splitting the code like this, it becomes evident that there's a different between the results of the J6 and J8 code versions. Whilst the J6 version does indeed return a <code>Map&lt;String, Integer&gt;</code>, the J8 version returns <code>Map&lt;Object,String&gt;</code>. It's not clear why this discrepancy is there. It doesn't really seem to make sense, but perhaps you want the vowel count in a string for some reason...</p>\n<h2>Naming</h2>\n<p>I'm not a huge fan of single letter variable names. Using something like <code>for(int i...</code> can be ok, if it's the only iterator in a block of code. As soon as you start introducing more iterations, or other single letter variables it starts to become confusing as to which <code>i</code> is for the inner iteration and which <code>j</code> is for the vowel count. Consider being more expressive with your names.</p>\n<h2>Break is down...</h2>\n<p>Counting the vowels in a string seems like something that you might want to do other than when counting the vowels in a list of countries. To me, this suggests that it should be its own function.</p>\n<h2>Grouping</h2>\n<p>I'm not sure <code>groupingBy</code> is the correct usage here. You're not <em>really</em> grouping, you're using it as a convenient way to turn the result into a map. If you were to pass in a duplicate country, you start getting some pretty unexpected results. For example, adding in another 'New Zealand', rather than producing the correct '4' vowels, or the '8' vowels which the J6 version returns, it returns '44' (4 from the first instance appended with 4 from the second instance). Instead it might be better to use <code>toMap</code>. This will actually throw an exception if you try to process a list that has multiple instances of the same country, so that you know your source data might be corrupted. Or, you can use <code>distinct</code> in combination to allow multiples in the source data.</p>\n<h2>Putting it together</h2>\n<p>You end up with something like:</p>\n<pre><code>Map&lt;String, Integer&gt; getVowelCounts(List&lt;String&gt; countryNames) {\n\n return countryNames.stream()\n .distinct() // Do you want to support multiple instances of countryNames?\n .collect(Collectors.toMap(name -&gt; name, this::vowelCount));\n}\n\n\nstatic Set&lt;Integer&gt; vowels = &quot;aeiouAEIOU&quot;.codePoints()\n .boxed().collect(Collectors.toSet());\n\nint vowelCount(String str) {\n return str.codePoints()\n .map(c -&gt; vowels.contains(c) ? 1 : 0)\n .sum();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T04:31:36.840", "Id": "533169", "Score": "0", "body": "I think the method `codePoints` is from Java9,\nThank you for the review and providing alternate better solution" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T11:19:20.977", "Id": "533180", "Score": "0", "body": "@AbdullahQayum Both `chars` and `codePoint` are Java8, They're part of the `CharSequence` interface: https://docs.oracle.com/javase/8/docs/api/java/lang/CharSequence.html" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T12:18:30.153", "Id": "533184", "Score": "2", "body": "Why the `mapToObj` then the `mapToInt`? They add unnecessary cognition and complexity while `.map(codePoint -> vowels.contains((char) codePoint) ? 1 : 0)` is very legible. Also, You cast a `codePoint` to `char`, so why not use `chars()` in the first place? Better yet, why not have a `Set<Integer> vowelCodePoints`? Then the code can easily become `str.codePoints().filter(vowelCodePoints::contains).count()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T20:12:03.250", "Id": "533226", "Score": "0", "body": "@OlivierGrégoire Development, at least for me, is an iterative process. My original version has `mapToObj->map->mapToInt` and at the time I didn't immediately think of a clean way to create a set of code points, `(int)'a'` wasn't very satisfactory. Your `filter/count` is probably more expressive than my `map/sum`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T18:44:48.633", "Id": "270075", "ParentId": "270064", "Score": "5" } }, { "body": "<p>Some of my suggestions won't necessarily make sense for this specific example, but for the general idea of counting occurrences of a set of characters in a string, they might scale better to bigger workloads.</p>\n<pre><code>public class StringUtils {\n private static final Set&lt;Character&gt; ENGLISH_VOWELS = new HashSet&lt;&gt;('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U');\n\n\n public static Integer countOccurrences(final String container, final Set&lt;Character&gt; toCount) {\n return container\n .chars()\n .reduce(0,\n (subtotal, element) -&gt;\n subtotal + (toCount.contains(element) ? 1 : 0));\n }\n\n public static Map&lt;String, Integer&gt; countOccurrencesMultiple(final List&lt;String&gt; containers, final Set&lt;Character&gt; toCount) {\n return containers\n .stream()\n .collect(Collectors.toMap(Function.identity(), \n StringUtils::countOccurrences));\n }\n\n public static Integer countVowelOccurrences(final String container) {\n return countOccurrences(container, ENGLISH_VOWELS);\n }\n\n public static Map&lt;String, Integer&gt; countVowelOccurrencesMultiple(final List&lt;String&gt; containers) {\n return countOccurrencesMultiple(containers, ENGLISH_VOWELS);\n }\n}\n</code></pre>\n<p>The main ideas here are:</p>\n<ol>\n<li>Make the characters you're going to count the occurrences of a <code>Set</code>, instead of any other <code>Iterable</code> type, including a <code>String</code> or an array. Iterating over all of your characters to count for every character in your test strings is fine for now but if your list of characters has to grow in the future (maybe count vowels in multiple languages?), the constant-time presence check characteristic of <code>Set</code> could become useful. Plus, it automatically takes care of any duplicate entries.</li>\n<li>Declare your parameters <code>final</code>, so that you don't reassign to them (mutation of variables is not a great idea in functional code).</li>\n<li><code>reduce</code> is really powerful!</li>\n<li>Try to solve your problems in as general a way as possible, but not too general!</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T15:09:33.967", "Id": "270095", "ParentId": "270064", "Score": "2" } } ]
{ "AcceptedAnswerId": "270073", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T13:09:47.420", "Id": "270064", "Score": "4", "Tags": [ "java", "stream" ], "Title": "Find vowels count in each given country names using Java6 and Java8" }
270064
<p>This was inspired by the question <a href="https://codereview.stackexchange.com/questions/269983/passing-programs-to-a-stack-machine-implemented-in-c">Passing Programs To A Stack Machine Implemented In C++</a>.</p> <p>I wanted to make it a bit smarter by adding control functions:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>instruction</th> <th>op1</th> <th>op2</th> <th>op3</th> <th>description</th> </tr> </thead> <tbody> <tr> <td><code>jmp</code></td> <td>a</td> <td></td> <td></td> <td>unconditional jump to <code>a</code></td> </tr> <tr> <td><code>jgt</code></td> <td>a</td> <td>b</td> <td>c</td> <td>jump to <code>c</code> if <code>a &gt; b</code></td> </tr> <tr> <td><code>jlt</code></td> <td>a</td> <td>b</td> <td>c</td> <td>jump to <code>c</code> if <code>a &lt; b</code></td> </tr> <tr> <td><code>get</code></td> <td>a</td> <td></td> <td></td> <td>push the element at <code>a</code> to the top of the stack</td> </tr> <tr> <td><code>set</code></td> <td>a</td> <td>b</td> <td></td> <td>set the element at <code>b</code> to <code>a</code></td> </tr> <tr> <td><code>wrt</code></td> <td>a</td> <td></td> <td></td> <td>writes <code>a</code> to the console</td> </tr> </tbody> </table> </div> <pre><code>#include &lt;charconv&gt; #include &lt;functional&gt; #include &lt;iostream&gt; #include &lt;map&gt; #include &lt;sstream&gt; #include &lt;string&gt; #include &lt;variant&gt; #include &lt;vector&gt; template &lt;class T&gt; class stackprog { public: static T run(const std::vector&lt;std::string&gt;&amp; arguments) { auto instructions = parse(arguments); return process(instructions); } static T run(const std::string&amp; prog) { std::vector&lt;std::string&gt; arguments; std::stringstream ss(prog); std::string item; while (getline(ss, item, ' ')) arguments.push_back(item); return run(arguments); } private: static T pop(std::vector&lt;T&gt;&amp; vec) { T retval = vec.back(); vec.pop_back(); return retval; } static void jump(std::vector&lt;T&gt;&amp; stack, std::size_t&amp; index, bool gt) { std::size_t pos = static_cast&lt;std::size_t&gt;(std::lround(pop(stack))); T b = pop(stack); T a = stack.back(); if ((gt &amp;&amp; a &gt; b) || (!gt &amp;&amp; a &lt; b)) index = pos - 1; } typedef std::function&lt;T(T)&gt; func1arg; typedef std::function&lt;T(T, T)&gt; func2arg; typedef std::function&lt;void(std::vector&lt;T&gt;&amp;, std::size_t&amp;)&gt; funcctrl; typedef std::variant&lt;T, func1arg, func2arg, funcctrl&gt; instruction; static std::vector&lt;instruction&gt; parse(const std::vector&lt;std::string&gt;&amp; args) { static std::map&lt;std::string, func1arg&gt; functions1{ { &quot;abs&quot;, [](T a) { return (T)std::fabs(a); } }, { &quot;cos&quot;, [](T a) { return (T)std::cos(a); } }, { &quot;exp&quot;, [](T a) { return (T)std::exp(a); } }, { &quot;log&quot;, [](T a) { return (T)std::log(a); } }, { &quot;sin&quot;, [](T a) { return (T)std::sin(a); } }, { &quot;tan&quot;, [](T a) { return (T)std::tan(a); } }, { &quot;flr&quot;, [](T a) { return (T)std::floor(a); } }, { &quot;sqrt&quot;, [](T a) { return (T)std::sqrt(a); } } }; static std::map&lt;std::string, func2arg&gt; functions2{ { &quot;add&quot;, [](T a, T b) { return a + b; } }, { &quot;div&quot;, [](T a, T b) { return a / b; } }, { &quot;mul&quot;, [](T a, T b) { return a * b; } }, { &quot;sub&quot;, [](T a, T b) { return a - b; } }, { &quot;pow&quot;, [](T a, T b) { return (T)std::pow(a, b); } }, { &quot;mod&quot;, [](T a, T b) { return (T)std::fmod(a, b); } } }; static std::map&lt;std::string, funcctrl&gt; functionsc{ { &quot;jmp&quot;, [](std::vector&lt;T&gt;&amp; stack, std::size_t&amp; index) { index = static_cast&lt;std::size_t&gt;(std::lround(pop(stack))) - 1; } }, { &quot;jgt&quot;, [](std::vector&lt;T&gt;&amp; stack, std::size_t&amp; index) { jump(stack, index, true); } }, { &quot;jlt&quot;, [](std::vector&lt;T&gt;&amp; stack, std::size_t&amp; index) { jump(stack, index, false); } }, { &quot;get&quot;, [](std::vector&lt;T&gt;&amp; stack, std::size_t&amp; index) { std::size_t pos = static_cast&lt;std::size_t&gt;(std::lround(pop(stack))); stack.emplace_back(stack[pos]); } }, { &quot;set&quot;, [](std::vector&lt;T&gt;&amp; stack, std::size_t&amp; index) { std::size_t pos = static_cast&lt;std::size_t&gt;(std::lround(pop(stack))); stack[pos] = pop(stack); } }, { &quot;wrt&quot;, [](std::vector&lt;T&gt;&amp; stack, std::size_t&amp; index) { std::cout &lt;&lt; pop(stack); } }, }; std::vector&lt;instruction&gt; instructions; for (auto arg : args) { T number; auto ret = std::from_chars(arg.data(), arg.data() + arg.size(), number); if (ret.ec == std::errc() &amp;&amp; ret.ptr == arg.data() + arg.size()) { instructions.emplace_back(number); continue; } auto func1 = functions1.find(arg); if (func1 != functions1.end()) { instructions.emplace_back(func1-&gt;second); continue; } auto func2 = functions2.find(arg); if (func2 != functions2.end()) { instructions.emplace_back(func2-&gt;second); continue; } auto funcc = functionsc.find(arg); if (funcc != functionsc.end()) { instructions.emplace_back(funcc-&gt;second); continue; } std::ostringstream oss; oss &lt;&lt; &quot;Error: invalid instruction: &quot; &lt;&lt; arg; throw std::runtime_error(oss.str()); } return instructions; } static T process(const std::vector&lt;instruction&gt;&amp; instructions) { std::vector&lt;T&gt; stack; stack.reserve(instructions.size()); for (size_t i = 0; i &lt; instructions.size(); i++) { const auto&amp; inst = instructions[i]; switch (inst.index()) { case 0: stack.emplace_back(std::get&lt;T&gt;(inst)); break; case 1: stack.emplace_back(std::get&lt;func1arg&gt;(inst)(pop(stack))); break; case 2: stack.emplace_back(std::get&lt;func2arg&gt;(inst)(pop(stack), pop(stack))); break; case 3: std::get&lt;funcctrl&gt;(inst)(stack, i); break; } } return stack.empty() ? 0 : stack.back(); } }; int main(int argc, char* argv[]) { if (argc == 1) { // simple loop, expected result: 10000000 std::cout &lt;&lt; stackprog&lt;int&gt;::run(&quot;0 1 add 1000000 1 jlt&quot;) &lt;&lt; '\n'; // hypot, expected result: 5 std::cout &lt;&lt; stackprog&lt;double&gt;::run(&quot;3 2 pow 4 2 pow add sqrt&quot;) &lt;&lt; '\n'; // calculating pi, expected result: pi to the fifth digit std::cout &lt;&lt; stackprog&lt;double&gt;::run(&quot;0 -1 1 get 2 add 1 set 4 1 get div 0 get add 0 set 0 get 1 get 2 add 1 set 4 1 get div sub 0 set 1 get 1e6 4 jlt 0 get&quot;) &lt;&lt; '\n'; // Hello World, expected result: Hello, World! std::cout &lt;&lt; stackprog&lt;char&gt;::run(&quot;72 wrt 101 wrt 108 wrt 108 wrt 111 wrt 44 wrt 32 wrt 87 wrt 111 wrt 114 wrt 108 wrt 100 wrt 33&quot;); } else { // execute from command line arguments try { std::cout &lt;&lt; stackprog&lt;double&gt;::run(std::vector&lt;std::string&gt;(argv + 1, argv + argc)); } catch (std::exception err) { std::cerr &lt;&lt; err.what(); return 1; } } } </code></pre>
[]
[ { "body": "<h2>Security / error handling:</h2>\n<p>I don't think it's a good idea to allow the user to crash the program, or (worse) achieve undefined behavior when running the interpreter. This means we have to check that stack indices are valid before we use them, that we don't try to pop from an empty stack, and that the stack has only one item on it at the end.</p>\n<p>We can either check manually, and <code>throw</code>, or use <code>std::vector::at()</code>.</p>\n<hr />\n<p>The rest of this review is mainly nitpicking.</p>\n<hr />\n<h2>Unnecessary string copies:</h2>\n<p>(Since this is tagged performance <code>¯\\_(ツ)_/¯</code>)</p>\n<blockquote>\n<pre><code>static T run(const std::string&amp; prog)\n{\n std::vector&lt;std::string&gt; arguments;\n std::stringstream ss(prog); // copy of entire input string\n std::string item;\n while (getline(ss, item, ' ')) // copy of every argument\n arguments.push_back(item); // copy of every argument (again)\n return run(arguments);\n}\n</code></pre>\n</blockquote>\n<p>Honestly this is a perfectly normal way of doing it, <strike>but streams are awful and should be avoided</strike> but we could use a vector of <code>std::string_view</code> for the arguments, and write our own <code>getline</code> function to split the string, and thus avoid making any copies at all. Hopefully someday the standards committee will get around to fixing this bit of the standard library, but until then we have to do it ourselves.</p>\n<p>I think it would be reasonable to parse directly into the instructions, instead of creating an intermediate vector. (Though I guess that would require concatenating the command line arguments).</p>\n<hr />\n<blockquote>\n<pre><code> static std::map&lt;std::string, func1arg&gt; functions1{\n static std::map&lt;std::string, func2arg&gt; functions2{\n static std::map&lt;std::string, funcctrl&gt; functionsc{\n</code></pre>\n</blockquote>\n<p>We could use <code>std::string_view</code> for the keys here.</p>\n<p>The maps could also be <code>const</code>.</p>\n<hr />\n<blockquote>\n<pre><code> ...\n for (auto arg : args) // unnecessary copy of every arg\n</code></pre>\n</blockquote>\n<p>It looks like could use <code>auto const&amp; arg</code> here.</p>\n<hr />\n<blockquote>\n<pre><code> std::ostringstream oss;\n oss &lt;&lt; &quot;Error: invalid instruction: &quot; &lt;&lt; arg;\n throw std::runtime_error(oss.str());\n</code></pre>\n</blockquote>\n<p><code>arg</code> is already a <code>std::string</code>, so we could just <code>throw std::runtime_error(&quot;Error: invalid instruction: &quot; + arg);</code>. Even if it wasn't, we could use <code>std::to_string(arg)</code> instead of a<strike>n evil</strike> <code>stringstream</code>.</p>\n<hr />\n<blockquote>\n<pre><code>std::vector&lt;std::string&gt;(argv + 1, argv + argc)\n</code></pre>\n</blockquote>\n<p>Again, if we used <code>std::vector&lt;std::string_view&gt;</code> we can avoid the copies here.</p>\n<hr />\n<h2>Modern <code>if</code> conditions:</h2>\n<blockquote>\n<pre><code> auto func1 = functions1.find(arg);\n if (func1 != functions1.end())\n {\n instructions.emplace_back(func1-&gt;second);\n continue;\n }\n</code></pre>\n</blockquote>\n<p>Can be written as:</p>\n<pre><code> if (auto f1 = functions1.find(arg); f1 != functions1.end())\n {\n instructions.push_back(f1-&gt;second);\n continue;\n }\n</code></pre>\n<p>Which keeps <code>f1</code> in as small a scope as possible.</p>\n<hr />\n<p>Likewise:</p>\n<blockquote>\n<pre><code> T number;\n auto ret = std::from_chars(arg.data(), arg.data() + arg.size(), number);\n if (ret.ec == std::errc() &amp;&amp; ret.ptr == arg.data() + arg.size())\n {\n instructions.emplace_back(number);\n continue;\n }\n</code></pre>\n</blockquote>\n<p>This is definitely complex enough to factor out into a separate function: <code>std::optional&lt;T&gt; to_number(std::string const&amp; str);</code>. Then we could do:</p>\n<pre><code> if (auto n = to_number(arg); n.has_value())\n {\n instructions.push_back(n.value());\n continue;\n }\n</code></pre>\n<hr />\n<h2>Magic numbers vs <code>std::visit</code>:</h2>\n<blockquote>\n<pre><code> for (size_t i = 0; i &lt; instructions.size(); i++)\n {\n const auto&amp; inst = instructions[i];\n switch (inst.index())\n {\n case 0:\n stack.emplace_back(std::get&lt;T&gt;(inst));\n break;\n case 1:\n stack.emplace_back(std::get&lt;func1arg&gt;(inst)(pop(stack)));\n break;\n case 2:\n stack.emplace_back(std::get&lt;func2arg&gt;(inst)(pop(stack), pop(stack)));\n break;\n case 3:\n std::get&lt;funcctrl&gt;(inst)(stack, i);\n break;\n }\n }\n</code></pre>\n</blockquote>\n<p>Using magic number indices like this is a bit... icky.</p>\n<p>To use <code>std::visit</code>, we can either declare a visitor struct inside the function:</p>\n<pre><code> struct visitor\n {\n std::size_t&amp; i;\n std::vector&lt;T&gt;&amp; stack;\n\n void operator()(T t) { stack.push_back(t); }\n void operator()(func1arg f1) { stack.push_back(f1(pop(stack))); }\n void operator()(func2arg f2) { stack.push_back(f2(pop(stack), pop(stack))); }\n void operator()(funcctrl fc) { fc(stack, i); }\n };\n\n for (size_t i = 0; i &lt; instructions.size(); i++)\n std::visit(visitor{ i, stack }, instructions[i]);\n</code></pre>\n<p>Which is a bit messy, because we only use the index sometimes.</p>\n<p>Or we can use the <a href=\"https://en.cppreference.com/w/cpp/utility/variant/visit\" rel=\"nofollow noreferrer\">inheritance trick from here</a> with some lambdas:</p>\n<pre><code>template&lt;class... Ts&gt; struct overloaded : Ts... { using Ts::operator()...; };\ntemplate&lt;class... Ts&gt; overloaded(Ts...) -&gt; overloaded&lt;Ts...&gt;;\n\n...\n\n for (size_t i = 0; i &lt; instructions.size(); i++)\n {\n std::visit(\n overloaded\n {\n [&amp;] (T t) { stack.push_back(t); },\n [&amp;] (func1arg f1) { stack.push_back(f1(pop(stack))); },\n [&amp;] (func2arg f2) { stack.push_back(f2(pop(stack), pop(stack))); },\n [&amp;] (funcctrl fc) { fc(stack, i); } \n },\n instructions[i]);\n }\n</code></pre>\n<p>Neither of these methods is perfect, but they're perhaps a little clearer.</p>\n<hr />\n<h2>Popping:</h2>\n<blockquote>\n<pre><code>static_cast&lt;std::size_t&gt;(std::lround(pop(stack)))\n</code></pre>\n</blockquote>\n<p>There are enough of these around that it would be worth factoring out into a <code>pop_stack_index</code> function.</p>\n<hr />\n<h2>Magic numbers:</h2>\n<blockquote>\n<pre><code> catch (std::exception err)\n {\n std::cerr &lt;&lt; err.what() &lt;&lt; std::endl;\n return 1;\n }\n</code></pre>\n</blockquote>\n<p>We could use <code>EXIT_FAILURE</code> from <code>&lt;cstdlib&gt;</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T19:46:59.463", "Id": "533145", "Score": "1", "body": "Thanks for the review and good tips. Do you have any thoughts about wrapping `stackprog` in a class? I initially tried to do it with stand-alone functions in a `stackprog` namespace, but made a huge mess of the templates." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T19:53:03.800", "Id": "533146", "Score": "2", "body": "I was actually going to say \"it's all static functions and no state, so it could be a namespace\", but then I saw that it makes the templates easier. You could maybe make a couple of free functions: `template<class T> run(...);` that call `stackprog<T>::run()` and then the user wouldn't need to see `stackprog` at all." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T21:26:04.780", "Id": "533153", "Score": "1", "body": "*“if we used `std::vector<std::string_view>` we can avoid the copies”* It would still make copies of the pointers and call the equivalent of `strlen()` for every argument. You could make `run()` take a `std::span<const char *> args`, so you can call it like so: `run({argv, argv + argc})`, and in `parse()` do a `for (std::string_view arg: args) ...`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T15:45:35.810", "Id": "533208", "Score": "1", "body": "@G.Sliepen The advantage of using `string_view` instead of a `const char*` is that you don't have to re-check the length. The argument you use when looking up something in the map should already be a `string` or `string_view`, not (only) the pointer to the beginning of the split-out argument." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T19:33:15.437", "Id": "270076", "ParentId": "270065", "Score": "3" } } ]
{ "AcceptedAnswerId": "270076", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T13:10:57.793", "Id": "270065", "Score": "3", "Tags": [ "c++", "performance", "virtual-machine" ], "Title": "Simple stack based interpreter" }
270065
<p><code>wordify_number</code> is the main function. A lot of passes are being done over the list (rev, do something, rev again). Is there a way I can improve this?</p> <pre class="lang-ml prettyprint-override"><code>open Base ;; let named_numbers = [| &quot;zero&quot; ; &quot;one&quot; ; &quot;two&quot; ; &quot;three&quot; ; &quot;four&quot; ; &quot;five&quot; ; &quot;six&quot; ; &quot;seven&quot; ; &quot;eight&quot; ; &quot;nine&quot; ; &quot;ten&quot; ; &quot;eleven&quot; ; &quot;twelve&quot; ; &quot;thirteen&quot; ; &quot;fourteen&quot; ; &quot;fifteen&quot; ; &quot;sixteen&quot; ; &quot;seventeen&quot; ; &quot;eighteen&quot; ; &quot;nineteen&quot; |] ;; let tens = [| &quot;zero&quot; (* will not be used *) ; &quot;ten&quot; ; &quot;twenty&quot; ; &quot;thirty&quot; ; &quot;forty&quot; ; &quot;fifty&quot; ; &quot;sixty&quot; ; &quot;seventy&quot; ; &quot;eighty&quot; ; &quot;ninety&quot; |] ;; let power_name = [| None ; Some &quot;thousand&quot; ; Some &quot;million&quot; ; Some &quot;billion&quot; ; Some &quot;trillion&quot; ; Some &quot;quadrillion&quot; ; Some &quot;quintillion&quot; |] ;; let join_with_spaces = String.concat ~sep:&quot; &quot; ;; let (&lt;&lt;) = Fn.compose ;; let extract_digits number = let rec aux digits n = if n = 0 then digits else aux (n % 10 :: digits) (n / 10) in aux [] number ;; let rec group_to_words = function | [] -&gt; None | 0 :: digits -&gt; group_to_words digits | [digit] -&gt; Some [named_numbers.(digit)] | [1; digit] -&gt; Some [named_numbers.(digit+10)] | [tenth; 0] -&gt; Some [tens.(tenth)] | [tenth; first] -&gt; Some [tens.(tenth); named_numbers.(first)] | h :: (_::_ as digits) -&gt; Some ((named_numbers.(h) ^ &quot; hundred&quot;) :: (Option.value (group_to_words digits) ~default:[])) ;; let name_group p l = match power_name.(p) with | None -&gt; l | Some name -&gt; Option.map l (List.cons name) ;; let wordify_number = function | n when n &lt; 20 -&gt; named_numbers.(n) | n -&gt; let open List in n |&gt; extract_digits |&gt; rev |&gt; groupi ~break:(fun i _ _ -&gt; i % 3 = 0) |&gt; map ~f:(Option.map ~f:rev &lt;&lt; group_to_words &lt;&lt; rev) |&gt; rev_filter_mapi ~f:(name_group) |&gt; map ~f:(join_with_spaces &lt;&lt; rev) |&gt; join_with_spaces ;; let tests = [ (2000378 , &quot;two million three hundred seventy eight&quot;); (1000 , &quot;one thousand&quot;); (1040 , &quot;one thousand forty&quot;); (31089 , &quot;thirty one thousand eighty nine&quot;); (8000000 , &quot;eight million&quot;); (0 , &quot;zero&quot;); (178 , &quot;one hundred seventy eight&quot;); (118 , &quot;one hundred eighteen&quot;); (56 , &quot;fifty six&quot;); (1 , &quot;one&quot;); ] ;; let () = List.iter tests (fun (test, expected) -&gt; let status = match (String.equal expected (wordify_number test)) with | true -&gt; &quot;o&quot; | false -&gt; &quot;x&quot; in Stdio.print_endline (Printf.sprintf &quot;%s %d&quot; status test)) ;; </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T15:00:48.763", "Id": "270067", "Score": "0", "Tags": [ "ocaml" ], "Title": "A program to convert a number to words written in OCaml. Can I accomplish the same result with less number of passes?" }
270067
<p>In my .net core console application, I am reading a mail inbox and saving excel attachments from a specific sender that has a specific subject. It is working as is expected, I wonder if there are any improvements to make it better. So I would be glad if you can share your comments.</p> <p>Thanks in advance.</p> <pre><code>class Program { static void Main(string[] args) { using var client = new ImapClient(); client.Connect(&quot;imap.gmail.com&quot;, 993, true); client.Authenticate(&quot;test@gmail.com&quot;, &quot;12345&quot;); var inbox = client.Inbox; inbox.Open(FolderAccess.ReadWrite); var query = SearchQuery.FromContains(&quot;test@gmail.com&quot;) .And(SearchQuery.SubjectContains(&quot;101&quot;)).And(SearchQuery.NotSeen); foreach (var uid in inbox.Search(query)) { var message = inbox.GetMessage(uid); foreach (var attachment in message.Attachments) { if (attachment is MessagePart) { var fileName = attachment.ContentDisposition?.FileName; var rfc822 = (MessagePart)attachment; if (string.IsNullOrEmpty(fileName)) fileName = &quot;attached-message.eml&quot;; using var stream = File.Create(fileName); rfc822.Message.WriteTo(stream); } else { var part = (MimePart)attachment; var fileName = part.FileName; var file = Path.GetFileNameWithoutExtension(fileName); var newPath = fileName.Replace(file, file + &quot;-&quot;+ uid); Console.WriteLine(newPath); Console.WriteLine(uid); using var stream = File.Create(newPath); part.Content.DecodeTo(stream); } inbox.AddFlags(uid, MessageFlags.Seen, true); } } client.Disconnect(true); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T21:11:13.800", "Id": "533151", "Score": "0", "body": "Do you want your code to be compacted?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T07:31:55.427", "Id": "533173", "Score": "0", "body": "may be more maintainable :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T11:24:30.513", "Id": "533181", "Score": "0", "body": "Which version of C# are you using?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T11:29:38.427", "Id": "533183", "Score": "0", "body": "I am using VS 2019, latest version" } ]
[ { "body": "<p>Maintainability can mean different things for different developers. Here I will use <a href=\"https://www.brcline.com/blog/5-tips-write-maintainable-code\" rel=\"nofollow noreferrer\">this website</a>'s definition:</p>\n<blockquote>\n<p>Maintainable code is basically<br />\nthe amount of time it takes a developer to make a change and  <br />\nthe amount of risk that the change could break something.</p>\n</blockquote>\n<p> So from this perspective a <em>not maintainable</em> code means:</p>\n<ul>\n<li>either there is lots of effort to make changes</li>\n<li>or there is a high probability to break something</li>\n</ul>\n<hr />\n<p>What sort of changes can you expect?</p>\n<ul>\n<li>Be able to connect to other user's mailbox</li>\n<li>Be able read not just inbox, but other folders as well</li>\n<li>Be able to retrieve other messages not just the not seen ones</li>\n</ul>\n<p>Any of the above changes requires <strong>multiple</strong> adjustments on your code. That means more effort and higher probability to break something.</p>\n<p>Oneway to lower risk and minimize modification efforts is to</p>\n<ul>\n<li><strong>Group those things together which are semantically tight to each other</strong></li>\n<li><strong>Have some and well-focused reusable parts/components</strong></li>\n<li><strong>Use optional parameters with default values to make your code more flexible</strong></li>\n</ul>\n<hr />\n<p> \nIf you look at your code from 1000 feet high then you can see the following:</p>\n<ul>\n<li>Connect to a mailbox</li>\n<li>Select a folder</li>\n<li>Issue a search query</li>\n<li>Iterate through the messages</li>\n<li>Handle attachments based on their type</li>\n</ul>\n<p>So, your <code>main</code> should follow this same level of abstraction:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>static void Main()\n{\n    using var client = ConnectToMailbox();\n    var folder = SelectFolder(client);\n \n    foreach (var messageId in IssueSearch(folder))\n    foreach (var attachment in folder.GetMessage(messageId).Attachments)\n    {\n        _ = attachment switch\n        {\n            MessagePart messagePart =&gt; HandleMessagePart(messagePart),\n            MimePart mimePart =&gt; HandleMimePart(mimePart, messageId),\n            _ =&gt; throw new NotSupportedException(&quot;Attachment is unknown&quot;)\n        };\n \n        folder.AddFlags(messageId, MessageFlags.Seen, true);\n    }\n}\n</code></pre>\n<p>Each of the methods are well focused and have small responsibilities. So, any of the above changes are localized (<em>there is a single and easy spot place to do adjustments</em>).</p>\n<h3>Connect to a mailbox </h3>\n<pre><code>
ImapClient ConnectToMailbox(\n    string host = &quot;imap.gmail.com&quot;, int port = 993, bool useSsl = true,\n    string username = &quot;test@gmail.com&quot;, string pwd = &quot;12345&quot;)\n{\n    var client = new ImapClient();\n    client.Connect(host, port, useSsl);\n    client.Authenticate(username, pwd);\n    return client;\n}\n</code></pre>\n<h3>Select a folder</h3>\n<pre><code>IMailFolder SelectFolder(ImapClient client, SpecialFolder? folder = null)\n{\n    var inbox = folder.HasValue ? client.GetFolder(folder.Value): client.Inbox;\n    inbox.Open(FolderAccess.ReadWrite);\n    return inbox;\n}\n</code></pre>\n<h3>Issue a search query</h3>\n<pre><code>IList&lt;UniqueId&gt; IssueSearch(IMailFolder inbox,\n    string from = &quot;test@gmail.com&quot;,\n    string subject = &quot;101&quot;,\n    SearchQuery? filter = null)\n{\n    var query = SearchQuery.FromContains(from)\n        .And(SearchQuery.SubjectContains(subject))\n        .And(filter ?? SearchQuery.NotSeen);\n    return inbox.Search(query);\n}\n</code></pre>\n<h3>Handle attachments based on their type</h3>\n<pre><code>MimeEntity HandleMessagePart(MessagePart attachment)\n{\n    var fileName = attachment.ContentDisposition?.FileName;\n \n    if (string.IsNullOrEmpty(fileName))\n        fileName = &quot;attached-message.eml&quot;;\n \n    using var stream = File.Create(fileName);\n    attachment.Message.WriteTo(stream);\n    return attachment;\n}\n\nMimeEntity HandleMimePart(MimePart attachment, UniqueId uid)\n{\n    var fileName = attachment.FileName;\n    var file = Path.GetFileNameWithoutExtension(fileName);\n    var newPath = fileName.Replace(file, $&quot;{file}-{uid}&quot;);\n    Console.WriteLine(newPath);\n    Console.WriteLine(uid);\n \n    using var stream = File.Create(newPath);\n    attachment.Content.DecodeTo(stream);\n    return attachment;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T12:24:15.433", "Id": "270093", "ParentId": "270068", "Score": "2" } } ]
{ "AcceptedAnswerId": "270093", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T15:10:52.767", "Id": "270068", "Score": "1", "Tags": [ "c#", ".net-core" ], "Title": "Reading inbox from a specific sender and for a specific subject in order to save excel attachments" }
270068
<p><strong>Main Questions:</strong></p> <ul> <li>Is my runtime analysis correct?</li> <li>Is my approach optimal or close to it?</li> <li>Is there a better way and/or improvements?</li> </ul> <p><strong>Objective:</strong></p> <ul> <li>Write an algorithm to assign <code>n</code> jobs to <code>k</code> entities (servers, cpus, whatever) in a round robin fashion. The job that takes longest will be assign first, the shortest last. In the case of a tie, the job with lowest id will be assigned first.</li> <li>return the job ids assigned to each entity, where an entity can be represented as a list</li> </ul> <p>sample input:</p> <ul> <li><code>jobs= [40, 80,40, 4, 2]</code></li> <li>entities = 2</li> <li>where <code>jobs[i]</code> is the length of time the task, and <code>i</code> is its identifier.</li> </ul> <p>sample output:</p> <ul> <li>[[1, 2, 4], [0, 3]]</li> </ul> <p>I came up with two algorithms and wanted to see if my runtime analysis is correct, and if there is a better way to approach this</p> <h3>Implementation 1: Linear Search</h3> <p><strong>Pseudocode:</strong></p> <ul> <li>linear search for the longest job, from left to right, saving its job id (index)</li> <li>only update the index if we find a larger job in list</li> <li>once we find it assign to another list, which will contain the jobs in order</li> <li>iterate over the ordered list, assigning to each server in round robin fashion</li> </ul> <p><strong>Hypothesis for runtime:</strong></p> <ul> <li>time proportional to <code>n ^ 2</code>, where <code>n</code> are the number of jobs</li> </ul> <p><strong>Code</strong></p> <pre class="lang-py prettyprint-override"><code> def findMax(jobs): ind_of_max = 0 ### iterate over jobs for k in range(len(jobs)): # if current job we are processing is greater than the previous lomgest job if jobs[k] &gt; jobs[ind_of_max]: ind_of_max = k # sinonimouns to removing the job from the PQ jobs[ind_of_max] = -1 return ind_of_max def determineJobOrder(jobs): # list of jobIds order_of_jobs = [] num_of_jobs = len(jobs) #### TOTAL RUNTIME ANALYSIS: # - runs in time proportional to N ^ 2 #### # runs in time proportional to N while num_of_jobs &gt; 0: # removing jobs from list (aka performing dequeue operations until we run out of jobs) # runs in time proportional to N ind_of_max = findMax(jobs) order_of_jobs.append(ind_of_max) num_of_jobs -= 1 return order_of_jobs def assignJobsToServers(servers, jobs): jobs = determineJobOrder(jobs) # create a list of lists, where the number of inner lists = number of servers assignment = [[] for i in range(0, servers)] num_jobs = len(jobs) job_ind = 0 server_ind = 0 ### ### RUNTIME ANALYSIS: # - runs in time proportional to n #while there are jobs left to assign while num_jobs &gt; 0: assignment[server_ind % servers].append(jobs[job_ind]) # update server index, job index, and number of jobs left to assign num_jobs -= 1 job_ind += 1 server_ind += 1 return assignment </code></pre> <h3>Implementation 2: Using Heap</h3> <p><strong>Pseudocode:</strong></p> <ul> <li>Iterate over all jobs, creating a Job object, Job(job_id, time)</li> <li>Since python's <code>heapq</code> class is a min heap, I use <code>heapq.nlargest</code>, passing a key for comparison, the list of Jobs</li> </ul> <p><strong>Hypothesis of runtime:</strong></p> <ul> <li>time proportional to <code>n log n</code>, where n are the number of jobs</li> </ul> <p><strong>Code:</strong></p> <pre class="lang-py prettyprint-override"><code> ## To enncapsulate the jobs and be able to compare by multiple attributes class Job: def __init__(self, job_id, time): self.job_id = job_id self.time = time def __repr__(self): return 'Job(id: {}, time: {})'.format(self.job_id, self.time) import heapq def assignJobsToServers(servers, jobs): for k, exec_time in enumerate(jobs): jobs[k] = Job(k, exec_time) # resource used to figure out how to sort by two attributes, one in natural order one in reverse: # https://www.techiedelight.com/sort-list-of-objects-by-multiple-attributes-python/ #### Runtime Analysis: # - I am assuming that what this will do is build the max heap, and then remove the n items to get them in max order. # - Inserts into heap take log (n). # - removals take log(n) # - if we are enqueueing n items, this will take n log n # - if we are removing n items, this will take n log n for removals # - hence: runtime should be proportional n log n, ignoring constants #### # key defines that that the larger the time the larger the, and on a tie, the smallest the job id the largest the item jobs_ordered = heapq.nlargest(len(jobs), jobs, key = lambda job: (job.time, -job.job_id)) # create a list of lists, where the number of inner lists = number of servers assignments = [[] for i in range(0, servers)] num_jobs = len(jobs) server_ind = 0 job_ind = 0 ###### RUNTIME ANALYSIS: # - at this point we already did all the difficult computation. We now just iterate over all jobs which will be in order and assign # - this takes time proportional to n, the number of jobs while num_jobs &gt; 0: assignments[server_ind % servers].append(jobs_ordered[job_ind].job_id) # update server index, and number of jobs left to assign num_jobs -= 1 server_ind += 1 job_ind += 1 return assignments </code></pre>
[]
[ { "body": "<p>Your runtime analysis seems fine and your heap-based approach is optimal in the\nnarrow sense that it achieves <code>O(n log n)</code> performance. However, the software\nitself is needlessly complex.</p>\n<p>The path to simplicity is found by remembering the most famous <code>O(n log n)</code>\noperation: <strong>sorting</strong>. You have a list of job durations that you\nwant to sort from largest to smallest, breaking ties via their ID/index. There\nare a variety of reasonable ways to achieve that. Here's one illustration:</p>\n<pre><code># Some job durations and a generator to produce (DURATION, ID) pairs.\ndurations = [40, 80, 40, 4, 2]\npairs = enumerate(durations)\n\n# A function to take a pair and return a modified pair for sorting purposes.\nsort_key = lambda pair: (-pair[1], pair[0])\n\n# Sort the pairs and extract job IDs from them.\njob_ids = [jid for jid, dur in sorted(pairs, key = sort_key)]\n\n# Allocate the job IDs to N workers/entities in round-robin fashion.\nn = 2\nallocated_job_ids = [job_ids[i::n] for i in range(n)]\nprint(allocated_job_ids) # [[1, 2, 4], [0, 3]]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T12:17:02.147", "Id": "533257", "Score": "0", "body": "got it. not sure why that did not come to mind but that would definitely be simpler in this case, Thank you. Would a PQ implemented with Heap be preferred in the case our list of jobs is not static , meaning, let's say, two jobs can be added to the initial list, then 1 remove, followed by more additions and removals interleaved? it seems like in that case we couldn't achieve n log n for both removals and additions. What do you think?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T15:57:04.967", "Id": "533273", "Score": "1", "body": "@MPC Correct. The superpower of a heap is its log-n ability to maintain sorted order in the face of inserts/removals." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T20:50:52.737", "Id": "270079", "ParentId": "270071", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T16:19:29.760", "Id": "270071", "Score": "0", "Tags": [ "python", "algorithm", "heap", "priority-queue" ], "Title": "Assigning Tasks to Entities (or some other entity) based on Priority" }
270071
<p>I'm a Python newbie and I made this GUI dictionary using PyDictionary module, it took me long though, I can sense that the if conditions are really unpractical and ugly, but I couldn't find a way to shorten that part of the code, any recommendations will be highly appreciated.</p> <pre><code>from tkinter import * from PyDictionary import PyDictionary root = Tk() root.geometry(&quot;450x550&quot;) root.columnconfigure(0, weight=1) root.config(bg=&quot;black&quot;) def space(): space = Label(text=&quot;&quot;, bg=&quot;black&quot;) space.grid() def find_meaning(): word = entry.get() dictionary = PyDictionary(word) definition = dictionary.getMeanings() print(definition) label = &quot;&quot; try: if &quot;Verb&quot; in definition[word]: label = &quot;Verb: &quot; + definition[word][&quot;Verb&quot;][0] if &quot;Noun&quot; in definition[word]: label = &quot;Noun: &quot; + definition[word][&quot;Noun&quot;][0] if &quot;Adverb&quot; in definition[word]: label = &quot;Adverb: &quot; + definition[word][&quot;Adverb&quot;][0] if &quot;Noun&quot; in definition[word] and &quot;Adverb&quot; in definition[word]: label = &quot;Noun: &quot; + definition[word][&quot;Noun&quot;][0] + &quot; \n\n &quot; + &quot;Adverb: &quot; + definition[word][&quot;Adverb&quot;][0] if &quot;Noun&quot; in definition[word] and &quot;Adjective&quot; in definition[word] and &quot;Adverb&quot; in definition[word]: label = &quot;Noun: &quot; + definition[word][&quot;Noun&quot;][0] + &quot; \n\n &quot; + &quot;Adjective: &quot; + definition[word][&quot;Adjective&quot;][0] + &quot; \n\n &quot; + &quot;Adverb: &quot; + definition[word][&quot;Adverb&quot;][0] if &quot;Adjective&quot; in definition[word]: label = &quot;Adjective: &quot; + definition[word][&quot;Adjective&quot;][0] if &quot;Noun&quot; in definition[word] and &quot;Adjective&quot; in definition[word] and &quot;Adverb&quot; in definition[word] and &quot;Verb&quot; in definition[word]: label = &quot;Noun: &quot; + definition[word][&quot;Noun&quot;][0] + &quot; \n\n &quot; + &quot;Adjective: &quot; + definition[word][&quot;Adjective&quot;][ 0] + &quot; \n\n &quot; + &quot;Adverb: &quot; + definition[word][&quot;Adverb&quot;][0] + &quot; \n\n &quot; + &quot;Verb: &quot; + definition[word][&quot;Verb&quot;][0] if &quot;Verb&quot; in definition[word] and &quot;Noun&quot; in definition[word]: label = &quot;Noun: &quot; + definition[word][&quot;Noun&quot;][0] + &quot; \n\n &quot; + &quot;Verb: &quot; + definition[word][&quot;Verb&quot;][0] if &quot;Noun&quot; in definition[word] and &quot;Adjective&quot; in definition[word]: label = &quot;Noun: &quot; + definition[word][&quot;Noun&quot;][0] + &quot; \n\n &quot; + &quot;Adjective: &quot; + definition[word][&quot;Adjective&quot;][0] if &quot;Adjective&quot; in definition[word] and &quot;Verb&quot; in definition[word]: label = &quot;Adjective: &quot; + definition[word][&quot;Adjective&quot;][0] + &quot; \n\n &quot; + &quot;Verb: &quot; + definition[word][&quot;Verb&quot;][0] except Exception: label = &quot;Wrong word entered!&quot; return label def write(): label.config(text=find_meaning()) entry.delete(0, END) space() dic_text = Label(root, text=&quot;Dictionary&quot;, fg=&quot;#3dcc8e&quot;, bg=&quot;black&quot;, font=(&quot;arial&quot;, 15, &quot;bold&quot;)) dic_text.grid() space() entry = Entry(root, font=(&quot;times&quot;, 15, &quot;bold&quot;)) entry.grid() space() btn = Button(root, text=&quot;Find Meaning&quot;, command=lambda: [find_meaning(), write()]) btn.grid() space() label = Label(root, text=&quot;Translation&quot;, background=&quot;#3e3e3e&quot;, width=40, height=21, relief=FLAT, state=DISABLED, disabledforeground=&quot;#3dcc8e&quot;, wraplength=200, justify=LEFT) label.grid() root.mainloop() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T07:37:17.270", "Id": "533246", "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": "2021-11-17T09:57:19.287", "Id": "533313", "Score": "0", "body": "@Katkoota \"hire some people to do that for you\". The site is run by volunteers. However, I'm sure people would be happy to go the extra mile you're demanding if _you_ pay them." } ]
[ { "body": "<p>Sure; you've got the right idea. Start by writing the code as repetitively as possible, then factor out the repetitive bits. Your first three lines are of the form</p>\n<pre><code>if partOfSpeech in definition[word]:\n label = &quot;{}: &quot;.format(partOfSpeech) + definition[word][partOfSpeech][0]\n</code></pre>\n<p>So, factor that out into a function!</p>\n<pre><code>def maybeSetSingleLabel(partOfSpeech):\n if partOfSpeech in definition[word]:\n label = &quot;{}: &quot;.format(partOfSpeech) + definition[word][partOfSpeech][0]\n\nmaybeSetSingleLabel(&quot;Verb&quot;)\nmaybeSetSingleLabel(&quot;Noun&quot;)\nmaybeSetSingleLabel(&quot;Adverb&quot;)\n</code></pre>\n<p>And then refactor into a loop:</p>\n<pre><code>for partOfSpeech in [&quot;Verb&quot;, &quot;Noun&quot;, &quot;Adverb&quot;]:\n maybeSetSingleLabel(partOfSpeech)\n</code></pre>\n<p>And then repeat the process for the next few lines:</p>\n<pre><code>def maybeSetDoubleLabel(pos1, pos2):\n if pos1 in definition[word] and pos2 in definition[word]:\n label = &quot;\\n\\n&quot;.join(\n &quot;{}: &quot;.format(pos1) + definition[word][pos1][0],\n &quot;{}: &quot;.format(pos2) + definition[word][pos2][0],\n )\n\nmaybeSetDoubleLabel(&quot;Noun&quot;, &quot;Adverb&quot;)\nmaybeSetSingleLabel(&quot;Adjective&quot;)\nmaybeSetDoubleLabel(&quot;Verb&quot;, &quot;Noun&quot;)\nmaybeSetDoubleLabel(&quot;Noun&quot;, &quot;Adjective&quot;)\nmaybeSetDoubleLabel(&quot;Adjective&quot;, &quot;Verb&quot;)\n</code></pre>\n<p>...Hey, that single <code>&quot;Adjective&quot;</code> case is out of order! We should move it up with the other three single-label cases.</p>\n<p>And then we could do the same for triple and quadruple labels. But maybe at this point we should look at reducing the repetition again. We have some repetition here parameterized on the <em>number</em> of labels as well as their string values. So let's make a general-purpose <code>maybeSetLabels</code> function!</p>\n<pre><code>def maybeSetLabels(poses):\n if all(pos in definition[word] for pos in poses):\n label = &quot;\\n\\n&quot;.join([\n &quot;{}: &quot;.format(pos) + definition[word][pos][0] for pos in poses\n ])\n\nmaybeSetLabels([&quot;Verb&quot;])\nmaybeSetLabels([&quot;Noun&quot;])\nmaybeSetLabels([&quot;Adverb&quot;])\nmaybeSetLabels([&quot;Adjective&quot;])\nmaybeSetLabels([&quot;Noun&quot;, &quot;Adverb&quot;])\nmaybeSetLabels([&quot;Verb&quot;, &quot;Noun&quot;])\nmaybeSetLabels([&quot;Noun&quot;, &quot;Adjective&quot;])\nmaybeSetLabels([&quot;Adjective&quot;, &quot;Verb&quot;])\nmaybeSetLabels([&quot;Noun&quot;, &quot;Adjective&quot;, &quot;Adverb&quot;])\nmaybeSetLabels([&quot;Noun&quot;, &quot;Adjective&quot;, &quot;Adverb&quot;, &quot;Verb&quot;])\n</code></pre>\n<p>...Hmm, you're missing some combinations. For example, <code>[&quot;Noun&quot;, &quot;Verb&quot;, &quot;Adverb&quot;]</code> is missing. Let's just have the computer generate the combinations for us! Computers are good at that.</p>\n<pre><code>def all_subsets_of(words):\n for r in range(len(words)):\n for subset in itertools.combinations(words, r+1):\n yield subset\n\nfor poses in all_subsets_of([&quot;Adjective&quot;, &quot;Adverb&quot;, &quot;Noun&quot;, &quot;Verb&quot;]):\n maybeSetLabels(poses)\n</code></pre>\n<p>And now that there's only one call to <code>maybeSetLabels</code>, we can re-inline its code:</p>\n<pre><code>def all_subsets_of(words):\n for r in range(len(words)):\n for subset in itertools.combinations(words, r+1):\n yield subset\n\nlabel = &quot;&quot;\nfor poses in all_subsets_of([&quot;Adjective&quot;, &quot;Adverb&quot;, &quot;Noun&quot;, &quot;Verb&quot;]):\n if all(pos in definition[word] for pos in poses):\n label = &quot;\\n\\n&quot;.join([\n &quot;{}: &quot;.format(pos) + definition[word][pos][0] for pos in poses\n ])\n</code></pre>\n<p>There are other ways to tackle the problem, too, depending on the shape of your data. For example, if every key in <code>definition[word]</code> is a part of speech that you're trying to put into the label, then you could just do this one line:</p>\n<pre><code>label = &quot;\\n\\n&quot;.join([\n &quot;{}: &quot;.format(pos) + definition[word][pos][0] for pos in definition[word]\n])\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T13:06:08.380", "Id": "533199", "Score": "1", "body": "Thank you very much for your great and detailed answer, I'm sure it will benefit a lot of advanced developers!, however, it is a bit hard for me to understand all that :( but thanks anyway sir <3" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T05:42:49.103", "Id": "270087", "ParentId": "270080", "Score": "1" } }, { "body": "<p>One way to clean up the <code>Verb/Noun/Adverb/Adjective</code> <code>if</code> blocks would be to handle each type independently of one another. Using a list to &quot;collect&quot; each definition grouped by type, you can then use <a href=\"https://docs.python.org/3/library/stdtypes.html#str.join\" rel=\"nofollow noreferrer\"><code>.join</code></a> to place <code>\\n\\n</code> in between each definition type.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def find_meaning():\n word = entry.get()\n dictionary = PyDictionary(word)\n definition = dictionary.getMeanings()\n # Set up an empty list to hold our definitions\n label_list = []\n if &quot;Noun&quot; in definition[word]:\n label_list.append(&quot;Noun: &quot; + definition[word][&quot;Noun&quot;][0])\n if &quot;Verb&quot; in definition[word]:\n label_list.append(&quot;Verb: &quot; + definition[word][&quot;Verb&quot;][0])\n if &quot;Adjective&quot; in definition[word]:\n label_list.append(&quot;Adjective: &quot; + definition[word][&quot;Adjective&quot;][0])\n if &quot;Adverb&quot; in definition[word]:\n label_list.append(&quot;Adverb: &quot; + definition[word][&quot;Adverb&quot;][0])\n # After each word form definition has been added,\n # join them together with two new lines in between each definition\n label = &quot;\\n\\n&quot;.join(label_list)\n return label\n</code></pre>\n<p><strong>Edit</strong></p>\n<p>I wanted to expand on the comment made by <a href=\"https://codereview.stackexchange.com/users/4612/fmc\">@FMc</a> as it is still possible to shorten the code:</p>\n<blockquote>\n<p>Also notice that <code>definition[word]</code> is used many times. A short convenience variable would lighten up the visual weight of the code, enhancing readability: <code>defin = dictionary.getMeanings()[word]</code></p>\n</blockquote>\n<p>Modifying my original code to include these suggestions could look like the following:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def find_meaning():\n word = entry.get()\n dictionary = PyDictionary(word)\n defin = dictionary.getMeanings()[word]\n # Set up an empty list to hold our definitions\n label_list = []\n if &quot;Noun&quot; in defin:\n label_list.append(&quot;Noun: &quot; + defin[&quot;Noun&quot;][0])\n if &quot;Verb&quot; in defin:\n label_list.append(&quot;Verb: &quot; + defin[&quot;Verb&quot;][0])\n if &quot;Adjective&quot; in defin:\n label_list.append(&quot;Adjective: &quot; + defin[&quot;Adjective&quot;][0])\n if &quot;Adverb&quot; in defin:\n label_list.append(&quot;Adverb: &quot; + defin[&quot;Adverb&quot;][0])\n # After each word form definition has been added,\n # join them together with two new lines in between each definition\n label = &quot;\\n\\n&quot;.join(label_list)\n return label\n</code></pre>\n<p>Notice how the readability is not lost, but possibly improved so long as the intent is easy to understand to other reviewers.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T13:07:14.033", "Id": "533201", "Score": "1", "body": "Wow, this is great and easy to understand, thank you very much!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T18:28:20.617", "Id": "533218", "Score": "1", "body": "The suggestions here are good (+1). Also notice that `definition[word]` is used many times. A short convenience variable would lighten up the visual weight of the code, enhancing readability: `defin = dictionary.getMeanings()[word]`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T05:52:20.893", "Id": "270088", "ParentId": "270080", "Score": "1" } } ]
{ "AcceptedAnswerId": "270088", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T21:06:01.487", "Id": "270080", "Score": "-1", "Tags": [ "python", "tkinter" ], "Title": "How possible it is to shorten repetitive if-statements in Python?" }
270080
<p>I have a survey response dataframe for which each survey has a <code>code</code>:</p> <p><code>df</code></p> <pre><code> code item_stamp question_name question_type scorable_question subquestion_name stage products_stamp product_ID answer_name respondent_id answers_identity answer Test Code 0 006032 '173303553131045' Age group single 1.0 NaN Screener NaN &lt;NA&gt; 31 - 45 '173303561331047' '11357427731020' 2 6032 1 006032 '173303553131045' Age group single 1.0 NaN Screener NaN &lt;NA&gt; 31 - 45 '173303561431047' '11357427731020' 2 6032 </code></pre> <p>I also have a dataframe with the types of each survey that are identified with <code>Test Code</code> :</p> <p><code>df_synthesis_clean</code></p> <pre><code> Country Country Code Category Application Gender Program Evaluation Stage Context Packaging Code Test Code Test Completion Agency Deadline Product Type Line Extension Dosage Fragrance House_ID product_ID Liking Mean Liking Scale Olfactive Family Olfactive Subfamily OLFACTIVE CLUSTER EASY FRESH TEXTURED WARM SIGNATURE QUALIFICATION VERT ORANGE ROUGE TOP SELLER TOP TESTER 0 France FR Fine Men Fragrances Perf/Edt/A-Shave/Col (FM) M scent hunter clst - sniff - on glass ball jar Blind NaN 3879 4/15/2016 0:00 NaN Market Product EDT 12.0 817.0 8082451124 5.55 0 to 10 WOODY Floral TEXTURED WARM NaN NaN NaN NaN 1 USA US Fine Men Fragrances Perf/Edt/A-Shave/Col (FM) M scent hunter clst - sniff - on glass ball jar Blind NaN 3855 4/15/2016 0:00 NaN Market Product EDT 12.0 817.0 8082451124 4.88 0 to 10 WOODY Floral TEXTURED WARM NaN NaN NaN NaN </code></pre> <p>I want to add a column about the type of Program that caused the response (Flash or non-flash).</p> <p>I have the test id in df and the test type in <code>df_synthesis_clean</code>. So I tried in a Google collaboratory without GPU (because I don't know how to use it):</p> <pre><code>for _, row in df.iterrows(): # I will look in the df_synthesis_clean table to see if the row['code'] corresponds to a Test Code. # I have to put iloc 0 because a study corresponds to several tested products but the respuestas no tienen program = df_synthesis_clean.loc[df_synthesis_clean['Test Code'] == row['code']].iloc[0]['Program'] row['Program'] = program </code></pre> <p>It works on small amount of data but unfortunately I now have more than <strong>three million lines</strong> in <code>df</code> so that's why it takes a long time.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-27T17:34:58.157", "Id": "534092", "Score": "0", "body": "Did my suggestion work for you?" } ]
[ { "body": "<p>Iterating over the rows of a data frame is usually very slow.\nFor combining the values of two data frames you can instead use <a href=\"https://pandas.pydata.org/docs/reference/api/pandas.merge.html\" rel=\"nofollow noreferrer\">pandas.merge</a> like this</p>\n<pre><code>import pandas as pd\ncols = ['Test Code', 'Program']\npd.merge(df, df_synthesis_clean[cols], left_on='code', right_on='Test Code')\n</code></pre>\n<p>When using <code>pd.merge</code>, take care to choose the correct value for the optional parameter <code>how</code>. By default, only the rows corresponding to keys that are present in both data frames will be part of the resulting data frame. But you might want to change that according to your needs.</p>\n<p>Please let me know if it works. Unfortunately, I cannot test my code at the moment.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T12:36:55.087", "Id": "270157", "ParentId": "270081", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T22:52:51.110", "Id": "270081", "Score": "0", "Tags": [ "python", "performance", "python-3.x", "pandas" ], "Title": "How to speed up the search for matching values in a second data frame in a line-by-line iteration over a first data frame?" }
270081
<p>(reposted from another forum, <a href="https://artofproblemsolving.com/community/c163h2712829_python_table_improvements" rel="nofollow noreferrer">AoPS</a>)</p> <p>I have made a &quot;Table&quot; data structure with fast mean, median, and mode calculations. To my knowledge there's no built-in function that does this. Here's my code, suggest improvements.</p> <pre><code>''' Please do not use without citing. Basically a dictionary only with functionalities of adding and extending but can calculate the average, median, and mode. Typical dictionary: O(K) initiation O(1) set_item O(1) get_item O(K) extend O(N) average O(NlogN) median (Techincally O(N), but in practice slower) O(K) mode This dictionary: O(K) initiation O(logN) set_item O(1) get_item O(KlogK) extend O(1) average O(1) median O(1) mode So as you can see this data structure is quite useful when you need to frequently calculate the average, median, and mode. ''' from collections import Counter class Table: def __init__(self, d = {}): self.heaps = [], [] self.d = d self.mean = sum(d) / len(d) if len(d) &gt; 0 else 0 self.count = Counter(d.values()) self.mode_key, self.mode_val = [None], 0 def contents(self): return self.d def average(self): return self.mean def median(self): small, large = self.heaps if len(large) &gt; len(small): return float(large[0]) return (large[0] - small[0]) / 2.0 def mode(self): return self.mode_key def index(self, key): return self.d[key] def add(self, key, val): if key in self.d: return #mean updating self.mean = (len(self.d) * self.mean + val) / (len(self.d) + 1) #median updating small, large = self.heaps heappush(small, -heappushpop(large, val)) if len(large) &lt; len(small): heappush(large, -heappop(small)) #mode updating self.d[key] = val self.count[val] += 1 if self.count[val] == self.mode_val: self.mode_key.append(val) elif self.count[val] &gt; self.mode_val: self.mode_key = [val] self.mode_val = self.count[val] def extend(self, d): #mean updating self.mean = (len(self.d) * self.mean + sum(d.values())) / (len(self.d) + len(d)) for key, val in d.items(): if key in self.d: continue #median updating small, large = self.heaps heappush(small, -heappushpop(large, val)) if len(large) &lt; len(small): heappush(large, -heappop(small)) #mode updating self.d[key] = val self.count[val] += 1 if self.count[val] == self.mode_val: self.mode_key.append(val) elif self.count[val] &gt; self.mode_val: self.mode_key = [val] self.mode_val = self.count[val] #Showcasing d = Table() d.add(1, 1) print(d) print(d.contents()) d.extend({3:9, 2:4}) print(d.contents()) print(d.median()) print(d.average()) print(d.mode()) d.add(4, 1) print(d.mode()) print(d.contents()) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T17:55:02.837", "Id": "533280", "Score": "0", "body": "Is there a reason why you are not using `@property` and `@set.property`? See https://stackoverflow.com/questions/2627002/whats-the-pythonic-way-to-use-getters-and-setters. Also the statistics module implements everything you did with more https://docs.python.org/3/library/statistics.html. Hopwever, if you are a beginner and want to learn Python by reinventing the wheel that is fine =)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-14T23:46:51.453", "Id": "270083", "Score": "0", "Tags": [ "python-3.x" ], "Title": "Python 3 Table Improvements" }
270083
<p>I've completed this as part of an online programming course (in which code review is supposed to be done by fellow learners, but it's been a very long time and none of them have reviewed this), and here are the specifics:</p> <blockquote> <p>Prompt</p> <p>Use a struct to define a card as an enumerated member that is its suit value and a short that is its pips value.</p> <p>Write a function that randomly shuffles the deck.</p> <p>Submit your work as a text file.</p> <p>Then deal out 7 card hands and evaluate the probability that a hand has no pair, one pair, two pair, three of a kind, full house and 4 of a kind. This is a Monte Carlo method to get an approximation to these probabilities. Use at least 1 million randomly generated hands. (The prompt wants us to find the probability of no pair, but doesn't give us a reference value in the standard table.)</p> <p>You can check against probabilities found in a standard table.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Hand</th> <th>Combinations</th> <th>Probabilities</th> </tr> </thead> <tbody> <tr> <td>Royal flush</td> <td>4324</td> <td>0.00003232</td> </tr> <tr> <td>Straight flush</td> <td>37260</td> <td>0.00027851</td> </tr> <tr> <td>Four of a kind</td> <td>224848</td> <td>0.00168067</td> </tr> <tr> <td>Full house</td> <td>3473184</td> <td>0.02596102</td> </tr> <tr> <td>Flush</td> <td>4047644</td> <td>0.03025494</td> </tr> <tr> <td>Straight</td> <td>6180020</td> <td>0.04619382</td> </tr> <tr> <td>Three of a kind</td> <td>6461620</td> <td>0.04829870</td> </tr> <tr> <td>Two pair</td> <td>31433400</td> <td>0.23495536</td> </tr> <tr> <td>Pair</td> <td>58627800</td> <td>0.43822546</td> </tr> <tr> <td>Ace high or less</td> <td>23294460</td> <td>0.17411920</td> </tr> <tr> <td>Total</td> <td>133784560</td> <td>1.00000000</td> </tr> </tbody> </table> </div></blockquote> <p>Here's my code:</p> <pre><code>/* A program that shuffles a deck of cards, and deals 1.4 million 7 card hands, to determine the probability of certain hand types. By John November 8 2021 */ #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include&lt;time.h&gt; #define DECK_SIZE 52 //to be used to randomly select each of 52 cards #define SUITS_PLUS_ONE 5 //to be used to generate any of the 4 suits #define PIPS_PLUS_ONE 14 //to be used to generate any of the 13 pips #define DECKS_NUMBER 200000 //this * 7 hands per deck = 1.4 million hands #define HANDS_NUMBER 1400000 #define HAND_SIZE 7 typedef enum suit { hearts, diamonds, spades, clubs } suit; typedef struct playing_card { suit suit; short pip; } card; card * shuffles_deck(card * ptr_to_deck, card * ptr_to_shuffled) //shuffles the deck { int element_numbers[52]; //keeps track of selected cards to avoid repetition int value = 53; //use to initalize the above array with number &gt; 52 for(int m = 0; m &lt; 52; m++) { element_numbers[m] = value; //filling the array with value not in deck } for(int i = 0; i &lt; 52; i++) { int which_element = rand() % DECK_SIZE; int original_i = i; // to keep track of i's value so far for(int k = 0; k &lt; 52; k++) { if(element_numbers[k] == which_element) //ie: if card drawn before { i--; } } if(original_i == i) //if i wsn't decremented = card not drawn before { element_numbers[i] = which_element; *(ptr_to_shuffled + i) = *(ptr_to_deck + which_element); } } return ptr_to_shuffled; } card * deals_hand(card * ptr_to_hand, card * ptr_to_shuffled) //deals each hand and organizes cards by ascending pip value { static int j = 0; int i = 0; card swapper_card; for( ; i &lt; 7; i++) { *(ptr_to_hand + i) = *(ptr_to_shuffled + j); j++; } for(int index = 0; index &lt; 7; index++) { for(int k = 0; k &lt; 6; k++) { if((ptr_to_hand + (k+1))-&gt;pip &lt; (ptr_to_hand + k)-&gt;pip) { swapper_card = *(ptr_to_hand + (k+1)); *(ptr_to_hand + (k+1)) = *(ptr_to_hand + k); *(ptr_to_hand + k) = swapper_card; } } if((ptr_to_hand + 6)-&gt;pip &gt;= (ptr_to_hand + 5)-&gt;pip &amp;&amp; (ptr_to_hand + 5)-&gt;pip &gt;= (ptr_to_hand+4)-&gt;pip &amp;&amp; (ptr_to_hand + 4)-&gt;pip &gt;= (ptr_to_hand + 3)-&gt;pip &amp;&amp; (ptr_to_hand + 3)-&gt;pip &gt;= (ptr_to_hand + 2)-&gt;pip &amp;&amp; (ptr_to_hand + 2)-&gt;pip &gt;= (ptr_to_hand + 1)-&gt;pip &amp;&amp; (ptr_to_hand + 1)-&gt;pip &gt;= (ptr_to_hand + 0)-&gt;pip) { break; } } if(j == 49) // meaning if j has reached the 50th card after which there is no more complete hand to be drawn from the deck { j = 0; } return ptr_to_hand; } void hand_determinator( card * ptr_to_hand) //determines what each hand contains (er: no pair, pair, etc.) { static int how_many_hands = 0; //when 1000005, calculate probabilities. static int no_pair = 0, one_pair = 0, three_of_kind = 0; static int two_pair = 0, four_of_kind = 0, full_house = 0; int first_type_counter = 1; int second_type_counter = 1; card *first_type = (card *) calloc(1, sizeof(card)); card *second_type = (card *) calloc(1, sizeof(card)); if(first_type == NULL || second_type == NULL) { exit(1); } how_many_hands ++; if(how_many_hands &lt; HANDS_NUMBER) { for(int i = 0; i &lt;HAND_SIZE; i++) { if( (second_type + 0)-&gt;pip == 0) //since calloc will initialize the pip value with 0 { if(i == 0) { *(first_type + 0) = *(ptr_to_hand + i); } else { if( (first_type + 0)-&gt;pip == (ptr_to_hand + i)-&gt;pip) { first_type_counter ++; first_type = realloc(first_type, first_type_counter * sizeof(card)); *(first_type + (first_type_counter - 1)) = *(ptr_to_hand + i); } else { if(first_type_counter == 1) { *(first_type + 0) = *(ptr_to_hand + i); } else if(first_type_counter &gt; 1) { *(second_type + 0) = *(ptr_to_hand + i); } } } } else { if( (second_type + 0)-&gt;pip == (ptr_to_hand + i)-&gt;pip) { second_type_counter ++; second_type = realloc(second_type, second_type_counter * sizeof(card)); *(second_type + (second_type_counter - 1)) = *(ptr_to_hand + i); } else { if(second_type_counter == 1) { *(second_type + 0) = *(ptr_to_hand + i); } else if(second_type_counter &gt; 1) { continue; } } } } if(first_type_counter == 1 &amp;&amp; second_type_counter == 1) { no_pair ++; } else if(first_type_counter == 2 &amp;&amp; second_type_counter == 1) { one_pair ++; } else if(first_type_counter == 2 &amp;&amp; second_type_counter == 2) { two_pair ++; } else if(first_type_counter == 3 &amp;&amp; second_type_counter != 2 || first_type_counter != 2 &amp;&amp; second_type_counter == 3) { three_of_kind ++; } else if(first_type_counter == 4 || second_type_counter == 4) { four_of_kind ++; } else if(first_type_counter == 3 &amp;&amp; second_type_counter == 2 || first_type_counter == 2 &amp;&amp; second_type_counter == 3) { full_house ++; } } else { double no_pair_prob = no_pair / (double)HANDS_NUMBER; double one_pair_prob = one_pair / (double)HANDS_NUMBER; double two_pair_prob = two_pair / (double)HANDS_NUMBER; double three_of_kind_prob = three_of_kind / (double)HANDS_NUMBER; double four_of_kind_prob = four_of_kind /(double)HANDS_NUMBER; double full_house_prob = full_house / (double)HANDS_NUMBER; printf(&quot;\n\nNo pair probablity = %lf\nOne pair probability = %lf\nTwo pair probability = %lf\n&quot; &quot;Three of a kind probablity = %lf\nFour of a kind probability = %lf\n&quot; &quot;Full house probability = %lf\n\n&quot;, no_pair_prob, one_pair_prob, two_pair_prob, three_of_kind_prob, four_of_kind_prob, full_house_prob); } free(first_type); free(second_type); } int main(void) { srand(time(0)); //seeding rand with current time card deck[52]; card shuffled_deck[52]; card hand[7]; card one_card; static int i = 0; //to represent the 52 cards //card * ptr_to_deck = deck; //card * ptr_to_shuffled = shuffled_deck; //card * ptr_to_hand = hand; card * ptr_to_deck; card * ptr_to_shuffled; card * ptr_to_hand; for( int j = 1; j &lt;= 13; j++) //to generate all pip values { for(int k = 1; k &lt;= 4; k++) //to generate all suits { one_card.suit = k; one_card.pip = j; deck[i] = one_card; i++; } } for(int i = 0; i &lt; DECKS_NUMBER; i++) //number of decks to exceed 1.4 M hands { ptr_to_shuffled = shuffles_deck(&amp;deck[0], &amp;shuffled_deck[0]); for(int j = 0; j &lt; 7; j++) { ptr_to_hand = deals_hand(&amp;hand[0], &amp;shuffled_deck[0]); hand_determinator(&amp;hand[0]); } } return 0; } </code></pre>
[]
[ { "body": "<p>We start off reasonably well, defining some constants:</p>\n<blockquote>\n<pre><code>#define DECK_SIZE 52 //to be used to randomly select each of 52 cards\n#define SUITS_PLUS_ONE 5 //to be used to generate any of the 4 suits\n#define PIPS_PLUS_ONE 14 //to be used to generate any of the 13 pips\n</code></pre>\n</blockquote>\n<p>I'd argue that we shouldn't have <code>_PLUS_ONE</code> constants, but to simply add <code>1</code> where necessary:</p>\n<pre><code>#define SUITS 4\n#define PIPS 13\n#define DECK_SIZE (SUITS * PIPS)\n</code></pre>\n<p>Unfortunately, we then mostly fail to use the constants where appropriate, instead using magic numbers throughout the code, so it's no longer simple to change the kind of deck we're using.</p>\n<hr />\n<p>We have correctly examined the return value from <code>calloc()</code>, but remember than <code>realloc()</code> can also return a null pointer if it fails, and we need to be careful about that (and also not leak the memory in that case).</p>\n<hr />\n<p>There's some long-winded array access, such as this:</p>\n<blockquote>\n<pre><code> *(second_type + 0) = *(ptr_to_hand + i);\n</code></pre>\n</blockquote>\n<p>More simply written using <code>[]</code>:</p>\n<pre><code> second_type[0] = ptr_to_hand[i];\n</code></pre>\n<p>Similarly, <code>&amp;deck[0]</code> can be simply <code>deck</code>.</p>\n<hr />\n<p>These three variables don't add anything useful - although we assign to them, we never read their values:</p>\n<blockquote>\n<pre><code>card * ptr_to_deck;\ncard * ptr_to_shuffled;\ncard * ptr_to_hand;\n</code></pre>\n</blockquote>\n<hr />\n<p>I don't think we should be copying when we shuffle the deck. There's a well-known algorithm for shuffling in place, and it looks something like this:</p>\n<pre><code>void shuffle_deck(card *deck, size_t length)\n{\n for (size_t i = 1; i &lt; length; ++i) {\n int j = rand() % (i+1); /* ignore a slight bias here */\n /* swap cards i and j */\n card tmp = deck[i];\n deck[i] = deck[j];\n deck[j] = tmp;\n }\n}\n</code></pre>\n<hr />\n<p>Sorting the hand is inefficient, using Bubble Sort. It's only for a small number of values, so unlikely to be a major problem, but the standard library <code>qsort()</code> is generally a better choice (not least because it's then very obvious that we are indeed sorting).</p>\n<p>If we adapt the program in future to count straights (and straight flushes), then we'll need to remember to allow for hands that also have pairs within the straight (e.g. 4♣ 5♣ 6♣ 6♦ 6♠ 7♣ 8♣).</p>\n<p>It might be better not to sort, but instead to count how many of each card are present in a histogram of size <code>PIPS</code>.</p>\n<hr />\n<p>The <code>static</code> variables in the hand evaluator are inconvenient. It means that the function has two responsibilities: measuring the hand's worth and printing the summary results. It actually has a third, as it decides which of those to do. It's better to have it update a suitable structure of counts:</p>\n<pre><code>struct hand_stats\n{\n unsigned long total;\n unsigned long no_pair;\n unsigned long one_pair;\n unsigned long three_of_kind;\n unsigned long two_pair;\n unsigned long four_of_kind;\n unsigned long full_house;\n};\n</code></pre>\n<hr />\n<h1>Modified code</h1>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;time.h&gt;\n\n#define SUITS 4\n#define PIPS 13\n#define DECK_SIZE (SUITS * PIPS)\n\n#define DECKS_NUMBER 200000\n#define HAND_SIZE 7\n\ntypedef enum suit\n{\n hearts,\n diamonds,\n spades,\n clubs\n} suit;\n\ntypedef struct playing_card\n{\n suit suit;\n short pip;\n} card;\n\nstruct hand_stats\n{\n unsigned long total;\n unsigned long no_pair;\n unsigned long one_pair;\n unsigned long three_of_kind;\n unsigned long two_pair;\n unsigned long four_of_kind;\n unsigned long full_house;\n};\n\nvoid shuffle_deck(card *deck, int length)\n{\n for (int i = 1; i &lt; length; ++i) {\n int j = rand() % (i+1);\n /* swap cards i and j */\n card tmp = deck[i];\n deck[i] = deck[j];\n deck[j] = tmp;\n }\n}\n\nvoid evaluate_hand(card* hand, int length, struct hand_stats *stats)\n{\n unsigned value_count[PIPS] = { 0 }; /* how many cards of each pip value */\n for (int i = 0; i &lt; length; ++i) {\n ++value_count[hand[i].pip];\n }\n\n unsigned count[SUITS+1] = { 0 }; /* how many singletons, pairs etc */\n for (int i = 0; i &lt; PIPS; ++i) {\n ++count[value_count[i]];\n }\n\n if (count[4]) {\n ++stats-&gt;four_of_kind;\n } else if (count[3] &amp;&amp; count[2] || count[3] &gt;= 2) {\n ++stats-&gt;full_house;\n } else if (count[3]) {\n ++stats-&gt;three_of_kind;\n } else if (count[2] &gt;= 2) {\n ++stats-&gt;two_pair;\n } else if (count[2]) {\n ++stats-&gt;one_pair;\n } else {\n ++stats-&gt;no_pair;\n }\n ++stats-&gt;total;\n}\n\n\nint main(void)\n{\n srand((unsigned)time(0));\n\n card deck[DECK_SIZE];\n\n int i = 0;\n for (short j = 1; j &lt;= PIPS; ++j) {\n for (short k = 1; k &lt;= SUITS; ++k) {\n deck[i].suit = k;\n deck[i].pip = j;\n ++i;\n }\n }\n\n struct hand_stats stats = { 0, 0, 0, 0, 0, 0, 0 };\n for (int i = 0; i &lt; DECKS_NUMBER; ++i) {\n shuffle_deck(deck, DECK_SIZE);\n for (int j = 0; j + HAND_SIZE &lt; DECK_SIZE; j += HAND_SIZE) {\n evaluate_hand(deck+j, HAND_SIZE, &amp;stats);\n }\n }\n\n /* now print the results */\n const long double total = stats.total;\n printf(&quot;No pair probablity = %Lf\\n&quot;, stats.no_pair / total);\n printf(&quot;One pair probability = %Lf\\n&quot;, stats.one_pair / total);\n printf(&quot;Two pair probability = %Lf\\n&quot;, stats.two_pair / total);\n printf(&quot;Three of a kind probablity = %Lf\\n&quot;, stats.three_of_kind / total);\n printf(&quot;Four of a kind probability = %Lf\\n&quot;, stats.four_of_kind / total);\n printf(&quot;Full house probability = %Lf\\n&quot;, stats.full_house / total);\n}\n</code></pre>\n<p>One final note - we'll never get the exact results that are in a standard table, because we're counting some hands that in real poker would be evaluated higher, as a straight or flush.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T12:35:04.847", "Id": "533189", "Score": "0", "body": "`if (count[3])` and `if (count[2] >= 2)` has an asymmetry to it. `if (count[3] >= 1)` and `if (count[2] >= 2)` or `if (count[3] > 0)` and `if (count[2] > 1)` would be more symmetric.\n `" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T12:37:35.970", "Id": "533191", "Score": "0", "body": "The re-use of `i` in `for (int i = 0; i < PIPS; ++i) { ++count[value_count[i]]; }` as compared to the prior `for (int i = 0; i < length; ++i)` _looks_ wrong as `i` is indexing different units. Perhaps different index names?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T12:42:08.287", "Id": "533193", "Score": "0", "body": "With `++stats->four_of_kind`, the `++` looks attacked to `stats` and not `four_of_kind`. Pre `++` vs. post `++` is a style issue, yet I'd go for `stats->four_of_kind++` here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T12:42:16.117", "Id": "533194", "Score": "0", "body": "Possibly, but the scope is very small, and `i` is well-understood to be a small-scope indexer, so different names might not be much clearer. I guess that's very much a matter of style, so look at your environment's other code for guidance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T12:46:57.550", "Id": "533195", "Score": "0", "body": "1) `double` is certainly sufficient vs. `long double` here. 2) As a matter of `()` usage in a `#define DECK_SIZE (SUITS * PIPS)` could be `#define DECK_SIZE ((SUITS) * (PIPS))` to avoid dependency of other defines being simple. (Overall good review)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T12:50:10.273", "Id": "533196", "Score": "0", "body": "I used `long double` because we used `unsigned long` for the totals (because plain `unsigned` is only guaranteed good for 65535 iterations). I agree that with the particular values used here, we'll remain within precision range of `double`. And we're not using all of the precision anyway, so yes. But it does save an explicit cast or otherwise ignoring a warning." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T12:57:56.910", "Id": "533197", "Score": "0", "body": "\"plain unsigned is only guaranteed good for 65535 iterations\" --> yes, yet `long double` may have same range of `double` (and still get a precision warning of `unsigned long` to `long double`) - such is the variety of implementations. Could use the ugly `uint_least32_t` to prevent precision creep, yet `unsigned long / long double` is fine." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T11:54:33.287", "Id": "270092", "ParentId": "270084", "Score": "4" } } ]
{ "AcceptedAnswerId": "270092", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T02:12:29.427", "Id": "270084", "Score": "3", "Tags": [ "beginner", "c", "homework", "playing-cards" ], "Title": "Monte Carlo Simulation of 7 Card Stud Poker" }
270084
<p>I have this assignment with the goal of improving the performance and execution time of a FFT C++ code without the use of external libraries. The code is as following:</p> <pre><code>void FftCalculator::ButterflyFFT(std::complex&lt;double&gt; *a, std::complex&lt;double&gt; *b, std::complex&lt;double&gt; w) { auto U = *b * w; *b = *a - U; *a = *a + U; } uint32_t FftCalculator::bitReverseSingle(uint32_t x) { x = (((x &amp; 0xaaaaaaaa) &gt;&gt; 1) | ((x &amp; 0x55555555) &lt;&lt; 1)); x = (((x &amp; 0xcccccccc) &gt;&gt; 2) | ((x &amp; 0x33333333) &lt;&lt; 2)); x = (((x &amp; 0xf0f0f0f0) &gt;&gt; 4) | ((x &amp; 0x0f0f0f0f) &lt;&lt; 4)); x = (((x &amp; 0xff00ff00) &gt;&gt; 8) | ((x &amp; 0x00ff00ff) &lt;&lt; 8)); return ((x &gt;&gt; 16) | (x &lt;&lt; 16)); } void FftCalculator::FFT(std::complex&lt;double&gt; *a, const int m) { for (int i = 0; i &lt; (degree_ / 2); i++) { int m_idx = i / m; // base address int t_idx = i % m; std::complex&lt;double&gt; *a_x = a + 2 * m_idx * m + t_idx; std::complex&lt;double&gt; *a_y = a_x + m; std::complex&lt;double&gt; w = tw[m + t_idx]; ButterflyFFT(a_x, a_y, w); } } void FftCalculator::bitReverse(std::complex&lt;double&gt; *a) { for (int i = 0; i &lt; (degree_); i++) { int logdegree_ = log2(degree_); int degree_idx = i % degree_; int revdegree_ = bitReverseSingle(degree_idx) &gt;&gt; (32 - logdegree_); if (revdegree_ &gt; degree_idx) { std::complex&lt;double&gt; temp = a[degree_idx]; a[degree_idx] = a[revdegree_]; a[revdegree_] = temp; } } } // mode 1 for FFT and 2 for inverse ComplexVec FftCalculator::GetTwiddle(int mode) { ComplexVec twiddle(degree_); twiddle[0] = {1.0, 0.0}; for (int i = 1; i &lt; degree_; i *= 2) { for (int j = 0; j &lt; i; j++) { twiddle[i + j] = {cos(M_PI * (double)j / (double)i), sin(powf(-1.0, mode) * M_PI * (double)j / (double)i)}; } } return twiddle; } void FftCalculator::ExecFFT(std::complex&lt;double&gt; *a) { auto twiddle_factor = GetTwiddle(1); bitReverse(a); for (int i = 1; i &lt; degree_; i *= 2) { FFT(a, i); } } </code></pre> <p>The execution time is 30 ms Aprox, so I don't know how much can this code be improved. The thing is i'm not too good on C++ so I don't know what can I do to improve the performance. I know there is some libraries to optimize FFT in C++ but I was told I cannot use them. If someone can help me, I'd be really grateful.</p> <p>Thanks</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T04:00:10.350", "Id": "533166", "Score": "3", "body": "[Don't cross post](https://meta.stackexchange.com/questions/64068/is-cross-posting-a-question-on-multiple-stack-exchange-sites-permitted-if-the-qu) your [question](https://stackoverflow.com/questions/69968623/how-to-optimize-fft-c-code-without-using-external-libraries). Pick one site, and delete the question on the other site." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T06:50:08.050", "Id": "533171", "Score": "0", "body": "I think we need to see the class definition, and how it's being used to have enough context to review this properly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T07:46:04.677", "Id": "533174", "Score": "1", "body": "There is some code missing to make this compile. If you add that, I'll probably give it a real look. In the meantime you can [this review of a different FFT implementation](https://codereview.stackexchange.com/a/226329/36018), several of the points of interest are probably going to be similar." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T12:39:13.530", "Id": "533192", "Score": "0", "body": "Why couldn't you use one of the available libraries? Licence compatibility?" } ]
[ { "body": "<ol>\n<li><p>Use <code>float</code> instead of <code>double</code>.</p>\n</li>\n<li><p>Don't use <code>logdegree_ = log2(degree_)</code>, you can use <code>std::bit_width</code> (<a href=\"https://en.cppreference.com/w/cpp/numeric/bit_width\" rel=\"nofollow noreferrer\">https://en.cppreference.com/w/cpp/numeric/bit_width</a>)</p>\n</li>\n<li><p>You can use <code>std::swap</code> to swap something</p>\n</li>\n<li><p>Change <code>mode</code> to template parameter typed <code>bool</code>. Replace <code>powf(-1.0, mode)</code> to <code>mode ? -1.0f : 1.0f</code></p>\n</li>\n</ol>\n<p>There are also lots of other room to improve your code style, but I think that things are irrelevant to performance.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T06:23:23.510", "Id": "533473", "Score": "0", "body": "Float isn't necessarily faster then double. It depends on your system/cpu, and the added precission from double might be a requirement!\nhttps://stackoverflow.com/questions/4584637/double-or-float-which-is-faster" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T05:17:30.833", "Id": "270086", "ParentId": "270085", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T02:50:52.693", "Id": "270085", "Score": "-1", "Tags": [ "c++", "performance" ], "Title": "HOW can I optimize this FFT C++ Code without using external libraries?" }
270085
<p>I'm trying to build a directory website with ReactJS as a frontend and Python Flask as a backend. I'm trying to pass the text inputs in my searchbar.js to my Python script but I cant find a way to display the data that I've passed from the frontend in my backend to make sure I've really passed the data.</p> <p>Here's my searchbar.js where I tried storing the data in a variable and had that passed to the api route i've made in python.:</p> <pre class="lang-javascript prettyprint-override"><code>function SearchBar() { const [searchedText, setSearchedText] = useState(&quot;&quot;); let navigate = useNavigate(); const onSearch = () =&gt; { navigate(`/search?q=${searchedText}`); fetch('/ML/search',{ method: 'POST', body: JSON.stringify({ content:searchedText }) }) }; return ( &lt;div&gt; &lt;Input.Search placeholder=&quot;Enter keyword...&quot; onChange={(e) =&gt; { setSearchedText(e.target.value); }} onSearch={onSearch} onPressEnter={onSearch} enterButton&gt;&lt;/Input.Search&gt; &lt;/div&gt; ); } export default SearchBar; </code></pre> <p>here's my api route in python for fetching the data that was passed from my frontend:</p> <pre><code>@app.route('/ML/search', methods=['POST']) def search(): request_data = json.loads(request.data) searchData = request_data['content'] return searchData </code></pre> <p>So basically what I want to happen is I want to pass the input in my searchbar.js to my Python backend and store it as a variable so I could use that variable to search a column in SQL</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T09:26:15.367", "Id": "533176", "Score": "2", "body": "Welcome to Code Review! Can you confirm that the code is complete and that it functions correctly? If so, I recommend that you [edit] to add a summary of the testing (ideally as reproducible unit-test code). If it's not working, it isn't ready for review (see [help/on-topic]) and the question may be deleted." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T15:02:50.547", "Id": "533206", "Score": "0", "body": "@TobySpeight Discussion going on in the second monitor." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T07:12:59.087", "Id": "270090", "Score": "-2", "Tags": [ "python", "javascript", "react.js", "form", "flask" ], "Title": "How to pass input data from ReactJS (Frontend) to Flask-Python (Backend)" }
270090
<p>I use the below code to sort <code>List&lt;DataAccessViewModel&gt;</code> list.</p> <p>Here is the sort order :</p> <ol> <li><code>PriorityScore</code></li> <li><code>MName</code></li> <li><code>CName</code></li> <li><code>FName</code></li> </ol> <p>It works as expected.</p> <pre><code>public int Compare(DataAccessViewModel x, DataAccessViewModel y) { if (x == null || y == null) { return 0; } return x.CompareTo(y); } public int CompareTo(DataAccessViewModel mod) { int retval = (int)(this.PriorityScore?.CompareTo(mod.PriorityScore)); if(retval != 0) return retval; else { retval = (this.MName ?? &quot;zzzzzzzzzzzzz&quot;).CompareTo(mod.MName ?? &quot;zzzzzzzzzzzzz&quot;); if (retval != 0) return retval; else { retval = (this.CName ?? &quot;zzzzzzzzzzzzz&quot;).CompareTo(this.CName ?? &quot;zzzzzzzzzzzzz&quot;); if (retval != 0) return retval; else retval = (this.FName ?? &quot;zzzzzzzzzzzzz&quot;).CompareTo(this.FName ?? &quot;zzzzzzzzzzzzz&quot;); } } return retval; } </code></pre> <p>But the code looks clunky to me. Is there any better way of doing it or is this it ?</p> <p>Edit: here is the DataAccessViewModel with relevant properties</p> <pre><code>public class DataAccessViewModel : IComparer&lt;DataAccessViewModel&gt; { public string CName { get; set; } public string MName { get; set; } public string FName { get; set; } public int? PriorityScore { get; set; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T06:10:46.260", "Id": "533242", "Score": "1", "body": "please provide `DataAccessViewModel` class." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T08:12:54.457", "Id": "533249", "Score": "2", "body": "Yes indeed this can be greatly simplified, but we need to know the data types of the properties to be able to help you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T22:34:19.937", "Id": "533297", "Score": "0", "body": "what class is this code in?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T09:45:33.750", "Id": "533308", "Score": "0", "body": "@iSR5 Added the model" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T09:45:44.400", "Id": "533309", "Score": "0", "body": "@PeterCsala Added the model" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T09:46:35.213", "Id": "533310", "Score": "1", "body": "@Pரதீப் Then in my post I've made a good assumption :D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T09:48:59.380", "Id": "533312", "Score": "0", "body": "@PeterCsala Bang ON!" } ]
[ { "body": "<p>First of all, your code has an error. Once you do this.PriorityScore?.CompareTo(mod.PriorityScore), for a PriorityScore that I assume it's a Nullable int, for any null value you will get null, then casting to int will fail. Or if mod.PriorityScore is null, the CompareTo method will fail.</p>\n<p>Fixing that, if you return values from an if block, you don't really need an else, so your code could look like this:</p>\n<pre><code>int retval = (this.PriorityScore ?? 0).CompareTo(other.PriorityScore ?? 0);\nif (retval != 0) return retval;\nretval = (this.MName ?? &quot;zzzzzzzzzzzzz&quot;).CompareTo(other.MName ?? &quot;zzzzzzzzzzzzz&quot;);\nif (retval != 0) return retval;\nretval = (this.CName ?? &quot;zzzzzzzzzzzzz&quot;).CompareTo(this.CName ?? &quot;zzzzzzzzzzzzz&quot;);\nif (retval != 0) return retval;\nretval = (this.FName ?? &quot;zzzzzzzzzzzzz&quot;).CompareTo(this.FName ?? &quot;zzzzzzzzzzzzz&quot;);\nreturn retval;\n</code></pre>\n<p>You could use Linq, although this would not be very efficient as performance goes, it would be more readable:</p>\n<pre><code>if (this.PriorityScore == other.PriorityScore\n &amp;&amp; this.MName == other.MName\n &amp;&amp; this.CName == other.CName\n &amp;&amp; this.FName == other.FName) return 0;\nreturn new[] { this, other }\n .OrderBy(vm =&gt; vm.PriorityScore)\n .ThenBy(vm =&gt; vm.MName)\n .ThenBy(vm =&gt; vm.CName)\n .ThenBy(vm =&gt; vm.FName)\n .First() == this ? -1 : 1;\n</code></pre>\n<p>(I removed the default values for readability, but you can add them)\nAlso, if you can make DataAccessViewModel a struct, equality is baked in, so you can replace the first check with <code>if (this.Equals(other)) return 0;</code>. You can still do that if you override equality.\nThis might not work well for the Compare method of an IComparable implementation, but it could work for your original List of DataAccessViewModel, if you want to move the ordering outside of the class:</p>\n<pre><code>var orderedList = list\n .OrderBy(vm =&gt; vm.PriorityScore)\n .ThenBy(vm =&gt; vm.MName)\n .ThenBy(vm =&gt; vm.CName)\n .ThenBy(vm =&gt; vm.FName)\n .ToList();\n</code></pre>\n<p>Another solution would be to implement a small method to simplify things:</p>\n<pre><code>public int CompareTo(DataAccessViewModel other)\n{\n return compare(this.PriorityScore ?? 0, other.PriorityScore ?? 0)\n ?? compare(this.MName ?? &quot;zzzzzzzzzzzzz&quot;, other.MName ?? &quot;zzzzzzzzzzzzz&quot;)\n ?? compare(this.CName ?? &quot;zzzzzzzzzzzzz&quot;, other.CName ?? &quot;zzzzzzzzzzzzz&quot;)\n ?? compare(this.FName ?? &quot;zzzzzzzzzzzzz&quot;, other.FName ?? &quot;zzzzzzzzzzzzz&quot;)\n ?? 0;\n}\n\nprivate int? compare(IComparable o1,IComparable o2)\n{\n var retval = o1.CompareTo(o2);\n return retval == 0 ? (int?)null : retval;\n}\n</code></pre>\n<p>I believe this would be readable and performant enough.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T12:52:01.847", "Id": "270115", "ParentId": "270097", "Score": "1" } }, { "body": "<p><strong>Get rid of all &quot;if/else&quot; complexity</strong></p>\n<pre><code>{\n var retval = x.PriorityScore.CompareTo(y.PriorityScore);\n\n if(retval = 0) \n retval = CompareMname(DataAccessViewModel x, DataAccessViewModel y);\n\n return retval;\n}\n\npublic int CompareMname(DataAccessViewModel x, DataAccessViewModel y)\n{\n var retval = x.MName.CompareTo(y.MName);\n\n if(retval = 0) \n retail = CompareCname(DataAccessViewModel x, DataAccessViewModel y);\n\n return retval;\n}\n\npublic int CompareCname(DataAccessViewModel x, DataAccessViewModel y)\n{\n var retval = x.CName.CompareTo(y.CName);\n\n if(retval = 0) \n retval = CompareFname(DataAccessViewModel x, DataAccessViewModel y);\n\n return retval;\n}\n\n// this must be the last called comparison\npublic int CompareFname(DataAccessViewModel x, DataAccessViewModel y)\n{\n return x.CName.CompareTo(y.CName);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T23:00:07.533", "Id": "270132", "ParentId": "270097", "Score": "0" } }, { "body": "<h3>Properties</h3>\n<p>For the sake of simplicity let's assume your view model's properties are defined like this:</p>\n<pre><code>public int? PriorityScore { get; set; }\npublic string MName { get; set; }\npublic string CName { get; set; }\npublic string FName { get; set; }\n</code></pre>\n<h3>Compare</h3>\n<p>Your <code>Compare</code> method can be simply implemented with the following one-liner:</p>\n<pre><code>private const int SamePositionInOrdering = 0;\npublic int Compare(DataAccessViewModel lhs, DataAccessViewModel rhs)\n =&gt; lhs is object &amp;&amp; rhs is object ? lhs.CompareTo(rhs) : SamePositionInOrdering;\n</code></pre>\n<ul>\n<li><code>lhs is object</code> is the <a href=\"https://www.thomasclaudiushuber.com/2020/03/12/c-different-ways-to-check-for-null/\" rel=\"nofollow noreferrer\">new way in C# 9</a> to express <code>lhs</code> is not <code>null</code></li>\n<li>I've used left and right hand side as parameter names, because I think they are more expressive than <code>x</code> and <code>y</code></li>\n<li>You might also consider to make it <code>static</code> since it does not rely on instance members</li>\n</ul>\n<h3>CompareTo</h3>\n<p>Here I make a separation of the <code>PriorityScore</code> and the rest of the properties. The reasoning is simple in case of <code>PriorityScore</code> you don't have fallback value if it is <code>null</code>.</p>\n<p>First lets define an array with property selectors to specify the ordering of <code>MName</code>, <code>CName</code> and <code>FName</code>:</p>\n<pre><code>private readonly Func&lt;DataAccessViewModel, IComparable&gt;[] propertySelectors;\n \npublic DataAccessViewModel()\n{\n propertySelectors = new Func&lt;DataAccessViewModel, IComparable&gt;[] {\n vm =&gt; vm.MName,\n vm =&gt; vm.CName,\n vm =&gt; vm.FName,\n };\n}\n</code></pre>\n<ul>\n<li>If you unfamiliar with the property selector concept then please visit <a href=\"https://stackoverflow.com/questions/5075484/property-selector-expressionfunct-how-to-get-set-value-to-selected-property\">this SO topic</a></li>\n<li>I've used <code>IComparable</code> instead of <code>string</code> or <code>object</code>, since we only care about the <code>CompareTo</code> method\n<ul>\n<li>This concept is generic enough to support other property types as well, like <code>int</code></li>\n</ul>\n</li>\n</ul>\n<p>Then let's see how can we implement the <code>CompareTo</code>:</p>\n<pre><code>private const string FallbackValue = &quot;zzzzzzzzzzzzz&quot;;\npublic int CompareTo(DataAccessViewModel that)\n{\n int positionInOrdering = (int)(PriorityScore?.CompareTo(that.PriorityScore));\n if (positionInOrdering != SamePositionInOrdering) return positionInOrdering;\n\n foreach (var selector in propertySelectors)\n {\n var lhs = selector(this) ?? FallbackValue;\n var rhs = selector(that) ?? FallbackValue;\n\n positionInOrdering = lhs.CompareTo(rhs);\n if (positionInOrdering != SamePositionInOrdering) return positionInOrdering;\n }\n\n return SamePositionInOrdering;\n}\n</code></pre>\n<ul>\n<li>I've renamed your <code>mod</code> parameter to <code>that</code>, since we are comparing this and that :)</li>\n<li>I've also renamed your <code>retval</code> to <code>positionInOrdering</code> since it better expresses the intent IMHO</li>\n<li>As I said I've treated the <code>PriorityScore</code> differently because there is no fallback value for that if its value is <code>null</code></li>\n<li>I've introduced some constants so the implementation is free from hard coded values.</li>\n</ul>\n<hr />\n<p>For the sake of completeness here is the entire implementation of <code>DataAccessViewModel</code> class</p>\n<pre><code>public class DataAccessViewModel: IComparable&lt;DataAccessViewModel&gt;\n{\n public int? PriorityScore { get; set; }\n public string MName { get; set; }\n public string CName { get; set; }\n public string FName { get; set; }\n\n private const string FallbackValue = &quot;zzzzzzzzzzzzz&quot;;\n private const int SamePositionInOrdering = 0;\n private readonly Func&lt;DataAccessViewModel, IComparable&gt;[] propertySelectors;\n \n public DataAccessViewModel()\n {\n propertySelectors = new Func&lt;DataAccessViewModel, IComparable&gt;[] {\n vm =&gt; vm.MName,\n vm =&gt; vm.CName,\n vm =&gt; vm.FName,\n };\n }\n \n public int Compare(DataAccessViewModel lhs, DataAccessViewModel rhs)\n =&gt; lhs is object &amp;&amp; rhs is object ? lhs.CompareTo(rhs) : SamePositionInOrdering;\n\n public int CompareTo(DataAccessViewModel that)\n {\n int positionInOrdering = (int)(PriorityScore?.CompareTo(that.PriorityScore));\n if (positionInOrdering != SamePositionInOrdering) return positionInOrdering;\n\n foreach (var selector in propertySelectors)\n {\n var lhs = selector(this) ?? FallbackValue;\n var rhs = selector(that) ?? FallbackValue;\n\n positionInOrdering = lhs.CompareTo(rhs);\n if (positionInOrdering != SamePositionInOrdering) return positionInOrdering;\n }\n\n return SamePositionInOrdering;\n }\n}\n</code></pre>\n<hr />\n<p>I've used the following data for testing:</p>\n<pre><code>List&lt;DataAccessViewModel&gt; models = new()\n{\n new() { PriorityScore = 1, MName = &quot;M&quot;, CName = &quot;C&quot;, FName = &quot;F&quot; },\n new() { PriorityScore = 1, MName = &quot;M&quot;, CName = &quot;C&quot;, FName = &quot;F&quot; },\n new() { PriorityScore = 0, MName = &quot;M&quot;, CName = &quot;C&quot;, FName = &quot;F&quot; },\n new() { PriorityScore = 2, MName = &quot;N&quot;, CName = &quot;C&quot;, FName = &quot;F&quot; },\n new() { PriorityScore = 2, MName = &quot;M&quot;, CName = &quot;C&quot;, FName = &quot;F&quot; },\n new() { PriorityScore = 4, MName = &quot;M&quot;, CName = &quot;C&quot;, FName = &quot;G&quot; },\n new() { PriorityScore = 4, MName = &quot;M&quot;, CName = &quot;C&quot;, FName = &quot;F&quot; },\n new() { PriorityScore = 3, MName = &quot;M&quot;, CName = &quot;D&quot;, FName = &quot;F&quot; },\n new() { PriorityScore = 3, MName = &quot;M&quot;, CName = &quot;C&quot;, FName = &quot;F&quot; },\n};\n\nmodels.Sort();\nforeach (var model in models)\n{\n Console.WriteLine($&quot;{{ PriorityScore = {model.PriorityScore}, MName = {model.MName}, CName = {model.CName}, FName = {model.FName} }}&quot;);\n}\n</code></pre>\n<p>The output is the following:</p>\n<pre><code>{ PriorityScore = 0, MName = M, CName = C, FName = F }\n{ PriorityScore = 1, MName = M, CName = C, FName = F }\n{ PriorityScore = 1, MName = M, CName = C, FName = F }\n{ PriorityScore = 2, MName = M, CName = C, FName = F }\n{ PriorityScore = 2, MName = N, CName = C, FName = F }\n{ PriorityScore = 3, MName = M, CName = C, FName = F }\n{ PriorityScore = 3, MName = M, CName = D, FName = F }\n{ PriorityScore = 4, MName = M, CName = C, FName = F }\n{ PriorityScore = 4, MName = M, CName = C, FName = G }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T09:47:24.857", "Id": "533311", "Score": "1", "body": "Thank you for this." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T08:56:06.507", "Id": "270141", "ParentId": "270097", "Score": "1" } }, { "body": "<p><code>CompareTo</code> is an <code>IComparable&lt;T&gt;</code> implementation and <code>Compare</code> is <code>IComparer&lt;T&gt;</code> implementation. So, it would be better if you use the proper interfaces for that.</p>\n<p>The default value <code>zzzzzzzzzzzzz</code> this should be a constant, either inside the model, or on a wider access class (if it's used on other classes).</p>\n<p>so, the your class design would be something like :</p>\n<pre><code>public class DataAccessViewModel : IComparable&lt;DataAccessViewModel&gt;, IComparer&lt;DataAccessViewModel&gt;\n{\n private const string DefaultStringValue = &quot;zzzzzzzzzzzzz&quot;;\n\n public int? PriorityScore { get; set; }\n public string MName { get; set; }\n public string CName { get; set; } \n public string FName { get; set; }\n \n\n // IComparer&lt;DataAccessViewModel&gt;\n public int Compare(DataAccessViewModel source, DataAccessViewModel target) { ... }\n \n // IComparable&lt;DataAccessViewModel&gt;\n public int CompareTo(DataAccessViewModel target) =&gt; Compare(this, target);\n \n}\n</code></pre>\n<p>for the <code>Compare</code> method, there are multiple ways, here are two additional ways to do it :</p>\n<p><strong>using <code>Dictionary</code></strong> :</p>\n<pre><code>public int Compare(DataAccessViewModel source, DataAccessViewModel target)\n{\n if (source == null || target == null)\n {\n return 0;\n }\n \n int retval = (int)(source.PriorityScore?.CompareTo(target.PriorityScore));\n \n if(retval != 0) return retval;\n \n Dictionary&lt;string, string&gt; comparsion = new Dictionary&lt;string, string&gt;\n {\n { source.MName, target.MName },\n { source.CName, target.CName },\n { source.FName, target.FName }\n };\n\n foreach(var item in comparsion)\n {\n var leftOperhand = item.Key ?? DefaultStringValue;\n var rightOperhand = item.Value ?? DefaultStringValue;\n \n retval = string.Compare(leftOperhand, rightOperhand, StringComparison.InvariantCultureIgnoreCase);\n \n if(retval != 0) return retval;\n }\n \n return retval;\n}\n</code></pre>\n<p><strong>Using private methods</strong>:</p>\n<pre><code>private int? InternalStringCompare(string leftOperhand, string rightOperhand)\n{\n // Always use StringComparison when comparing strings\n int? result = string.Compare(leftOperhand ?? DefaultStringValue, rightOperhand ?? DefaultStringValue, StringComparison.InvariantCultureIgnoreCase); \n return result != 0 ? result : null;\n}\n\nprivate int? InternalIntCompare(int? leftOperhand, int? rightOperhand)\n{\n int? result = (leftOperhand ?? 0).CompareTo(rightOperhand ?? 0); \n return result != 0 ? result : null;\n}\n\npublic int Compare(DataAccessViewModel source, DataAccessViewModel target)\n{\n return source != null &amp;&amp; target != null ?\n InternalIntCompare(source.PriorityScore, target.PriorityScore) \n ?? InternalStringCompare(source.MName, target.MName) \n ?? InternalStringCompare(source.CName, target.CName) \n ?? InternalStringCompare(source.FName, target.FName) \n ?? 0 : 0;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T13:00:28.063", "Id": "270158", "ParentId": "270097", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T16:36:06.837", "Id": "270097", "Score": "1", "Tags": [ "c#", "sorting" ], "Title": "Sorting based on multiple fields using IComparer" }
270097
<p>I know my code is ugly and unreadable. I originally had the game working without class functions but when I had to implement class function it all went downhill.</p> <p>TennisMaster.py</p> <pre><code>import random import time import pygame import Menu from RunningGame import * class TennisMaster(RunningGame): def __init__(self): self.screen_height_and_width=TennisMaster.sizeCheck() self.imagesDirectory=&quot;images/&quot; self.screen=pygame.display.set_mode((self.screen_height_and_width,self.screen_height_and_width)) TennisMaster.setUp(self) def setUp(self): screen=self.screen screen_height_and_width=self.screen_height_and_width pygame.font.init() screen.fill((255,255,255)) Menu.startAnimation(self,screen,screen_height_and_width) TennisMaster.clearBackground(self) map=Menu.mapSelection(self,screen,screen_height_and_width) print(str(map)+&quot;.png &lt;====&quot;) bg = pygame.image.load(self.imagesDirectory+str(map)+&quot;.png&quot;) screen.blit(pygame.transform.scale(bg,(screen_height_and_width,screen_height_and_width)), (0, 0)) pygame.display.update() powerUps=Menu.powerUpSelection(self) score=0 RunningGame.NextBall(screen,screen_height_and_width,score,map,powerUps) def clearBackground(self): screen=self.screen screen_height_and_width=self.screen_height_and_width bg = pygame.image.load(self.imagesDirectory+&quot;whiteImage.png&quot;) screen.blit(pygame.transform.scale(bg,(screen_height_and_width,screen_height_and_width)), (0, 0)) pygame.display.update() def sizeCheck(): return(800) TennisMaster() </code></pre> <p>Menu.py</p> <pre><code>import random import time import pygame class Menu(): def __init__(screen,screen_height_and_width): self.screen=screen self.screen_height_and_width=screen_height_and_width self.imagesDirectory=&quot;images/&quot; def powerUpSelection(self): screen=self.screen screen_height_and_width=self.screen_height_and_width with open(&quot;score.txt&quot;,&quot;r&quot;) as scoreFile: scoreText=scoreFile.read() highScore=max(Menu.Convert_To_List(self,scoreText)) print(highScore,'&lt;---') clear = pygame.image.load(self.imagesDirectory+&quot;whiteImage.png&quot;) screen.blit(pygame.transform.scale(clear,(screen_height_and_width,screen_height_and_width)), (0, 0)) if highScore&lt;20: powerUpSelection = pygame.image.load(self.imagesDirectory+&quot;powerUp-1.png&quot;) elif highScore&lt;30 and highScore&gt;=20: powerUpSelection = pygame.image.load(self.imagesDirectory+&quot;powerUp-2.png&quot;) elif highScore&lt;40 and highScore&gt;=30: powerUpSelection = pygame.image.load(self.imagesDirectory+&quot;powerUp-3.png&quot;) elif highScore&lt;60 and highScore&gt;=40: powerUpSelection = pygame.image.load(self.imagesDirectory+&quot;powerUp-4.png&quot;) elif highScore&gt;=60 or highScore==60: powerUpSelection = pygame.image.load(self.imagesDirectory+&quot;powerUp-5.png&quot;) screen.blit(pygame.transform.scale(powerUpSelection,(screen_height_and_width,screen_height_and_width)), (0, 0)) pygame.display.update() working=True while working: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key==49:#49 for 1 print(&quot;scoreBoost&quot;) return(&quot;scoreBoost&quot;) elif event.key==50 and highScore&gt;=15:#50 for 2 print(&quot;biggerHitbox&quot;) return(&quot;biggerHitbox&quot;) elif event.key==51 and highScore&gt;=25:#51 for 3 print(&quot;ballSlow&quot;) return(&quot;ballSlow&quot;) elif event.key==52 and highScore&gt;=35:#51 for 3 print(&quot;directionHint&quot;) return(&quot;directionHint&quot;) elif event.key==53 and highScore&gt;=50:#51 for 3 print(&quot;extraLife&quot;) return(&quot;extraLife&quot;) else: print(&quot;fail&quot;) elif event.type == pygame.QUIT: pygame.quit() exit() #bigger hitbox #slow down #extra life # score boost every 5 balls you gain an extra point #direction hint #if you get a highscore of 75 you have an option to level up a power boost def mapSelection(self,screen,screen_height_and_width): screen=self.screen screen_height_and_width=self.screen_height_and_width with open(&quot;score.txt&quot;,&quot;r&quot;) as scoreFile: scoreText=scoreFile.read() totalScore=int(Menu.totalScores(Menu.Convert_To_List(self,scoreText))) clear = pygame.image.load(self.imagesDirectory+&quot;whiteImage.png&quot;) screen.blit(pygame.transform.scale(clear,(screen_height_and_width,screen_height_and_width)), (0, 0)) if totalScore&lt;250: mapSelectionBG = pygame.image.load(self.imagesDirectory+&quot;mapselection-1.png&quot;) elif totalScore&lt;500: mapSelectionBG = pygame.image.load(self.imagesDirectory+&quot;mapselection-2.png&quot;) else: mapSelectionBG = pygame.image.load(self.imagesDirectory+&quot;mapselection-3.png&quot;) screen.blit(pygame.transform.scale(mapSelectionBG,(screen_height_and_width,screen_height_and_width)), (0, 0)) pygame.display.update() working=True while working: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: totalScore=int(totalScore) print(totalScore,&quot;\n&quot;,event.key) if event.key==49:#49 for 1 print(&quot;test map 1&quot;) return(&quot;map1&quot;) elif event.key==50 and totalScore&gt;=250:#50 for 2 print(&quot;test map 2&quot;) return(&quot;map2&quot;) elif event.key==51 and totalScore&gt;=500:#51 for 3 print(&quot;test map 3&quot;) return(&quot;map3&quot;) else: print(&quot;failed&quot;) elif event.type == pygame.QUIT: pygame.quit() exit() def Convert_To_List(self, scoreText): newList=[] eachScore=&quot;&quot; for letter in list(scoreText): if letter == &quot;,&quot;: if eachScore!=&quot;&quot;: newList.append(int(eachScore)) eachScore=&quot;&quot; else: eachScore=eachScore+str(int(letter)) return(newList) def totalScores(scoreFile): totalScoreNumber=0 for number in scoreFile: if number!=1: totalScoreNumber+=number return(totalScoreNumber) def startAnimation(self,screen,screen_height_and_width): screen=self.screen screen_height_and_width=self.screen_height_and_width bg = pygame.image.load(self.imagesDirectory+&quot;startAnimation.png&quot;) screen.blit(pygame.transform.scale(bg,(screen_height_and_width,screen_height_and_width)), (0, 0)) working=0 pygame.display.update() while working==0: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: print(&quot;key hit&quot;) working=1 elif event.type == pygame.QUIT: pygame.quit() exit() </code></pre> <p>RunningGame.py</p> <pre><code>import random import time import pygame import TennisMaster #if i have this it breaks from Menu import * class RunningGame: def __init__(direction,screen,screen_height_and_width,score,map,powerUps): self.direction=direction self.screen=screen self.screen_height_and_width=screen_height_and_width self.score=score self.map=map self.powerUps=powerUps def imagesDirectory(): return(&quot;images/&quot;) def tennisBall(direction,screen,screen_height_and_width,score,map,powerUps): backwards=False working=True slowdown=0 speed=12-slowdown+score*0.5 speed=int(speed) if powerUps==&quot;scoreBoost&quot; and speed%4==0: score+=1 elif powerUps==&quot;ballSlow&quot;: slowdown=2 score+=1 if powerUps==&quot;biggerHitbox&quot;: biggerHitbox=True else: biggerHitbox=False if direction==&quot;left&quot;: x=int(screen_height_and_width/160) y=int(screen_height_and_width/2-int(screen_height_and_width/22)) ball = pygame.image.load(RunningGame.imagesDirectory()+&quot;tennisball.png&quot;) clear = pygame.image.load(RunningGame.imagesDirectory()+&quot;whiteImage.png&quot;) bg = pygame.image.load(RunningGame.imagesDirectory()+str(map)+&quot;-left.png&quot;) start=int(screen_height_and_width/160) while working: screen.blit(pygame.transform.scale(clear,(screen_height_and_width,screen_height_and_width)), (0, 0)) screen.blit(pygame.transform.scale(bg,(screen_height_and_width,screen_height_and_width)), (0, 0)) screen.blit(pygame.transform.scale(ball,(int(screen_height_and_width/10),int(screen_height_and_width/10))), (x,y)) RunningGame.scoreBoard(screen,screen_height_and_width,score) pygame.display.update() time.sleep(0.005) x+=speed for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key==pygame.K_a or event.key==1073741904: #97 = a if x&gt;200 and x&lt;400: backwards=True RunningGame.scoreBoard(screen,screen_height_and_width,score) RunningGame.NextBall(screen,screen_height_and_width,score,map,powerUps) elif powerUps==&quot;extraLife&quot;: powerUps=&quot;&quot; time.sleep(0.5) print(&quot;extra life over&quot;) backwards=True RunningGame.scoreBoard(screen,screen_height_and_width,score) RunningGame.NextBall(screen,screen_height_and_width,score,map,powerUps) elif biggerHitbox and x&gt;150 and x&lt;450: backwards=True RunningGame.scoreBoard(screen,screen_height_and_width,score) RunningGame.NextBall(screen,screen_height_and_width,score,map,powerUps) else: RunningGame.failScreen(screen,screen_height_and_width,score) else: RunningGame.failScreen(screen,screen_height_and_width,score) elif event.type == pygame.QUIT: pygame.quit() exit() if x&lt;screen_height_and_width/160: screen.blit(pygame.transform.scale(clear,(screen_height_and_width,screen_height_and_width)), (0, 0)) screen.blit(pygame.transform.scale(bg,(screen_height_and_width,screen_height_and_width)), (0, 0)) working=False if backwards: if speed&gt;0: speed=(speed*-1)*2 if direction==&quot;right&quot;: x=int(screen_height_and_width-screen_height_and_width/160) y=int(screen_height_and_width/2-int(screen_height_and_width/22)) ball = pygame.image.load(RunningGame.imagesDirectory()+&quot;tennisball.png&quot;) clear = pygame.image.load(RunningGame.imagesDirectory()+&quot;whiteImage.png&quot;) bg = pygame.image.load(RunningGame.imagesDirectory()+str(map)+&quot;-right.png&quot;) start=int(screen_height_and_width/160) while working: screen.blit(pygame.transform.scale(clear,(screen_height_and_width,screen_height_and_width)), (0, 0)) screen.blit(pygame.transform.scale(bg,(screen_height_and_width,screen_height_and_width)), (0, 0)) screen.blit(pygame.transform.scale(ball,(int(screen_height_and_width/10),int(screen_height_and_width/10))), (x,y)) RunningGame.scoreBoard(screen,screen_height_and_width,score) pygame.display.update() time.sleep(0.005) x-=speed for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key==100 or event.key==1073741903:#100 = d if x&lt;600 and x&gt;400: backwards=True RunningGame.scoreBoard(screen,screen_height_and_width,score) RunningGame.NextBall(screen,screen_height_and_width,score,map,powerUps) elif powerUps==&quot;extraLife&quot;: powerUps=&quot;&quot; time.sleep(0.5) print(&quot;extra life over&quot;) backwards=True RunningGame.scoreBoard(screen,screen_height_and_width,score) RunningGame.NextBall(screen,screen_height_and_width,score,map,powerUps) elif biggerHitbox and x&lt;650 and x&lt;350: backwards=True RunningGame.scoreBoard(screen,screen_height_and_width,score) RunningGame.NextBall(screen,screen_height_and_width,score,map,powerUps) else: RunningGame.failScreen(screen,screen_height_and_width,score) else: RunningGame.failScreen(screen,screen_height_and_width,score) elif event.type == pygame.QUIT: pygame.quit() exit() if x&lt;screen_height_and_width/160: screen.blit(pygame.transform.scale(clear,(screen_height_and_width,screen_height_and_width)), (0, 0)) screen.blit(pygame.transform.scale(bg,(screen_height_and_width,screen_height_and_width)), (0, 0)) working=False if backwards: if speed&gt;0: speed=(speed*-1)*2 if direction==&quot;up&quot;: x=int(screen_height_and_width/2-screen_height_and_width/20) y=int(int(screen_height_and_width/80)) ball = pygame.image.load(RunningGame.imagesDirectory()+&quot;tennisball.png&quot;) clear = pygame.image.load(RunningGame.imagesDirectory()+&quot;whiteImage.png&quot;) bg = pygame.image.load(RunningGame.imagesDirectory()+str(map)+&quot;-up.png&quot;) start=int(screen_height_and_width/160) while working: screen.blit(pygame.transform.scale(clear,(screen_height_and_width,screen_height_and_width)), (0, 0)) screen.blit(pygame.transform.scale(bg,(screen_height_and_width,screen_height_and_width)), (0, 0)) screen.blit(pygame.transform.scale(ball,(int(screen_height_and_width/10),int(screen_height_and_width/10))), (x,y)) RunningGame.scoreBoard(screen,screen_height_and_width,score) pygame.display.update() time.sleep(0.005) y+=speed for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key==119 or event.key == 1073741906:#199 = w if y&gt;200 and y&lt;400: backwards=True RunningGame.scoreBoard(screen,screen_height_and_width,score) RunningGame.NextBall(screen,screen_height_and_width,score,map,powerUps) elif powerUps==&quot;extraLife&quot;: powerUps=&quot;&quot; time.sleep(0.5) print(&quot;extra life over&quot;) backwards=True RunningGame.scoreBoard(screen,screen_height_and_width,score) RunningGame.NextBall(screen,screen_height_and_width,score,map,powerUps) elif biggerHitbox and y&gt;150 and y&lt;450: backwards=True RunningGame.scoreBoard(screen,screen_height_and_width,score) RunningGame.NextBall(screen,screen_height_and_width,score,map,powerUps) else: RunningGame.failScreen(screen,screen_height_and_width,score) else: RunningGame.failScreen(screen,screen_height_and_width,score) elif event.type == pygame.QUIT: pygame.quit() exit() if x&lt;screen_height_and_width/160: screen.blit(pygame.transform.scale(clear,(screen_height_and_width,screen_height_and_width)), (0, 0)) screen.blit(pygame.transform.scale(bg,(screen_height_and_width,screen_height_and_width)), (0, 0)) working=False if backwards: if speed&gt;0: speed=(speed*-1)*2 if direction==&quot;down&quot;: x=int(screen_height_and_width/2-screen_height_and_width/20) y=int(int(screen_height_and_width-screen_height_and_width/80)) ball = pygame.image.load(RunningGame.imagesDirectory()+&quot;tennisball.png&quot;) clear = pygame.image.load(RunningGame.imagesDirectory()+&quot;whiteImage.png&quot;) bg = pygame.image.load(RunningGame.imagesDirectory()+str(map)+&quot;-down.png&quot;) start=int(screen_height_and_width/160) while working: screen.blit(pygame.transform.scale(clear,(screen_height_and_width,screen_height_and_width)), (0, 0)) screen.blit(pygame.transform.scale(bg,(screen_height_and_width,screen_height_and_width)), (0, 0)) screen.blit(pygame.transform.scale(ball,(int(screen_height_and_width/10),int(screen_height_and_width/10))), (x,y)) RunningGame.scoreBoard(screen,screen_height_and_width,score) pygame.display.update() time.sleep(0.005) y-=speed for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key==115 or event.key==1073741905:#115 = a if y&lt;600 and y&gt;400: backwards=True RunningGame.scoreBoard(screen,screen_height_and_width,score) RunningGame.NextBall(screen,screen_height_and_width,score,map,powerUps) elif powerUps==&quot;extraLife&quot;: time.sleep(0.5) powerUps=&quot;&quot; print(&quot;extra life over&quot;) backwards=True RunningGame.scoreBoard(screen,screen_height_and_width,score) RunningGame.NextBall(screen,screen_height_and_width,score,map,powerUps) elif biggerHitbox and y&lt;650 and y&gt;350: backwards=True RunningGame.scoreBoard(screen,screen_height_and_width,score) RunningGame.NextBall(screen,screen_height_and_width,score,map,powerUps) else: RunningGame.failScreen(screen,screen_height_and_width,score) else: RunningGame.failScreen(screen,screen_height_and_width,score) elif event.type == pygame.QUIT: pygame.quit() exit() if x&lt;screen_height_and_width/160: screen.blit(pygame.transform.scale(clear,(screen_height_and_width,screen_height_and_width)), (0, 0)) screen.blit(pygame.transform.scale(bg,(screen_height_and_width,screen_height_and_width)), (0, 0)) working=False if backwards: if speed&gt;0: speed=(speed*-1)*2 def NextBall(screen,screen_height_and_width,score,map,powerUps): newDirection=random.randint(1,4) #2 and 4 dont work if powerUps==&quot;directionHint&quot;: if newDirection==1: x=int(screen_height_and_width/160) y=int(screen_height_and_width/2-int(screen_height_and_width/22)) arrow=pygame.image.load(RunningGame.imagesDirectory()+&quot;leftArrow.png&quot;) if newDirection==2: x=int(screen_height_and_width-screen_height_and_width/160-82) y=int(screen_height_and_width/2-int(screen_height_and_width/22)) arrow=pygame.image.load(RunningGame.imagesDirectory()+&quot;rightArrow.png&quot;) print(arrow) if newDirection==3: x=int(screen_height_and_width/2-screen_height_and_width/20) y=int(int(screen_height_and_width/80)) arrow=pygame.image.load(RunningGame.imagesDirectory()+&quot;upArrow.png&quot;) if newDirection==4: x=int(screen_height_and_width/2-screen_height_and_width/20) y=int(int(screen_height_and_width-screen_height_and_width/80)-82) arrow=pygame.image.load(RunningGame.imagesDirectory()+&quot;downArrow.png&quot;) pygame.display.update() screen.blit(pygame.transform.scale(arrow,(int(screen_height_and_width/10),int(screen_height_and_width/10))), (x,y)) pygame.display.update() time.sleep(0.05) if newDirection==1: RunningGame.tennisBall(&quot;left&quot;,screen,screen_height_and_width,score,map,powerUps) elif newDirection==2: RunningGame.tennisBall(&quot;right&quot;,screen,screen_height_and_width,score,map,powerUps) elif newDirection==3: RunningGame.tennisBall(&quot;up&quot;,screen,screen_height_and_width,score,map,powerUps) elif newDirection==4: RunningGame.tennisBall(&quot;down&quot;,screen,screen_height_and_width,score,map,powerUps) def Convert_To_List(scoreText): newList=[] eachScore=&quot;&quot; for letter in list(scoreText): if letter == &quot;,&quot;: if eachScore!=&quot;&quot;: newList.append(int(eachScore)) eachScore=&quot;&quot; else: eachScore=eachScore+str(int(letter)) return(newList) def scoreBoard(screen,screen_height_and_width,score): if score&gt;100000000000000000000000000000000000000000000: score-=100000000000000000000000000000000000000000000 myfont = pygame.font.SysFont('Comic Sans MS', 100) bigfont = pygame.font.SysFont('They definitely dont have this installed Gothic', 120) textsurface = myfont.render(str(score), False, (0, 0, 0)) if score&gt;=10: screen.blit(textsurface,(145,270)) else: screen.blit(textsurface,(179,270)) with open(&quot;score.txt&quot;,&quot;r&quot;) as scoreFile: scoreText=scoreFile.read() highScore=max(RunningGame.Convert_To_List(scoreText)) textsurface = myfont.render(''+str(highScore), False, (0, 0, 0)) if highScore&gt;=10: screen.blit(textsurface,(541,270)) else: screen.blit(textsurface,(570,270)) if highScore&lt;score: textsurface = bigfont.render(&quot;New Highscore&quot;, False, (0, 0, 0)) screen.blit(pygame.transform.scale(textsurface,(600,110)), (100, 415)) else: myfont = pygame.font.SysFont('Comic Sans MS', 50) textsurface = myfont.render(&quot;Score: &quot;+str(score), False, (0, 0, 0)) if score&gt;=10: screen.blit(textsurface,(10,10)) else: screen.blit(textsurface,(10,10)) pygame.display.update() def clearBackground(screen,screen_height_and_width): bg = pygame.image.load(RunningGame.imagesDirectory()+&quot;whiteImage.png&quot;) screen.blit(pygame.transform.scale(bg,(screen_height_and_width,screen_height_and_width)), (0, 0)) pygame.display.update() def failScreen(screen,screen_height_and_width,score): score+=100000000000000000000000000000000000000000000 failPanel = pygame.image.load(RunningGame.imagesDirectory()+&quot;failScreen.png&quot;) screen.blit(pygame.transform.scale(failPanel,(screen_height_and_width,screen_height_and_width)), (0, 0)) with open(&quot;score.txt&quot;, &quot;a&quot;) as scoreFile: scoreFile.write(&quot;,&quot;+str(score-100000000000000000000000000000000000000000000)) RunningGame.scoreBoard(screen,screen_height_and_width,score) pygame.display.update() time.sleep(2.5) TennisMaster.setUp() def totalScores(scoreFile): totalScoreNumber=0 for number in scoreFile: if number!=1: totalScoreNumber+=number return(totalScoreNumber) def sizeCheck(): ''' sizeOptions=int(input(&quot;Pick your resolution\n1 for 1080p\n2 for 2k\n4 for 4k\n&quot;)) if sizeOptions==1: return(800) elif sizeOptions==2: return(1400) elif sizeOptions==4: return(1900) else: print(&quot;You Failed Basic Directions&quot;) return(1) ''' return(800) <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T20:01:30.330", "Id": "533225", "Score": "0", "body": "I tried to run your code, but the resource files are missing. Do you have a git repo online that we can download from?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T22:59:39.677", "Id": "533230", "Score": "0", "body": "https://github.com/PainEXE/TennisMaster this has the images" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T07:36:10.213", "Id": "533245", "Score": "2", "body": "We require that the code be working correctly, to the best of the author's knowledge, before proceeding with a review. Please [**follow the tour**](https://CodeReview.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://CodeReview.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://CodeReview.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://CodeReview.StackExchange.com/help/dont-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T07:51:55.393", "Id": "533247", "Score": "1", "body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." } ]
[ { "body": "<p>I took a preliminary look at your code. Here are some basic tips:</p>\n<h2>1. Include a link to a repo hosting site.</h2>\n<p>You've got multiple files. You've got image resources. You've got code that computes the names of the images it wants to load!</p>\n<p>This is all smooth and sophisticated, but not if I can't play along...</p>\n<p>I want to be able to see your code the way you have it structured. It won't hurt to show me setting for things like what version of python you are using, etc., which may be in the various config files.</p>\n<h2>2. Black it.</h2>\n<p>There are a lot of code reformatting tools out there. Right now, you are obviously not using one. So install <code>black</code> and run it on your code.</p>\n<p>Why <code>black</code>? Because it works directly and doesn't mess around with too much configuration. You won't spend a week &quot;tweaking my style.&quot; Just run the program, and save the result.</p>\n<h2>3. Reorganize your classes.</h2>\n<p>You have a <code>RunningGame</code> and a <code>TennisMaster</code> class. I assume this is a tennis game. That would make RunningGame the parent and TennisMaster the child class.</p>\n<p>As such, there should be nothing &quot;low level&quot; in Tennis Master. Try to eliminate references to <code>pygame</code> from TennisMaster -- if you have to talk to the support library, that should be a task for the base class. (This may not work if there is some amazing thing that the support library does for the specific subclass. But it's the right attitude to start with - be suspicious of any need to reach too far down. Try to put it in a class or a standalone function.)</p>\n<p>Similarly, there should not be a <code>tennisBall</code> method on Running Game. That is either a method in the wrong place, or a method with the wrong name. In this case, I think wrong place.</p>\n<h2>4. Eliminate magic numbers.</h2>\n<p>You write:</p>\n<pre><code>x = int(screen_height_and_width / 160) \ny = int(screen_height_and_width / 2 - int(screen_height_and_width / 22))\n</code></pre>\n<p>What do those numbers mean?</p>\n<p>Either use named constants, or use named functions (or methods) to describe what you are doing.</p>\n<pre><code>x = height // NUM_CELLS_HORIZONTAL\n\n# -OR-\n\ny = self.centerline_bottom() \n</code></pre>\n<h2>5. Stop repeating yourself!</h2>\n<p>You have (what I hope is) duplicated code in your <code>tennisBall</code> method. In fact, you've got a few copies of a pygame event loop.</p>\n<p>First, the loop should be in the top-level function and it should call other things.</p>\n<p>Second, don't repeat yourself. If you have multiple copies of code, make a function or method out of them and give it a name. That way, when you add a powerup, you won't have a powerup that only works when the ball is moving right to left.</p>\n<p><strong>Edit:</strong></p>\n<h2>6. Use lowercase file names.</h2>\n<p>Your python files are named the same as the classes they contain. This is irksome but understandable.</p>\n<p>However, you are also using mixed-case file names for your resource files, but you have not actually given the resource files the identically-cased names. For example, 'powerup-3.png' versus &quot;powerUp-3.png&quot;.</p>\n<p>I suspect you are coding under windows, because under Linux those differences actually <em>matter.</em></p>\n<p>The easiest way to address this is to make yourself a simple rule: always use lowercase filenames unless there is a compelling reason not to. (Example: Java requires matching case.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T21:13:59.230", "Id": "270102", "ParentId": "270099", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T19:37:29.020", "Id": "270099", "Score": "1", "Tags": [ "python-3.x", "game", "classes", "pygame" ], "Title": "When I try to re set up my code after failing in the game I cant get it to run the function without its own file being undefined" }
270099
<p>This logic checks different method and adds links to response that is returned to a view. I there a better way to do this ?</p> <pre><code> [HttpGet] [StandaloneResponseFilter] public JsonResult GetMenuLinkList() { List&lt;FlyoutMenuLinkItem&gt; response = new List&lt;FlyoutMenuLinkItem&gt;(); try { var IsDisplayLink = ProfileHelpers.DisplayLink(); var IsGroupLink = ProfileHelpers.DisplayGroupLink(); var favoritePages = ProfileHelpers.GetFavoritePages(); if (IsDisplayLink){ FlyoutMenuLinkItem fmlMI = new FlyoutMenuLinkItem(); fmlMI.PageName = &quot;Portal&quot;; fmlMI.PageURL = &quot;/members/portal&quot;; fmlMI.PageSection = FlyoutMenuLinkItem.Section.MemberPortal; response.Add(fmlMI); } if (IsGroupLink ) { FlyoutMenuLinkItem fmlMD = new FlyoutMenuLinkItem(); fmlMD.PageName = &quot;Group Link&quot;; fmlMD.PageURL = &quot;/meetings/disclosures&quot;; fmlMD.PageSection = FlyoutMenuLinkItem.Section.MeetingsDisclosures; response.Add(fmlMD); } if (favoritePages != null) { foreach (FavoritePage f in favoritePages) { FlyoutMenuLinkItem fmlFav = new FlyoutMenuLinkItem(); fmlFav.PageName = f.PageName; fmlFav.PageURL = f.Url; fmlFav.PageSection = FlyoutMenuLinkItem.Section.MyPages; response.Add(fmlFav); } } } catch (Exception e) { Log.Write(e, ConfigurationPolicy.ErrorLog); } } return Json(response, JsonRequestBehavior.AllowGet); } </code></pre>
[]
[ { "body": "<p>it seems <code>DisplayLink()</code> , <code>DisplayGroupLink()</code> have a bad naming, which made you store them in a variable with a better naming. if you're working on old code that has not followed good practices, I would suggest you avoid using it directly, and instead, implement a new class that would follow good practices, and use it instead. Then, you can then mark old code as an <code>Obsolete</code>.</p>\n<p>For your code portion, you can either create a method to create a menu link OR (better) add a constructor to <code>FlyoutMenuLinkItem</code> that accepts three arguments you need to create a new <code>FlyoutMenuLinkItem</code> :</p>\n<pre><code>public class FlyoutMenuLinkItem\n{\n FlyoutMenuLinkItem() { }\n FlyoutMenuLinkItem(string name, string url, FlyoutMenuLinkItem.Section section) { ... }\n}\n</code></pre>\n<p>Now, you can do this :</p>\n<pre><code>if (IsDisplayLink)\n{\n response.Add(new FlyoutMenuLinkItem(&quot;Portal&quot;, &quot;/members/portal&quot;, FlyoutMenuLinkItem.Section.MemberPortal);\n}\n\n\nif (IsGroupLink)\n{\n response.Add(new FlyoutMenuLinkItem(&quot;Group Link&quot;, &quot;/meetings/disclosures&quot;, FlyoutMenuLinkItem.Section.MeetingsDisclosures);\n}\n\n\nif (favoritePages != null)\n{\n response.AddRange(favoritePages.Select(x=&gt; new FlyoutMenuLinkItem(x.PageName, x.Url, FlyoutMenuLinkItem.Section.MyPages)));\n}\n</code></pre>\n<p>Also, a private method would do the same if you don't have access to <code>FlyoutMenuLinkItem</code> :</p>\n<pre><code>private FlyoutMenuLinkItem CreateMenuLink(string name, string url, FlyoutMenuLinkItem.Section section)\n{\n return new FlyoutMenuLinkItem\n {\n PageName = name,\n PageURL = url,\n PageSection = section\n };\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T13:06:09.880", "Id": "533258", "Score": "0", "body": "Thanks when you say constructor to FlyoutMenuLinkItem that accepts three arguments is that the private method ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T13:10:21.393", "Id": "533259", "Score": "0", "body": "@Jefferson the constructor is for the `FlyoutMenuLinkItem`, if you cannot change `FlyoutMenuLinkItem` constructors, then you create a private method with the same arguments just like the last example in my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T13:12:41.923", "Id": "533260", "Score": "0", "body": "So in the model I would add a constructor ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T13:13:19.333", "Id": "533261", "Score": "1", "body": "@Jefferson yes, that's correct." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T08:34:48.653", "Id": "270109", "ParentId": "270101", "Score": "1" } } ]
{ "AcceptedAnswerId": "270109", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T21:08:03.083", "Id": "270101", "Score": "1", "Tags": [ "c#", "asp.net-mvc" ], "Title": "JsonResult Building menu" }
270101
<p>I have created a template class <code>Gallery</code> which is intended to be used as a container for objects. I used a private member of type<code>std::map</code> to maintain the collection alongside other functions. This class was not intended to be used on production code but rather to help me practice design and coding skills. I tried to incorporate <strong>templates, Inheritance, Polymorphism, smart pointers, mutators and accessors</strong>, a few <strong>data structures, operator overloading, the big five</strong>, and <strong>exceptions</strong>. The driver Program doesn't test everything since I tried to save on space.</p> <p>Be gentle, I am only a newbie.</p> <p>How can this class be designed and written better?</p> <pre><code>/** The Gallery Class can be used to hold a map of objects that has some sort of unique identifier. The object should implement the functions: const Identifier&amp; getName(); std::unique_ptr&lt;LabeledObject&gt; clone() const; overload: &lt;, ==, &gt;, and &lt;&lt; */ #ifndef GALLERY_H #define GALLERY_H #include &lt;map&gt; #include &lt;unordered_set&gt; #include &lt;string&gt; #include &lt;iostream&gt; #include &quot;shape.h&quot; // Gallery of Objects template&lt;typename LabeledObject, typename Identifier&gt; class Gallery{ public: /// constructors Gallery() = default; Gallery(const Gallery&amp; galleryB); Gallery(Gallery&amp;&amp; galleryB); /// getters LabeledObject&amp; objectCheckOut(const Identifier&amp; name); const LabeledObject&amp; viewObject(const Identifier&amp; name) const; /// overloaded operators Gallery&amp; operator=(const Gallery&amp; galleryB); Gallery&amp; operator=(Gallery&amp;&amp; galleryB); bool operator&lt;(const Gallery&amp; galleryB) const; // compare sizes bool operator&gt;(const Gallery&amp; galleryB) const; // compare sizes bool operator==(const Gallery&amp; galleryB) const; // compare owned objects Gallery&amp; operator+(const Gallery&amp; galleryB); // append galleryB's objects Gallery&amp; operator-(const Gallery&amp; galleryB); // erase objects that resemble galleryB's objects template&lt;typename T, typename U&gt; friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, Gallery&lt;T,U&gt; galleryB); /// other utility functions void removeObject(const Identifier&amp; name); bool isCheckedOut(const Identifier&amp; name) const; bool objectExists(const Identifier&amp; name) const; void objectCheckIn(const Identifier&amp; name); void addObject(const LabeledObject&amp; obj); private: // boolean to show if checked out std::map&lt;Identifier, std::pair&lt;std::unique_ptr&lt;LabeledObject&gt;, bool&gt;&gt; objectsMap; /// private exception classes class GalleryException{ private: std::string description; public: GalleryException(const std::string&amp; description = &quot;Exception Occurred in Gallery Class&quot;) : description(description){} const std::string&amp; getException() const; }; class ObjectCheckedOut : public GalleryException{ public: ObjectCheckedOut(const std::string&amp; description = &quot;Object Checked Out Exception Occurred in Gallery Class&quot;) : GalleryException(description){} }; class ObjectNotInGallery: public GalleryException{ public: ObjectNotInGallery(const std::string&amp; description = &quot;Object Not In Gallery Exception Occurred in Gallery Class&quot;) : GalleryException(description){} }; class ObjectNotCheckedOut: public GalleryException{ public: ObjectNotCheckedOut(const std::string&amp; description = &quot;Object Not Checked Out Exception Occurred in Gallery Class&quot;) : GalleryException(description){} }; /// private functions void appendToGallery(const Gallery&amp; galleryB); static void handleException(GalleryException&amp;&amp;); }; #endif /************************************************************************************************ ************************************************************************************************* * FUNCTION DEFINITIONS * * ----------------------------- * * Note that our class is a template hence functions are best defined within the.h file * * * ************************************************************************************************* *************************************************************************************************/ /// constructors /// copy constructor template&lt;typename LabeledObject, typename Identifier&gt; Gallery&lt;LabeledObject,Identifier&gt;::Gallery(const Gallery&amp; galleryB){ appendToGallery(galleryB); } /// move constructor template&lt;typename LabeledObject, typename Identifier&gt; Gallery&lt;LabeledObject, Identifier&gt;::Gallery(Gallery&amp;&amp; galleryB) :objectsMap(std::move(galleryB.objectsMap)){} /// getters /// viewObject template&lt;typename LabeledObject, typename Identifier&gt; const LabeledObject&amp; Gallery&lt;LabeledObject, Identifier&gt;::viewObject(const Identifier&amp; key) const{ if(!objectExists(key)) handleException(ObjectNotInGallery()); else if(isCheckedOut(key)) handleException(ObjectCheckedOut()); // returning reference of unique_ptr from : [Identifier, {unique_ptr, true/false}] return *((objectsMap.find(key) -&gt; second).first); } /// objectCheckOut template&lt;typename LabeledObject, typename Identifier&gt; LabeledObject&amp; Gallery&lt;LabeledObject, Identifier&gt;::objectCheckOut(const Identifier&amp; key){ if(!objectExists(key)) handleException(ObjectNotInGallery()); else if(isCheckedOut(key)) handleException(ObjectCheckedOut()); // change false to true in mapElement : [Identifier, {unique_ptr, false}] objectsMap[key].second = true; // label as checked out return *(objectsMap[key].first); } /// utility functions /// addObject template&lt;typename LabeledObject, typename Identifier&gt; void Gallery&lt;LabeledObject, Identifier&gt;::addObject(const LabeledObject&amp; obj){ // new Element is in the form [Identifier, {unique_ptr, true/false}] objectsMap[obj.getName()] = std::make_pair(obj.clone(), false); } /// objectCheckIn template&lt;typename LabeledObject, typename Identifier&gt; void Gallery&lt;LabeledObject, Identifier&gt;::objectCheckIn(const Identifier&amp; key){ objectsMap[key].second = false; } /// removeObject template&lt;typename LabeledObject, typename Identifier&gt; void Gallery&lt;LabeledObject, Identifier&gt;::removeObject(const Identifier&amp; key) { if(objectExists(key)) objectsMap.erase(key); } /// isCheckedOut template&lt;typename LabeledObject, typename Identifier&gt; bool Gallery&lt;LabeledObject, Identifier&gt;::isCheckedOut(const Identifier&amp; key) const{ //find() returns true/false form : [Identifier, {unique_ptr, true/false}] return objectExists(key) &amp;&amp; (objectsMap.find(key)-&gt; second).second; } /// objectExists template&lt;typename LabeledObject, typename Identifier&gt; bool Gallery&lt;LabeledObject, Identifier&gt;::objectExists(const Identifier&amp; key) const{ return objectsMap.find(key) != objectsMap.end(); } /// overloaded operators /// assignment operator template&lt;typename LabeledObject, typename Identifier&gt; Gallery&lt;LabeledObject, Identifier&gt;&amp; Gallery&lt;LabeledObject, Identifier&gt;::operator=(const Gallery&amp; galleryB){ if(objectsMap != galleryB.objectsMap){ objectsMap.clear(); appendToGallery(galleryB); } return *this; } /// move assignment template&lt;typename LabeledObject, typename Identifier&gt; Gallery&lt;LabeledObject, Identifier&gt;&amp; Gallery&lt;LabeledObject, Identifier&gt;::operator=(Gallery&amp;&amp; galleryB){ objectsMap = std::move(galleryB.objectsMap); return *this; } /// == operator template&lt;typename LabeledObject, typename Identifier&gt; bool Gallery&lt;LabeledObject, Identifier&gt;::operator==(const Gallery&amp; galleryB) const{ return objectsMap.size() == galleryB.objectsMap.size(); } /// &lt; operator template&lt;typename LabeledObject, typename Identifier&gt; bool Gallery&lt;LabeledObject, Identifier&gt;::operator&lt;(const Gallery&amp; galleryB) const{ return objectsMap.size() &lt; galleryB.objectsMap.size(); } /// &gt; operator template&lt;typename LabeledObject, typename Identifier&gt; bool Gallery&lt;LabeledObject, Identifier&gt;::operator&gt;(const Gallery&amp; galleryB) const{ return objectsMap.size() &gt; galleryB.objectsMap.size(); } /// + operator template&lt;typename LabeledObject, typename Identifier&gt; Gallery&lt;LabeledObject, Identifier&gt;&amp; Gallery&lt;LabeledObject, Identifier&gt;::operator+(const Gallery&amp; galleryB){ appendToGallery(galleryB); return *this; } /// - operator template&lt;typename LabeledObject, typename Identifier&gt; Gallery&lt;LabeledObject, Identifier&gt;&amp; Gallery&lt;LabeledObject, Identifier&gt;::operator-(const Gallery&amp; galleryB){ for(auto it = galleryB.objectsMap.begin(); it != galleryB.objectsMap.end(); ++it) removeObject(it -&gt; first); return *this; } /// &lt;&lt; operator template&lt;typename LabeledObject, typename Identifier&gt; std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, Gallery&lt;LabeledObject, Identifier&gt; galleryB){ // it points to an element in the form : [Identifier, {unique_ptr, true/false}] for(auto it = galleryB.objectsMap.begin(); it != galleryB.objectsMap.end(); ++it){ std::string status = (it -&gt; second).second ? &quot;checked out \n&quot; :&quot;available \n&quot;; out &lt;&lt; &quot;This Object is &quot; &lt;&lt; status; out &lt;&lt; ((it -&gt;second).first) -&gt; clone(); } return out; } /// private member functions /// appendToGallery template&lt;typename LabeledObject, typename Identifier&gt; void Gallery&lt;LabeledObject, Identifier&gt;::appendToGallery(const Gallery&lt;LabeledObject, Identifier&gt;&amp; galleryB){ // s is in the form : [Identifier, {unique_ptr, true/false}] for(auto s = galleryB.objectsMap.begin(); s != galleryB.objectsMap.end(); ++s) addObject(*((s -&gt; second).first)); } /// handleException template&lt;typename LabeledObject, typename Identifier&gt; void Gallery&lt;LabeledObject, Identifier&gt;::handleException(GalleryException&amp;&amp; exp){ try{ throw exp; }catch(GalleryException){ std::cout &lt;&lt; exp.getException(); } } /// functions of private member classes /// getException template&lt;typename LabeledObject, typename Identifier&gt; const std::string&amp; Gallery&lt;LabeledObject, Identifier&gt;::GalleryException::getException() const{ return description; } /****************************************** /* DRIVER PROGRAM /*****************************************/ #include &lt;iostream&gt; #include &lt;vector&gt; #include &quot;location.h&quot; #include &quot;shape.h&quot; #include &quot;circle.h&quot; #include &quot;rectangle.h&quot; #include &quot;gallery.h&quot; using namespace std; int main() { Location a(2,4, &quot;A&quot;); Location c(5,3, &quot;C&quot;); vector&lt;shared_ptr&lt;Shape&gt;&gt; shapes {make_shared&lt;Shape&gt;(c, &quot;Tree&quot;, 35), make_shared&lt;Circle&gt;(c, &quot;Circle C&quot;, 4), make_shared&lt;Rectangle&gt;(c, 6, 7, &quot;Rec1&quot;)}; Gallery&lt;Shape, std::string&gt; g, h; for(auto s: shapes) g.addObject(*c); h = g; cout &lt;&lt; g &lt;&lt; h; return 0; } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T23:29:08.397", "Id": "533231", "Score": "3", "body": "Welcome to Code Review! I [changed the title](https://codereview.stackexchange.com/posts/270103/revisions#rev-body-ad82d9b8-eb49-443e-b18d-4eb9e9538999) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T23:30:09.490", "Id": "533232", "Score": "3", "body": "Also it would benefit reviewers to have a bit more information about the code in the description. From [the help center page _How to ask_](https://codereview.stackexchange.com/help/how-to-ask): \"_You will get more insightful reviews if you not only provide your code, but also give an explanation of what it does. The more detail, the better._\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T23:49:05.767", "Id": "533233", "Score": "1", "body": "I added some context @SᴀᴍOnᴇᴌᴀ. Does that help?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T23:55:19.193", "Id": "533234", "Score": "1", "body": "Thanks @Shwalala. TBH c++ isn't my realm of expertise but it looks better. I could be wrong but it may help reviewers to see example code that uses the class." } ]
[ { "body": "<p>First impression: looking good.</p>\n<pre><code>#ifndef GALLERY_H\n#define GALLERY_H\n</code></pre>\n<p>The name is hardly unique. In real code, you need to consider that programs will include headers (possibly indirectly, several levels deep) from different unrelated libraries. Any simple name has a serious possibility of clashing.</p>\n<p>Use a UUID for this.</p>\n<p>Later: why is the <code>#endif</code> in the middle of the file? If you've already included the file, why do you want to repeat the template body definitions?</p>\n<hr />\n<pre><code>template&lt;typename LabeledObject, typename Identifier&gt; class Gallery{\n</code></pre>\n<p>I think the template arguments are backwards. It should work like <code>map</code>, with the key being first.</p>\n<hr />\n<blockquote>\n<p>overload: &lt;, ==, &gt;,</p>\n</blockquote>\n<p>Do you know about the new three-way comparison operator? You don't need separate relational operators anymore. These will be automatically generated from the &quot;master&quot; three-way comparison. Look up <code>operator&lt;=&gt;</code></p>\n<p>But wait a minute... <code>&lt;</code> and <code>&gt;</code> compare <em>sizes</em>, while <code>==</code> compares &quot;owned objects&quot;? That sounds like a bad idea.</p>\n<hr />\n<p><code>GalleryException(const std::string&amp; description = &quot;Exception Occurred in Gallery Class&quot;)</code><br />\nYou should generally use <code>string_view</code> (by value) for parameters taking strings. This being a constructor &quot;sink&quot; parameter, you might instead use the &quot;sink&quot; idiom which takes a string <em>by value</em>. Anytime the default argument is used, it creates a fresh <code>string</code> instance and copies the text into it; then it copies again to the member and deletes the first copy.</p>\n<p>Is <code>GetException</code> the right name for something that gets a descriptive string? It's not derived from <code>std::exception</code> so it's (hopefully) not being used as an exception, and this is nothing more than a wrapper around a string, so I don't really know why you have a hierarchy here.</p>\n<hr />\n<p>Trivial (especially single-function-call) template bodies should just be defined inline in the class. There's no reason to move them out into a separate definition, especially if it's in the same source file anyway. The template verbiage is longer than the body being supplied! This is especially true for constructors and simple accessors.</p>\n<hr />\n<p>You don't have to put a comment on the copy constructor that says <code>//copy constructor</code>. We expect people to be able to read the code. Comments should add something, or give context, not restate what the code says.</p>\n<hr />\n<p><strike>I'm thinking the copy constructor and move constructor can just be <code>=default</code>. Am I missing something? You're just copying/moving the underlying instance data, right?</strike>\nThe move constructor can just be <code>=default</code>, since the generated body will just move all the data members. Implementing copy constructor to call <code>appendToGallery</code> is a sound design. (not so much the name <code>appendToGallery</code> though. Look at the standard library containers: you don't have <code>appendToMap</code> and <code>appendToVector</code> and <code>appendStrings</code> etc. You just have <code>append</code> and it appends to whatever object it's called on.)</p>\n<hr />\n<pre><code> if(!objectExists(key))\n handleException(ObjectNotInGallery());\n</code></pre>\n<p>Hmm, another case where your nomenclature causes confusion. You call the function to raise an exception <code>handleException</code>? Handling is when you <em>catch</em> the thing.</p>\n<hr />\n<p>I see the same two preconditions in the next function body. Move that to common code so you only have to say it once.</p>\n<hr />\n<pre><code> template&lt;typename LabeledObject, typename Identifier&gt;\n void Gallery&lt;LabeledObject, Identifier&gt;::handleException(GalleryException&amp;&amp; exp) \n {\n try{\n throw exp;\n }catch(GalleryException){\n std::cout &lt;&lt; exp.getException();\n }\n }\n</code></pre>\n<p>Whaaaaat??<br />\nYou throw the object only to immediately catch it and then you return to the caller to continue, even though the preconditions have not been met?</p>\n<p>And, you're printing the <em>original</em> parameter that you threw, not the thing you caught, and you're catching by value which makes a copy. This is seriously messed up.</p>\n<p>How can the code possibly work if this function catches its own error and then returns, essentially doing nothing? The body of the caller will proceed as if the check had not failed... if that's possible, why did you need to check? Did you test this?</p>\n<p>Looking back at one of those uses:</p>\n<pre><code> template&lt;typename LabeledObject, typename Identifier&gt;\n LabeledObject&amp; Gallery&lt;LabeledObject, Identifier&gt;::objectCheckOut(const Identifier&amp; key){\n if(!objectExists(key))\n handleException(ObjectNotInGallery());\n else if(isCheckedOut(key))\n handleException(ObjectCheckedOut());\n/// what happens after handleException returns??????\n // change false to true in mapElement : [Identifier, {unique_ptr, false}]\n objectsMap[key].second = true; // label as checked out\n return *(objectsMap[key].first);\n }\n</code></pre>\n<p>You use <code>objectsMap[key]</code> <em>twice</em> when looking up in a map is expensive. You should look up once and keep using the same reference or iterator to what was found.</p>\n<pre><code> auto&amp; [obj,co]= objectsMap[key];\n co= true;\n return *obj\n</code></pre>\n<p>Here, you also look up the same map in each of the precondition checks, which are buried inside other function calls. This is very inefficient.</p>\n<p>I'd write it more like this:</p>\n<pre><code>auto std::indirectly_readable it = lookup(key); //throws if not present or already checked out.\nauto&amp; [obj,co]= *it;\nco= true;\nreturn *obj\n</code></pre>\n<p>The implementation of <code>lookup</code> should directly call <code>map::find</code> and check the resulting iterator against the end. Then, check (through that iterator) if it's already checked out; then return that iterator.</p>\n<p>As for what it throws if there is a problem...<br />\nIf you needed a hierarchy to represent different errors, you would derive from a standard base class and implement <code>what</code>. Don't make unrelated objects and make up your own naming convention for getting the string out of it!</p>\n<p>But don't do that.</p>\n<p>You are not adding any additional information, so just provide an <strong>error code</strong>. Make an enumeration of the different errors, and put the associated strings in an <strong>error category</strong> structure. Throw the <a href=\"https://en.cppreference.com/w/cpp/error/system_error\" rel=\"nofollow noreferrer\">existing <code>std</code> class that holds an error code</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T03:24:02.100", "Id": "533235", "Score": "0", "body": "I responded to your Answer on the answer below:" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T17:30:55.697", "Id": "533277", "Score": "0", "body": "#1. I used ```#endif``` since I had a separate **gallery.cpp** file. I ran into too many problems using template functions in that manner. So I ended up copy pasting the entire contents of the **gallery.cpp** file into the **gallery.h** file. I tried moving ```#endif``` to the end of the file but it still requires me to full qualify the class name with its template parameters in the function definitions. Is that the expected behavior?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T16:38:03.720", "Id": "533343", "Score": "0", "body": "The `#endif` has nothing to do with the syntax of member templates defined outside of their class body. It is a pure text based thing, not anything like a `namespace`. Try `#including` that header file twice, and see if it causes any errors or other issues. That is what the `#if`/`#endif` is there for." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T00:56:22.257", "Id": "270104", "ParentId": "270103", "Score": "1" } } ]
{ "AcceptedAnswerId": "270104", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-15T22:52:12.670", "Id": "270103", "Score": "2", "Tags": [ "c++", "beginner", "template", "classes", "polymorphism" ], "Title": "Gallery template class" }
270103
<p>I finally got this working but I am concerned I am being 'too' specific in my tests, and also that I am repeating myself a significant amount.</p> <p>I could also combine all of the failures into a single test but that feels incorrect as I could change max to 500 and then the entire thing would fail.</p> <p>Namely, I am not happy with the <code>article = build</code> sets everywhere, but is it correct?</p> <p><code>articles.rb</code> - Factory</p> <pre><code>require 'faker' # Article Specs # Title - Min 6, Max 100 # Desc - Min 10, Max 400 FactoryBot.define do factory :article do trait :short_title do title { Faker::Lorem.characters(number: 5) } end trait :long_title do title { Faker::Lorem.characters(number: 101) } end trait :short_desc do description { Faker::Lorem.characters(number: 9) } end trait :long_desc do description { Faker::Lorem.characters(number: 401) } end title { Faker::Lorem.characters(number: 8) } description { Faker::Lorem.characters(number: 53) } end end </code></pre> <p><code>articles_controller_test.rb</code></p> <pre><code>require &quot;test_helper&quot; require &quot;faker&quot; class ArticlesControllerTest &lt; ActionDispatch::IntegrationTest setup do @article = build(:article) end test &quot;should get index&quot; do get articles_url assert_response :success end test &quot;should get new&quot; do get new_article_url assert_response :success end test &quot;should create article&quot; do assert_difference('Article.count') do post articles_url, params: { article: { description: @article.description, title: @article.title }} end end test &quot;should deny due to small desc size&quot; do article = build(:article, :short_desc) assert_no_difference('Article.count') do post articles_url, params: { article: { description: article.description, title: article.title }} end end test &quot;should deny due to long desc size&quot; do article = build(:article, :long_desc) assert_no_difference('Article.count') do post articles_url, params: { article: { description: article.description, title: article.title }} end end test &quot;should deny due to small title size&quot; do article = build(:article, :short_title) assert_no_difference('Article.count') do post articles_url, params: { article: { description: article.description, title: article.title }} end end test &quot;should deny due to large title size&quot; do article = build(:article, :long_title) assert_no_difference('Article.count') do post articles_url, params: { article: { description: article.description, title: article.title }} end end end <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>Approaching duplication in test one should usually be very careful not to introduce unnecessary dependencies between the <strong>test</strong> and <strong>fixtures</strong>.</p>\n<p>Oftentimes we encounter <strong>accidental duplication</strong> between tests that gets too eagerly removed - like creating some kind of helper for test inputs and then relaying too much on its implementation in test (ofc you want to relay on the helper to some degree - like if you want something to be valid number when its a helper for numbers etc.).<br />\nWhen we not remove it we have seemingly repeated setup of inputs - but as long as these inputs could be different in each test such duplication should be fine.</p>\n<p>I would even dare to argue that making the <code>@article</code> instance variable is already a little too much and would let it be test local variable (with perhaps different per-test name as it may be different kind of article and this difference could be conveyed in name).</p>\n<p>The main idea why such &quot;&quot;duplication&quot;&quot; is acceptable is because we usually consider test self-containment as more valuable:</p>\n<ol>\n<li>its easier to reason about something if it has no hidden dependencies</li>\n<li>refactoring self contained chunks of code is easier that ones with hidden dependencies</li>\n</ol>\n<p>On the other hand I would consider the duplication of making the request based of <code>article</code> instance - as this is not something per-test specific (like test input) but rather a reflection of implementation and would change with it (adding something to the body would currently require changes in multiple tests and while it could be in one place).</p>\n<p>BTW as you have yourself noticed changing max in factory could break the tests - which means it is a currently hidden (from the test perspective) dependency. I would consider making it explicit in tests - which, honestly would be quite readable to see test for posting an article failing because it is too long (or to short) and seeing <strong>exactly what it means</strong>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T14:45:40.360", "Id": "533267", "Score": "0", "body": "Wouldn't making every article instance be local to the test in itself go against Rails principles? If I am doing `article = build(:article)` in every test that should pass, I'm repeating myself a lot. The setup section is how the documentation declares to pass in the Fixture." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T10:18:28.280", "Id": "533318", "Score": "0", "body": "Are you really repeating yourself? Is it meaningful repetition? Or maybe its just you typing a little bit more? How easy to change is solution with and without duplication? Note that even with mutable instance variable you are already reassigning values quite often - have you considered how default article \"pollutes\" scope of tests where it is not needed? \nYou don't have to believe me - see discussion (and the post) in [here](https://news.ycombinator.com/item?id=22022466) by a lot of experienced developers and make your own mind." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T11:09:04.443", "Id": "270113", "ParentId": "270106", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T01:50:17.417", "Id": "270106", "Score": "1", "Tags": [ "unit-testing", "ruby-on-rails" ], "Title": "Optimize Tests in Rails6 - Minitest - Factory" }
270106
<p>I just implemented the Kosaraju's algorithm in Go. I tried to implement the same algorithm that is described in <a href="https://en.wikipedia.org/wiki/Kosaraju%27s_algorithm" rel="nofollow noreferrer">the relevant Wikipedia page</a>:</p> <pre class="lang-none prettyprint-override"><code>For each vertex u of the graph, mark u as unvisited. Let L be empty. For each vertex u of the graph do Visit(u), where Visit(u) is the recursive subroutine: If u is unvisited then: Mark u as visited. For each out-neighbour v of u, do Visit(v). Prepend u to L. Otherwise do nothing. For each element u of L in order, do Assign(u,u) where Assign(u,root) is the recursive subroutine: If u has not been assigned to a component then: Assign u as belonging to the component whose root is root. For each in-neighbour v of u, do Assign(v,root). Otherwise do nothing. </code></pre> <p>The Go code works as expected (i.e. gives the correct result), but it's unexpectedly slow. I implemented the very same algorithm in C# (.net 5) and got a 3x speedup. I would expect that Go would be at least as fast as C#... not 3x slower.</p> <p>I'm here to see if I did something particularly bad in my Go code, performance-wise. I'm also open to criticism on the readability of my Go code -- I'm new to Go.</p> <p>Here's the implementation file and the test file.</p> <pre class="lang-golang prettyprint-override"><code>package main var emptyStruct struct{} type Graph struct { edges map[interface{}]map[interface{}]int inNeighbors map[interface{}]map[interface{}]struct{} } func NewGraph(expectedNodes int) *Graph { return &amp;Graph{ edges: make(map[interface{}]map[interface{}]int, expectedNodes), inNeighbors: make(map[interface{}]map[interface{}]struct{}, expectedNodes), } } func (graph *Graph) Connect(vertexFrom interface{}, vertexTo interface{}, weight int) { if _, ok := graph.edges[vertexFrom]; !ok { graph.edges[vertexFrom] = make(map[interface{}]int, len(graph.edges)) graph.inNeighbors[vertexFrom] = make(map[interface{}]struct{}, len(graph.inNeighbors)) } if _, ok := graph.edges[vertexTo]; !ok { graph.edges[vertexTo] = make(map[interface{}]int, len(graph.edges)) graph.inNeighbors[vertexTo] = make(map[interface{}]struct{}, len(graph.inNeighbors)) } graph.edges[vertexFrom][vertexTo] = weight graph.inNeighbors[vertexTo][vertexFrom] = emptyStruct } func (graph *Graph) FindAllOutNeighbors(vertex interface{}) map[interface{}]struct{} { keys := make(map[interface{}]struct{}, len(graph.edges)) for key := range graph.edges[vertex] { keys[key] = emptyStruct } return keys } func (graph *Graph) FindAllInNeighbors(vertex interface{}) map[interface{}]struct{} { keys := make(map[interface{}]struct{}, len(graph.edges)) for key := range graph.inNeighbors[vertex] { keys[key] = emptyStruct } return keys } func (graph *Graph) FindAllVertices() map[interface{}]struct{} { keys := make(map[interface{}]struct{}, len(graph.edges)) for key := range graph.edges { keys[key] = emptyStruct } return keys } func (graph *Graph) FindConnectedComponents() map[interface{}]map[interface{}]struct{} { var visit func(interface{}, map[interface{}]struct{}, *[]interface{}) var assign func(interface{}, interface{}, map[interface{}]map[interface{}]struct{}) visit = func(vertex interface{}, unvisited map[interface{}]struct{}, L *[]interface{}) { if _, ok := unvisited[vertex]; ok { delete(unvisited, vertex) for neighbor := range graph.FindAllOutNeighbors(vertex) { visit(neighbor, unvisited, L) } *L = append(*L, vertex) } } assign = func(vertex interface{}, root interface{}, components map[interface{}]map[interface{}]struct{}) { hasBeenAssigned := false for root := range components { if _, ok := components[root][vertex]; ok { hasBeenAssigned = true break } } if !hasBeenAssigned { if _, ok := components[root]; !ok { components[root] = make(map[interface{}]struct{}) } components[root][vertex] = emptyStruct for neighbor := range graph.FindAllInNeighbors(vertex) { assign(neighbor, root, components) } } } unvisited := graph.FindAllVertices() L := make([]interface{}, 0, len(unvisited)) for vertex := range graph.FindAllVertices() { visit(vertex, unvisited, &amp;L) } components := make(map[interface{}]map[interface{}]struct{}) for i := len(L) - 1; i &gt;= 0; i -= 1 { assign(L[i], L[i], components) } return components } </code></pre> <pre class="lang-golang prettyprint-override"><code>package main import &quot;testing&quot; func TestFindConnectedComponents(t *testing.T) { graph := NewGraph(8) graph.Connect(&quot;1&quot;, &quot;2&quot;, 1) graph.Connect(&quot;2&quot;, &quot;3&quot;, 1) graph.Connect(&quot;2&quot;, &quot;4&quot;, 1) graph.Connect(&quot;3&quot;, &quot;1&quot;, 1) graph.Connect(&quot;3&quot;, &quot;4&quot;, 1) graph.Connect(&quot;4&quot;, &quot;5&quot;, 1) graph.Connect(&quot;5&quot;, &quot;4&quot;, 1) graph.Connect(&quot;6&quot;, &quot;7&quot;, 1) graph.Connect(&quot;6&quot;, &quot;5&quot;, 1) graph.Connect(&quot;7&quot;, &quot;6&quot;, 1) graph.Connect(&quot;7&quot;, &quot;8&quot;, 1) graph.Connect(&quot;8&quot;, &quot;7&quot;, 1) graph.Connect(&quot;8&quot;, &quot;5&quot;, 1) components := graph.FindConnectedComponents() if len(components) != 3 { t.Fatalf(&quot;Expected 3 components, found %d&quot;, len(components)) } } <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T07:08:13.323", "Id": "270108", "Score": "0", "Tags": [ "performance", "graph", "go" ], "Title": "Kosaraju's algorithm is too slow" }
270108
<p>I have some code that uses a <code>lambda</code> to enhance the functionality. For backward compatibility reasons, this lambda can take one or two arguments. To handle these cases, I now use <code>except TypeError</code> to differentiate in the calls:</p> <pre><code># This should work for both these cases: # l = lambda x: x+2 # l = lambda x,y: x+y try: value = l(10) except TypeError: value = l(10, 20) </code></pre> <p>This works, but could this be made better? What if I decide to have three or more arguments for example?</p>
[]
[ { "body": "<p>I would move the lambda into a full function. There are some schools of though that lambdas should never be assigned and persisted to variables (the alterative being they're directly passed as arguments.</p>\n<p>What your existing code shows is that you'd like the second argument (<code>y</code>) to be optional with a default value of 2 (or is it 20?). Therefore, you could do:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def l(x, y=2):\n return x + y\n\nvalue = l(10) # 12\nvalue = l(10, 20) # 30\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T18:00:34.873", "Id": "533281", "Score": "0", "body": "Please refrain from answering low-quality questions that are likely to get closed. Once you've answered, that [limits what can be done to improve the question](/help/someone-answers#help-post-body), making it more likely that your efforts are wasted. It's better to wait until the question is properly ready before you answer!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T16:21:36.717", "Id": "270124", "ParentId": "270111", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T10:52:57.187", "Id": "270111", "Score": "0", "Tags": [ "python", "lambda" ], "Title": "Is using except TypeError the right way to do this?" }
270111
<p>I'm experimenting with some variations of validation pattern. I've created Validator class:</p> <pre><code>public class Validator&lt;O&gt; { private O toValidate; private ValidationResult error; private Validator(O object) { this(object, null); } private Validator(O object, ValidationResult existingError) { toValidate = object; error = existingError; } public static &lt;O&gt; Validator&lt;O&gt; toFirstError(O object) { return new Validator&lt;&gt;(object); } private static &lt;O&gt; Validator&lt;O&gt; toFirstError(O object, ValidationResult existingError) { return new Validator&lt;&gt;(object, existingError); } public Validator&lt;O&gt; must(Function&lt;O, ValidationResult&gt; predicate) { if (error != null) { return this; } var validationResult = predicate.apply(toValidate); validationResult.ifInvalid(e -&gt; error = e); return this; } public Validator&lt;O&gt; ifValid(Consumer&lt;O&gt; consumer) { if (error == null) { consumer.accept(toValidate); } return this; } public &lt;N&gt; Validator&lt;N&gt; mapIfValid(Function&lt;O, N&gt; mapFun) { if (error == null) { var newObject = mapFun.apply(toValidate); return toFirstError(newObject, error); } return toFirstError(null, error); } public ValidationResult getFirstError() { if (error == null) { return ValidationResult.valid(); } return error; } public CommandResult&lt;O&gt; toCommandResult() { if (error == null) { return CommandResult.success(toValidate); } return CommandResult.error(error.getErrorCode()); } } </code></pre> <p><code>ValidationResult</code> is pretty simple</p> <pre><code>@AllArgsConstructor(access = AccessLevel.PRIVATE) public class ValidationResult { @Getter private final ErrorCode errorCode; public static ValidationResult valid() { return new ValidationResult(null); } public static ValidationResult error(ErrorCode errorCode) { return new ValidationResult(errorCode); } public boolean isInvalid() { return errorCode != null; } public boolean isValid() { return errorCode == null; } public void ifInvalid(Consumer&lt;ValidationResult&gt; consumer) { if (isInvalid()) { consumer.accept(this); } } @Override public String toString() { if (isValid()) { return &quot;VALID&quot;; } else { return &quot;INVALID[errorCode=%s]&quot;.formatted(errorCode); } } } </code></pre> <p>Next, I have some command handler. And this is the example of how to use the validator:</p> <pre><code>@Override public CommandResult&lt;Profile&gt; handle(CreateProfileCommand command) { return Validator.toFirstError(command) .must(this::userDoNotHaveProfile) .mapIfValid(this::buildProfile) .must(Profile::validate) .ifValid(repository::save) .toCommandResult(); } private ValidationResult userDoNotHaveProfile(CreateProfileCommand command) { var existForUser = repository.existByOwnerId(command.owner()); if (existForUser) { return ValidationResult.error(USER_ALREADY_HAVE_PROFILE); } return ValidationResult.valid(); } private Profile buildProfile(CreateProfileCommand command) { var slug = createUniqueSlug(command.name()); return new Profile( ProfileId.random(), command.owner(), command.name(), slug, Description.empty(), clock.instant() ); } </code></pre> <p>And some domain object with different usage of the validator:</p> <pre><code>public record Profile( ProfileId id, UserAccountId owner, Name name, ProfileSlug slug, Description description, Instant created ) { public ValidationResult validate() { return Validator.toFirstError(this) .must(p -&gt; p.name().validate()) .getFirstError(); } } public record Name( String asString ) { private static final int MIN_LEN = 2; private static final int MAX_LEN = 200; public static Name of(String name) { return new Name(name); } public ProfileSlug createSlug() { return ProfileSlug.of(this); } public ValidationResult validate() { if (asString == null || asString.length() &lt; MIN_LEN || asString.length() &gt; MAX_LEN) { return ValidationResult.error(PROFILE_NAME_INVALID_NAME_LENGTH); } return ValidationResult.valid(); } } </code></pre> <p>This variation in general looks good for me, but the whole logic is inside validation class, and this look a little stupid for me. Maybe I'm reinventing the wheel and this method have its name, or maybe exist lib that implements this pattern?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T06:35:33.807", "Id": "533300", "Score": "1", "body": "Are you aware of \"Bean Validation API\"? And if yes, why do you consider it not suitable?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T07:38:59.250", "Id": "533302", "Score": "1", "body": "1) I'm trying to learn the intuition - it't good or bad idea\n2) Bean Validation means countless annotations, and finally (for me) it looks like 'annotation driven development'\n3) It's hard to valid bussiness logic\n4) Throws exception. I'm learning to code universally, simple code without a dozen of catch blocks" } ]
[ { "body": "<p>Frankly, I have a hard time trying figuring out how the validator is supposed to work. Either the code needs a lot of documentation or it requires comprehensive redesigning.</p>\n<p>I don't understand the purpose of the <code>toFirstError</code> methods. The names suggest that they perform a validation action, but instead they are just static replacements for the constructors. The purpose of having static initialization methods instead of direct constructors, is to allow the initializer to return a different type depending on the parameters. You're not doing that so they are just confusing now.</p>\n<p>I get a feeling that you are trying to mimic Java streams with the validator. But you end up loading responsibilities about converting and processing the input into the validator. This requires you to maintain state in the validator. All this makes the validator unnecessarily complex and may case loss of reusability. Is the ability to make your code look like stream operations worth it? Can you efficiently use the validator as part in a regular Java stream processing?</p>\n<p>Defining each validation criteria as a predicate helps in testing but at the moment each component that requires validation has to know the correct combination of predicates in order to successfully validate an object. You're better of creating a single composite predicate for each class, in which case having the ability to define the validation as a list of predicates becomes a bit useless.</p>\n<p>Regarding your comment about annotation driven development, you are placing validation code into the business objects with the methods that return <code>ValidationResult</code>. You could as well do that with the Bean Validation API I asked about. Your approach is no better, you are still binding your business objects to a single concrete validation library. If you want to use some other way to validate your objects, you then have a lot of useless validation code lying around in your classes. Functionally it's no different and you wouldn't be trying to reinvent the wheel. Whether it is annotation or your own code, the amount of checks is equal and with a well known library you don't force others to learn new undodumented libraries.</p>\n<p>Personally I do not like having validation code in business objects, whether it is Bean Validation API or home grown stuff. It breaks the single responsibility principle. I prefer having validators be separate classes that implement validation rules for a specific class for a specific use case. I have been enough times in a place where I would have wanted to reuse a common data class but have not been able to do so because they have been riddled with validation rules invented by the person who created the first use case.</p>\n<p>Can you report all validation errors in one pass? The code isn't very straightforward but I get the impression that you stop at the first one, right? Not being able to list all validation errors immediately would be a complete deal braker.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T10:30:29.550", "Id": "270148", "ParentId": "270117", "Score": "2" } }, { "body": "<p>In opposition to (just posted) answer @TorbenPutkonen - I think that separating validation from data is exactly against OOP principles (cohesion and encapsulation) and leads to massive duplication of <code>if (something.isValid)</code> checks and ultimately (from my experience) harder to maintain and secure code.</p>\n<p>If you indeed desire to have validation of separate fields summed up in one validation result abstraction (I don't recommend it as I prefer to fail faster, also it introduces no real benefit while heavily complicating the code) then mentioned bean validation api seems the way to go. Incidentally I happened to be in similar discussion on reddit: <a href=\"https://www.reddit.com/r/java/comments/ongysb/bean_validation_vs_calling_validation_methods/\" rel=\"nofollow noreferrer\">https://www.reddit.com/r/java/comments/ongysb/bean_validation_vs_calling_validation_methods/</a></p>\n<p>However if you would like to go for more compiler-relaying way (functional languages inspired) I'd recommend reading <a href=\"https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/\" rel=\"nofollow noreferrer\">the legendary parse don't validate article</a>. Tldr: keep validation with types, if you validate something in constructor then no instance of class is invalidated - guaranteed by compiler.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T11:10:04.040", "Id": "270153", "ParentId": "270117", "Score": "2" } } ]
{ "AcceptedAnswerId": "270148", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T14:18:44.040", "Id": "270117", "Score": "1", "Tags": [ "java", "validation" ], "Title": "my idea of validating data and bussiness logic" }
270117
<p>A hiring company gave me the following challenge:</p> <blockquote> <p>We want a function which accepts a very large list of prices (<code>pricesLst</code>) and returns the largest possible loss a client could have made with only a buy transaction followed by a sell transaction. The largest loss is calculated as <code>pricesLst[index2] - pricesLst[index1]</code> where <code>index1 &lt; index2</code>. Please then write tests for this function to ensure it works as expected guarding against all edge cases you can think of.</p> </blockquote> <p>I did implement my solution, but they told me that it was not good enough. Can someone please tell me what could the issue with my code, and how to improve it?</p> <pre><code>import unittest # Return biggest loss a client made | Time complexity O(n) def find_biggest_loss(prices_list): # Store biggest loss biggest_loss = 0 # Verify data-type and buy/sell transaction pairs. if (type(prices_list) == list) and (len(prices_list)%2 == 0): for i in range(0,len(prices_list)-1,2): try: sell_trans, buy_trans = abs(prices_list[i+1]), abs(prices_list[i]) # Check for loss if sell_trans &lt; buy_trans: new_loss = abs(sell_trans - buy_trans) if biggest_loss &lt; new_loss: biggest_loss = new_loss except: raise TypeError(&quot;The list contains non-numerical values.&quot;) else: raise TypeError(&quot;Non-supported data type! Please use a 'list' containing buy/sell transaction pairs.&quot;) return biggest_loss class Test_find_biggest_loss(unittest.TestCase): # Non-supported parameter data-type def test_parameter_type(self): prices_list1, prices_list2, prices_list3 = 2, &quot;prices&quot;, True with self.assertRaises(TypeError): find_biggest_loss(prices_list1) find_biggest_loss(prices_list2) find_biggest_loss(prices_list3) # Missing value pairs def test_missing_pair_list(self): prices_list = [20,10,10,30,3,6,200,500,1] with self.assertRaises(TypeError): find_biggest_loss(prices_list) # Prices list with postive values def test_postive_values(self): prices_list = [60,5,30,10,6,0,500,200] self.assertEqual(find_biggest_loss(prices_list),300) # Prices list with negative values def test_negative_values(self): prices_list = [-21,-1,-10,-20,-30,-60,-200,-500] self.assertEqual(find_biggest_loss(prices_list), 20) # Empty prices list def test_empty_or_zeros_list(self): prices_list1 = [] prices_list2 = [0,0,0,0] self.assertEqual(find_biggest_loss(prices_list1), 0) self.assertEqual(find_biggest_loss(prices_list2), 0) # Prices list combination values def test_mixed_values(self): prices_list = [-300,240,200,-250,-30,-60, 50, 70, 200, 150, 0,0, 0,-0.1, 50, -30, 5.5,8.7] self.assertEqual(find_biggest_loss(prices_list), 60) # Prices list that has no client losses def test_list_without_losses(self): prices_list = [20,20,30,170,500,700] prices_list = [200,5000,435,9000] self.assertEqual(find_biggest_loss(prices_list), 0) # Prices list that has non-numeric values def test_non_numerical_embedded_values(self): prices_list1 = [1,[2,3,4],5,7] prices_list2 = [1,&quot;ten&quot;,55,False] prices_list3 = [{},{},{},{}] with self.assertRaises(TypeError): find_biggest_loss(prices_list1) find_biggest_loss(prices_list2) find_biggest_loss(prices_list3) if __name__ == &quot;__main__&quot;: unittest.main() <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T14:40:39.613", "Id": "533265", "Score": "0", "body": "I think you misunderstood the problem. You don't get a list of buy/sell pairs, you get a list of daily (?) prices like [100, 237, 42, 93, 17, 140, 121] and you must return that buying at 237 and selling at 17 yields the biggest loss." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T19:10:42.330", "Id": "533287", "Score": "0", "body": "It was stated that each buy transaction is followed by a sell transaction. So, according to the list you provided. The client bought at 100 and sold at 237, making it a profit rather than a loss." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T19:51:30.767", "Id": "533288", "Score": "0", "body": "Your understanding is still incorrect. This question is about something like stock prices and the client buys, holds for some time, then sells. Your job is to find the worst possible investment, which in my example is to buy stock on day 2 when the price is $237 and then sell it again on day 5 when the price is $17. Note that \"A buy followed by a sale\" does not mean that the sale comes immediately afterwards. The client can hold the stock for a while before selling again. The question even says \"index1 < index2\", not \"index1 = index2 - 1\" as you interpret it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T21:51:42.383", "Id": "533376", "Score": "0", "body": "How are you getting the idea that this is a daily or stock prices? And that the client can hold his investment for some time? You are making many assumptions!? I am not sure what you mean with \"The question even says \"index1 < index2\", not \"index1 = index2 - 1\" as you interpret it.\" I didn't say that. Nevertheless, the task literally states that \"pricesLst[index2]-pricesLst[index1\", so to my understanding they mean each sell transaction comes after a buy transaction as they literally also mentioned that \"buy transaction followed by a sell transaction\"\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T08:24:44.780", "Id": "533395", "Score": "1", "body": "The question says \"The largest loss is calculated as pricesLst[index2]-pricesLst[index1] where index1<index2\". In my example, this happens with index1=2 and index2=5. Since 2<5, this is a valid solution. Your algorithm fails to produce that solution and instead suggests a smaller \"biggest loss\", which is simply the wrong answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T08:29:04.647", "Id": "533396", "Score": "1", "body": "If you want a naive but correct algorithm, calculate pricesLst[index2]-pricesLst[index1] for all combinations of index1 and index2 using nested loops, then throw away those results where index1>=index2 and then report the minimum (most negative result) of what remains." } ]
[ { "body": "<p>You may have misinterpreted the question. Still, you've written code based on your interpretation of the problem, and we can still make review comments on that code to help you write better code in the future ...</p>\n<h1>PEP 8</h1>\n<p><a href=\"https://pep8.org/\" rel=\"nofollow noreferrer\">PEP 8: The Style Guide for Python Code</a> enumerates many conventions Python programmers should follow to increase the readability of their code. These include:</p>\n<ul>\n<li>use white space around binary operators</li>\n<li>use white space after commas</li>\n<li>don’t use underscores in class names</li>\n</ul>\n<p>You violate these in a few places. You should use one of the many lint checkers (pylint, pyflakes, ...) to help clean up your code.</p>\n<h1>Exception Handling</h1>\n<p>Your code reads:</p>\n<pre class=\"lang-py prettyprint-override\"><code> for i in range(...):\n try:\n process(...)\n except:\n raise TypeError(&quot;The list contains non-numerical values.&quot;)\n</code></pre>\n<p>There are a few problems with this.</p>\n<h2>Bare Except</h2>\n<p>What kind of Exception are you catching? It looks like you are intending on trapping cases where non-numerical input is given, but it will also catch the entire range of other exceptions, such as <code>NameError</code>, <code>IndexError</code>, <code>ValueError</code>, <code>ZeroDivisionError</code>, <code>KeyError</code>, and so on.</p>\n<p>If you are intent on catching a <code>TypeError</code>, explicitly catch only that kind of exception using <code>except TypeError:</code></p>\n<h2>Loss of Exception Information</h2>\n<p>Not only are you capturing any and all exceptions, you are also forgetting all of the exception information. If you have some other kind of a problem deeper inside the your code, and it raises an exception, you blindly report &quot;The list contains non-numerical values&quot; and destroy any hope of debugging information being available.</p>\n<p>Capture the exception, and report or log the exact issue. Or at the very least, pass the problem details on to the caller.</p>\n<pre class=\"lang-py prettyprint-override\"><code> except TypeError as type_err:\n # Maybe print the problem\n print(&quot;Find biggest loss had this issue: &quot; + type_err)\n\n # Maybe log it somewhere\n log.exception(&quot;Type error in find_biggest_loss&quot;)\n\n # Maybe pass it to the caller with raise-from\n raise TypeError(&quot;The list contains non-numeric values.&quot;) from type_error\n</code></pre>\n<h2>Efficiency</h2>\n<p>Inside your loop, you establish an exception handling context ... and then destroy it and loop back for the next data, recreating the exception handling context, only to again destroy it ad nauseam.</p>\n<p>Switch the order:</p>\n<pre class=\"lang-py prettyprint-override\"><code> try:\n for i in range(...):\n process(...)\n except TypeError as type_error:\n raise TypeError(&quot;The list contains non-numerical values.&quot;) from type_error\n</code></pre>\n<p>Now the try...except context is only created once, which should be more efficient.</p>\n<h2>Define your own exception types</h2>\n<pre class=\"lang-py prettyprint-override\"><code>class LengthError(Exception):\n pass\n\ndef find_biggest_loss(prices_list):\n if type(prices_list) != list:\n raise TypeError(&quot;Not a list&quot;)\n if len(prices_list) % 2 != 0:\n raise LengthError(&quot;List is of the incorrect length -- must be odd&quot;)\n ...\n</code></pre>\n<p>As a bonus, having the checks written in this fashion means the rest of the code doesn’t need as much indentation, thus improving readability.</p>\n<h2>Duck Typing</h2>\n<p>The <a href=\"https://en.wikipedia.org/wiki/Robustness_principle\" rel=\"nofollow noreferrer\">Robustness Principle</a> states &quot;be liberal in what you accept&quot;.</p>\n<p>Does it have to be a <code>list</code>? You could test <code>isinstance(prices_list, list)</code> allowing the <code>prices_list</code> to be a user-defined subtype of <code>list</code>.</p>\n<p>Does it really have to be a <code>list</code>? A <code>tuple</code> would be perfectly acceptable, so <code>isinstance(prices_list, (list, tuple))</code> would be better. But is that enough? A user might define their own indexable container which could work perfectly fine.</p>\n<p>Just use the container given to you. If it doesn't define <code>len(...)</code> or fails on <code>__getitem__</code>, then it fails and will raises an exception all by itself.</p>\n<h1>Loop Like a Native</h1>\n<p>Ned Batchelder has recorded a <a href=\"https://www.youtube.com/watch?v=EnSu9hHGq5o\" rel=\"nofollow noreferrer\">talk</a> on looping in Python. In general, there are always better alternatives to using <code>for index in range(len(container))</code>.</p>\n<p>In this particular case, you want to look at successive elements in <code>prices_list</code>. The <a href=\"https://docs.python.org/3/library/itertools.html#itertools-recipes\" rel=\"nofollow noreferrer\"><code>more_itertools</code> package</a> has a function exactly for this; it is called <code>grouper</code>.</p>\n<p>Let's rewrite the function using it:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from more_itertools import grouper\n\ndef find_biggest_loss(prices_list):\n return max((abs(buy) - abs(sell) for buy, sell in grouper(prices_list, 2)), default=0)\n</code></pre>\n<p>Is that a little too terse? Ok, here it is expanded out a little:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from more_itertools import grouper\n\ndef find_biggest_loss(prices_list):\n\n biggest_loss = 0\n\n for buy, sell in grouper(prices_list, 2):\n loss = abs(buy) - abs(sell)\n if loss &gt; biggest_loss:\n biggest_lost = loss\n\n return biggest_loss\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T21:32:44.237", "Id": "533375", "Score": "0", "body": "Amazing answer, thanks a lot. I couldn't ask for a better answer. Just one more thing, do you think that I misunderstood the question as Rainer P pointed out?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T03:59:18.567", "Id": "533388", "Score": "0", "body": "Did you misunderstand the question? Maybe. Do you have the question source? Do you have a link to it? The way you’ve quoted it, it seems to starts in mid sentence, so I think you haven’t posted the entire question text. Without the definitive question text, I don’t feel comfortable with taking a concrete stance. However, the question you’ve answered is definitely “easier” than Rainer’s interpretation, so I’m leaning towards a “yes, you have misunderstood.”" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T15:45:37.197", "Id": "533431", "Score": "0", "body": "I did include the entier text as it was provided. Nevertheless, here is the task with its exact wording:\n\"We want a function which accepts a very large list of prices (pricesLst) and returns the\nlargest possible loss a client could have made with only a buy transaction followed by a sell\ntransaction. The largest loss is calculated as pricesLst[index2] - pricesLst[index1] where\nindex1 < index2.\nPlease then write tests for this function to ensure it works as expected guarding against all\nedge cases you can think of.\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T11:25:54.293", "Id": "533498", "Score": "0", "body": "'Define your own exception types' - this is bad advice imo, you almost never need to." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T22:12:33.083", "Id": "533553", "Score": "0", "body": "@rak1507 Creating your own exception types is an important tool for your toolkit. Like any tool, it can be overused. In a hiring company's coding challenge, sneaking it into the code is a stealth advertisement that you know Python's exception hierarchy can be extended, so I would absolutely do it in this case. It does open the door for additional interview questions, like what the parent class of the exception should be. I used `Exception` above, but `ValueError` might be more appropriate. It would certainly not be a `TypeError`, which the OP originally raised." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T23:59:22.287", "Id": "270133", "ParentId": "270118", "Score": "6" } } ]
{ "AcceptedAnswerId": "270133", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T14:22:12.347", "Id": "270118", "Score": "4", "Tags": [ "python", "python-3.x", "interview-questions" ], "Title": "Return the biggest loss a client made from prices list" }
270118
<p>I have this JS ajax GET that returns menus to be used in a view. I wanted to see if there is any more way to write this method. Its a lot of code and just wanted to make sure there is no better way to do this?</p> <pre><code> console.log('Processing Login ajax GetMenuLinkList') var url = &quot;/login/GetMenuLinkList&quot;; $.ajax({ type: &quot;GET&quot;, data: param = &quot;&quot;, contentType: &quot;application/json; charset=utf-8&quot;, dataType: &quot;json&quot;, url: url, success: function (data, status) { console.log(data); $('#favoritepagesListBlock').empty(); $('#meetingsanddisclosuresBlock').empty(); $('#memberinstitutionBlock').empty(); $('#orderListBlock').empty(); var orderShowMore = false; var subscriptionShowMore = false; $.each(data, function (index, data) { switch (data.PageSection) { case 1: $('#favoritepagesListBlock').append(&quot;&lt;a class='link-text' href='&quot;+data.Url+&quot;'&gt;&quot; + data.PageName + &quot;&lt;/a&gt;&quot;); break; case 2: $('#meetingsanddisclosuresBlock').append(&quot;&lt;a class='link-text' href='&quot; + data.Url + &quot;'&gt;&quot; + data.PageName + &quot;&lt;/a&gt;&quot;); break; case 3: $('#memberinstitutionBlock').append(&quot;&lt;a class='link-text' href='&quot; + data.Url + &quot;'&gt;&lt;b&gt;&quot; + data.PageName + &quot;&lt;/b&gt;&lt;/a&gt;&quot;); break; case 4: $('#orderListBlock').append(&quot;&lt;a class='link-text' href='&quot; + data.Url + &quot;'&gt;&quot; + data.PageName + &quot;&lt;/a&gt;&quot;); orderShowMore = data.ShowMore; break; case 5: $('#subscriptionListBlock').append(&quot;&lt;a class='link-text' href='&quot; + data.Url + &quot;'&gt;&quot; + data.PageName + &quot;&lt;/a&gt;&quot;); subscriptionShowMore = data.ShowMore; break; } }); if (orderShowMore = true) { $('#orderListBlock').append(&quot;&lt;a class='show-more' href='/home/store/order-history'&gt;View More&lt;/a&gt;&quot;); } if (subscriptionShowMore=true) { $('#subscriptionListBlock').append(&quot;&lt;a class='show-more' href='/home/store/subscriptions'&gt;View More&lt;/a&gt;&quot;); } }, error: function (request, status, error) { // alert(request.responseText); } }); </code></pre>
[]
[ { "body": "<p>First, make your code work. <code>orderShowMore = true</code> is assigning <code>true</code> to <code>orderShowMore</code> - the code in the block after this is inevitably going to get executed. Just go <code>if(orderShowMore)</code>.</p>\n<p>Second, don't use two variables named <code>data</code> - while scoping may make it unambiguous to the compiler, it's confusing to anyone reading your code. Also, consistent indenting goes a long way.</p>\n<p>You really don't need a switch statement there - you're basically repeating almost the same code four or five times. You could assign all the ids to a variable - probably a good idea, since I'm assuming you want to clear <code>$('#subscriptionListBlock')</code> so it doesn't fill up with junk.</p>\n<p>This seems like a perfect oppurtunity to use template strings - you're inserting values into a string, this is pretty much what they're made for.</p>\n<p>You might actually want to look up the <a href=\"https://api.jquery.com/Jquery.ajax/\" rel=\"nofollow noreferrer\"><code>$.ajax</code> docs</a> - You're meant to call with <code>(url, settings)</code> not <code>({url: url})</code>. Also, if you're not sending any data to the server, cut that out - right now, you're assigning an undeclared variable <code>param</code> to an empty string, which could cause errors if run in strict mode.</p>\n<p>Use <code>let</code> and <code>const</code> over <code>var</code> - <code>var</code> allows redeclaration, which can cause problems and make debugging harder.</p>\n<p>Final code:</p>\n<pre class=\"lang-js prettyprint-override\"><code>console.log('Processing Login ajax GetMenuLinkList')\nlet url = &quot;/login/GetMenuLinkList&quot;;\nconst idList = ['#favoritepagesListBlock','#meetingsanddisclosuresBlock','#memberinstitutionBlock','#orderListBlock','#subscriptionListBlock']\n$.ajax(url, {\n type: &quot;GET&quot;,\n contentType: &quot;application/json; charset=utf-8&quot;,\n dataType: &quot;json&quot;,\n success: function (data, status) {\n console.log(data);\n for(id of idList) $(id).empty();\n let orderShowMore = false;\n let subscriptionShowMore = false;\n for(let item of data){\n $(idList[item.PageSection - 1]).append(`&lt;a class='link-text' href='${item.Url}'&gt;${\n item.PageSection == 3 ?\n `&lt;b&gt;${item.PageName}&lt;/b&gt;` :\n iiitem.PageName\n }&lt;/a&gt;`);\n if(item.PageSection == 4) orderShowMore = true;\n if(item.PageSection == 5) subscriptionShowMore = true;\n }\n\n if (orderShowMore) {\n $('#orderListBlock').append(&quot;&lt;a class='show-more' href='/home/store/order-history'&gt;View More&lt;/a&gt;&quot;);\n }\n if (subscriptionShowMore) {\n $('#subscriptionListBlock').append(&quot;&lt;a class='show-more' href='/home/store/subscriptions'&gt;View More&lt;/a&gt;&quot;);\n }\n },\n error: function (request, status, error) {\n //console.log(request.responseText);\n }\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T12:54:01.813", "Id": "533332", "Score": "0", "body": "`idList[data.PageSection - 1])` what is that doing? should it be `item` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T19:00:35.680", "Id": "533366", "Score": "0", "body": "Oops, I misadapted your code. Fixing." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T09:01:10.583", "Id": "270142", "ParentId": "270120", "Score": "2" } }, { "body": "<p>A short review;</p>\n<ul>\n<li><p>You inlined the success function, I would use a properly named function outside of that block</p>\n</li>\n<li><p>This</p>\n<pre><code> $('#favoritepagesListBlock').empty();\n $('#meetingsanddisclosuresBlock').empty();\n $('#memberinstitutionBlock').empty();\n $('#orderListBlock').empty();\n</code></pre>\n<p>can be</p>\n<pre><code> $('#favoritepagesListBlock,#meetingsanddisclosuresBlock,#memberinstitutionBlock,#orderListBlock').empty();\n</code></pre>\n</li>\n<li><p><code>orderShowMore = data.ShowMore;</code> seems like a bug, I would write <code>orderShowMore = orderShowMore || data.ShowMore;</code> Same thing for <code>subscriptionShowMore</code></p>\n</li>\n<li><p>Your error handling is empty, you should fix that ;)</p>\n</li>\n<li><p>In production code, your <code>success</code> function should not write to the console</p>\n</li>\n<li><p>You can apply DRY techniques, a lot of the code looks copy pasted, especially this part;</p>\n<pre><code> switch (data.PageSection) {\n case 1:\n $('#favoritepagesListBlock').append(&quot;&lt;a class='link-text' href='&quot;+data.Url+&quot;'&gt;&quot; + data.PageName + &quot;&lt;/a&gt;&quot;);\n break;\n case 2:\n $('#meetingsanddisclosuresBlock').append(&quot;&lt;a class='link-text' href='&quot; + data.Url + &quot;'&gt;&quot; + data.PageName + &quot;&lt;/a&gt;&quot;);\n break;\n case 3:\n $('#memberinstitutionBlock').append(&quot;&lt;a class='link-text' href='&quot; + data.Url + &quot;'&gt;&lt;b&gt;&quot; + data.PageName + &quot;&lt;/b&gt;&lt;/a&gt;&quot;);\n break;\n case 4:\n $('#orderListBlock').append(&quot;&lt;a class='link-text' href='&quot; + data.Url + &quot;'&gt;&quot; + data.PageName + &quot;&lt;/a&gt;&quot;);\n orderShowMore = data.ShowMore;\n break;\n case 5:\n $('#subscriptionListBlock').append(&quot;&lt;a class='link-text' href='&quot; + data.Url + &quot;'&gt;&quot; + data.PageName + &quot;&lt;/a&gt;&quot;);\n subscriptionShowMore = data.ShowMore;\n break;\n }\n</code></pre>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T09:49:31.023", "Id": "270146", "ParentId": "270120", "Score": "2" } } ]
{ "AcceptedAnswerId": "270142", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T15:47:48.230", "Id": "270120", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "JS Menu Post Get method" }
270120
<p>(From <code>stackoverflow.com</code>, they suggest me to post this question here)<br /> I'm trying to build a bot to check with accounts the status of a service connected to each of them, I thought since they have to do some <code>I/O</code> I'd try to use <code>Tokio</code> (also &quot;<em>to make my bones</em>&quot; since I've never used it).<br /> I came out with a code similar to the following:</p> <pre class="lang-rust prettyprint-override"><code>#[tokio::main] async fn main() { // Load config file let config = Config::parse(&quot;config.toml&quot;).await.unwrap(); // Get accounts data let accounts = config.accounts(); // Init a bot for each account let mut tasks = Vec::with_capacity(accounts.len()); for account in accounts { // Init bot client (wrapper for Reqwest::Client) let client = Client::new(account).await; if let Err(e) = client { println!(&quot;ERROR {}&quot;, e); continue; } let task = tokio::spawn(async move || { let client = client.unwrap(); tokio::pin!(client); loop { // Do login let login = do_login(&amp;mut client).await; if let Err(e) = login { println!(&quot;ERROR {}&quot;, e); tokio::time::sleep(60).await; continue; } // Loop until X number of errors occurs let mut errors = 0; while errors &lt; 50 { // Get information let info = get_info(&amp;client).await; if let Err(e) = info { println!(&quot;ERROR {}&quot;, e); tokio::time::sleep(120).await; errors += 1; continue; } // Send a confirmation let info_id = info.unwrap(); let submit = do_sumbit(info_id, &amp;client).await; if let Err(e) = submit { println!(&quot;ERROR {}&quot;, e); tokio::time::sleep(60).await; errors += 1; } } } }); tasks.push(tasks); } // Join all clients join_all(tasks).await; } async do_login(client: &amp;mut Pin&lt;&amp;mut Client&gt;) -&gt; Result&lt;(), CustomError&gt; { // work async mainly with reqwest } async get_info(client: &amp;Pin&lt;&amp;mut Client&gt;) -&gt; Result&lt;String, CustomError&gt; { // work async mainly with reqwest } async do_sumbit(info_id: String, client: &amp;Pin&lt;&amp;mut Client&gt;) -&gt; Result&lt;(), CustomError&gt; { // work async mainly with reqwest } </code></pre> <ul> <li>Is this code actually asynchronous and concurrent?</li> <li>I was thinking that if the number of accounts to be managed grows much larger than the number of CPUs of the host, the asynchronous approach is better, or am I wrong?</li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T16:22:30.237", "Id": "270125", "Score": "0", "Tags": [ "rust", "asynchronous", "async-await" ], "Title": "Rust infinite loop in Tokio tasks join_all() made concurrency?" }
270125
<p>Please be brutal with my attempt at logging middle ware.</p> <p>The aim of the middle ware is to tag all the logging with the same tracing detail as the apm modules from elastic that are sent to apm-server <a href="https://github.com/igknot/apmzap" rel="nofollow noreferrer">https://github.com/igknot/apmzap</a></p> <pre><code>package logger import ( &quot;log&quot; &quot;net/http&quot; &quot;time&quot; &quot;go.elastic.co/apm/module/apmzap&quot; &quot;go.uber.org/zap&quot; ) //StatusRecorder wraps a ResponseWriter and records the status code type StatusRecorder struct { http.ResponseWriter Status int Length int } //WriteHeader Intercepts the status func (r *StatusRecorder) WriteHeader(status int) { r.Status = status r.ResponseWriter.WriteHeader(status) } //Write Intercepts the status func (r *StatusRecorder) Write(b []byte) (n int, err error) { n, err = r.ResponseWriter.Write(b) r.Length += n return } //ZapLogger wraps a zap logger type zapLogger struct { logZ *zap.Logger name string } // NewMiddleware returns a new Zap Middleware handler. func NewZapLogger(name string, logger *zap.Logger) func(next http.Handler) http.Handler { if logger == nil { log.Fatal(&quot;No logger provided &quot;) } return zapLogger{ logZ: logger, name: name, }.Middleware } //middleware logs tracecontext and request detail to ease correlation with APM trace details func (zl zapLogger) Middleware(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { recorder := &amp;StatusRecorder{ ResponseWriter: w, Status: 200, Length: 0, } start := time.Now() h.ServeHTTP(recorder, r) duration := time.Since(start) traceContextFields := apmzap.TraceContext(r.Context()) fields := append( traceContextFields, zap.String(&quot;http.request.method&quot;, r.Method), zap.String(&quot;url.path&quot;, r.RequestURI), zap.String(&quot;logger&quot;, zl.name), zap.Int(&quot;http.response.status_code&quot;, recorder.Status), zap.Duration(&quot;event.duration&quot;, duration), zap.Int(&quot;http.response.length&quot;, recorder.Length), zap.String(&quot;client.address&quot;, r.RemoteAddr), ) if (recorder.Status &gt;= 500 || recorder.Status == 429) { zl.logZ.Error(&quot;&quot;,fields...) return } if recorder.Status &gt;=400 { zl.logZ.Warn(&quot;&quot;,fields...) return } zl.logZ.Info(&quot;&quot;,fields...) }) } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T17:08:15.997", "Id": "533434", "Score": "0", "body": "Is it a rational thing to do? When you've got apm span's you'll have all the above data over there, in that case you'll duplicate it. The fields that you should add to your logs are these \"trace.id\", \"transaction.id\" and \"span.id\" (https://www.elastic.co/guide/en/apm/agent/go/master/log-correlation.html. In that case your logs will be corelated nicely to the spans." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T08:22:16.983", "Id": "533667", "Score": "1", "body": "Thanks. The (trace.id,transaction.id and span.id) are populated via traceContextFields := apmzap.TraceContext(r.Context())" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T16:38:18.830", "Id": "270126", "Score": "0", "Tags": [ "go", "logging", "elasticsearch" ], "Title": "Go middleware for logging with ZAP and elastic APM" }
270126
<p>I have to improve this code that searches for missing and duplicates values in a list:</p> <pre><code>using System; using System.Collections.Generic; namespace Test { class Program { static void Main(string[] args) { Console.WriteLine(&quot;Hello World!&quot;); int[] input = new int[] { 5, 2, 1, 4, 6, 5 }; Tuple&lt;List&lt;int&gt;, List&lt;int&gt;&gt; result = Process(input); Console.WriteLine(&quot;Missing values: &quot;); foreach (int value in result.Item1) Console.WriteLine(value); Console.WriteLine(&quot;Duplicate values: &quot;); foreach (int value in result.Item2) Console.WriteLine(value); } static Tuple&lt;List&lt;int&gt;, List&lt;int&gt;&gt; Process(int[] input) { Dictionary&lt;int, int&gt; dict = new Dictionary&lt;int, int&gt;(); List&lt;int&gt; missing = new List&lt;int&gt;(); List&lt;int&gt; duplicate = new List&lt;int&gt;(); for(int index = 0; index &lt; input.Length; index++) { int value = input[index]; if (dict.ContainsKey(value)) duplicate.Add(value); else dict.Add(value, value); } for(int index = 0; index&lt; input.Length; index++) { int value = index + 1; if (dict.ContainsKey(value)) continue; else missing.Add(value); } return new Tuple&lt;List&lt;int&gt;, List&lt;int&gt;&gt;(missing, duplicate); } } } </code></pre> <p>I have to use the less memory that I can and make it faster. I've been thinking about how to use only one for loop but I think I can't.</p> <p><code>int[] input</code> parameter can have <code>n</code> elements.</p> <p>E.g. if <code>n = 6</code>, the <code>input</code> parameter should have <code>{ 1, 2, 3, 4, 5, 6}</code> in any order.</p> <p>How can I make it use less memory and runs faster?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T20:02:25.440", "Id": "533289", "Score": "1", "body": "https://ericlippert.com/2012/12/17/performance-rant/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T20:15:48.767", "Id": "533290", "Score": "6", "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) for examples, and revise the title accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T21:26:17.890", "Id": "533292", "Score": "0", "body": "my only concern is the `missing` part, because you're using the array length, which would invalidate the results if the element value is larger than the array length." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T22:08:43.960", "Id": "533295", "Score": "0", "body": "Recursion. Take the leading input pair and recurse with the remaining. Have each recursive call run on a different cpu core using C#'s parallel programming model. I suspect that presorting the input array is not necessarily required. The general idea reminds me of the quicksort algorithm." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T08:51:55.513", "Id": "533307", "Score": "1", "body": "The code doesn't work correctly. Calling `Process` with input `{2,5}` returns missing value 1." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T11:24:48.270", "Id": "533323", "Score": "0", "body": "Looking for a generic solution, or are there any additional constraints (e.g., all numbers in range [0, 100], difference never more than X) ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T11:32:30.010", "Id": "533324", "Score": "0", "body": "@ColouredPanda I'm looking for a generic solution without constraints. Thanks." } ]
[ { "body": "<p>From an <span class=\"math-container\">\\$O(n)\\$</span> perspective, the code is already pretty fast. Everything in the loops is constant or amortized constant.</p>\n<p>So let's look at memory. Allocating the dictionary is something we can remove, the lists belong to the return and cannot be removed.</p>\n<p>Therefore you could sort the input array first <span class=\"math-container\">\\$(O(n*log n))\\$</span> and then loop over it once to add elements into the list. Start with the first element and look at the next one to decide which list needs an addition.</p>\n<pre><code>if the element is the same as the last element\n check whether it is the last added duplicate (if not: add it)\nelse\n all elements in between are missing, add them to the missing list\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T20:11:00.903", "Id": "270129", "ParentId": "270127", "Score": "6" } }, { "body": "<h3>Review</h3>\n<p>Use proper types. If you don't need to map values to something else, you don't need Dictionary. You should use a <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1?view=net-5.0\" rel=\"nofollow noreferrer\">HashSet</a> here.</p>\n<h3>Better performance</h3>\n<p>I don't think you can do better than <span class=\"math-container\">\\$O(n)\\$</span> speed here. But you can avoid creating extra structures (and save memory). It looks like you should do something like sorting here, so it would be a good idea to recall sorting algorithms... and BUM! - <a href=\"https://en.wikipedia.org/wiki/Counting_sort\" rel=\"nofollow noreferrer\">counting sort</a> looks very close to what you need. Create an array (List) of 0's and increase every element taking input array as indexes (minus 1 to be precise). Now, to get missing elements, walk that array and gather indexes of 0's. To get duplicates - walk it and gather indexes of numbers greater than 1. If the task doesn't tell you to form a tuple, you can do that in output loops. Also check the exact task - do you need to find duplicates or duplicate values? I.e. does {2, 2, 2} have 3 duplicates of 2 or only 1 duplicate with value of 2 (repeated 3 times)? In the second case you can save even more memory by using BitArray to store counts.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T11:11:01.977", "Id": "533322", "Score": "0", "body": "Thanks for your answer. I use a dictionary because it lets me search for a value. And, yes, I thought to use a HashSet. Thanks again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T17:27:33.370", "Id": "533358", "Score": "0", "body": "You're using only Add and ContainsKey methods. HashSet has Add and Contains." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T10:50:24.050", "Id": "270151", "ParentId": "270127", "Score": "3" } }, { "body": "<p>Reading your suggestions, especially from <a href=\"https://codereview.stackexchange.com/users/243687/pavlo-slavynskyy\">Pavlo Slavynskyy</a> I have updated the method:</p>\n<pre><code>static Tuple&lt;BitArray, BitArray&gt; Process2(int[] input)\n{\n HashSet&lt;int&gt; set = new HashSet&lt;int&gt;();\n BitArray missing = new BitArray(input.Length, true);\n BitArray repeated = new BitArray(input.Length, false);\n\n for(int index = 0; index &lt; input.Length; index++)\n {\n int value = input[index] - 1;\n\n // This value is not missing.\n missing[value] = false;\n\n if (set.Contains(value))\n repeated[value] = true;\n else\n set.Add(value);\n }\n\n return new Tuple&lt;BitArray, BitArray&gt;(missing, repeated);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T11:40:25.000", "Id": "270154", "ParentId": "270127", "Score": "0" } } ]
{ "AcceptedAnswerId": "270151", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T19:52:00.200", "Id": "270127", "Score": "0", "Tags": [ "c#" ], "Title": "Use less memory and make it runs faster (if it is possible)" }
270127
<p>I tried to recreate Reddit's functionality of replacing <code>r/*</code> on a comment with a link to the subreddit and I came up with this:</p> <pre><code>import React, { useRef, useState } from 'react'; const LinkReplace = () =&gt; { const text = useRef(''); const [comment, setComment] = useState([]); const handleComment = () =&gt; { // replace all spaces with single spaces const textSingleSpaces = text.current.value.replace(/ +/, ' '); // split comment at any character that isn't a letter, digit or / const words = textSingleSpaces.split(/([^\w\d/])/); // replace r/* with a link to the subreddit const wordsParsed = words.map((word, i) =&gt; { if (word.match(/r\/\S+/)) { return React.createElement( 'a', { key: i, href: `https://reddit.com/${word}` }, word ); } return word; }); setComment(wordsParsed); }; return ( &lt;div&gt; &lt;p style={{ whiteSpace: 'pre-wrap' }}&gt;{comment.map((word) =&gt; word)}&lt;/p&gt; &lt;textarea ref={text} onChange={handleComment} cols='30' rows='10' &gt;&lt;/textarea&gt; &lt;/div&gt; ); }; export default LinkReplace; </code></pre> <p>but I'm not sure it's a good way of implementing it. I can't think of any other way, though. Is my code efficient? What can I do to improve it?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T21:57:17.067", "Id": "270130", "Score": "0", "Tags": [ "react.js", "jsx" ], "Title": "Implementing Reddit-like comment links" }
270130
<p>I at one time used class forname newinstance but newinstance is deprecated. I wanted to be able to pass a class name as a string and be able to load a class, so I came up with:</p> <pre><code> public static Object getClass(String myclass) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Class clz = Class.forName(myclass); return clz.getDeclaredConstructor().newInstance(); } </code></pre> <p>Which works good. And usage is:</p> <pre><code> Jim.Newpager apager = (Jim.Newpager) Jim.Jiminject.getInstance().getClass(&quot;Jim.Newpager&quot;); </code></pre> <p>Does that look alright?</p> <p>The whole class that does the inject is:</p> <pre><code>package Jim; import java.lang.reflect.InvocationTargetException; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; public class Jiminject { private static final Jiminject instance = new Jiminject(); private Jiminject() { } public static Jiminject getInstance() { return instance; } public static Object getClass(String myclass) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Class clz = Class.forName(myclass); return clz.getDeclaredConstructor().newInstance(); } } </code></pre> <p>I use for Tomcat, all works good.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T06:07:06.657", "Id": "533299", "Score": "2", "body": "Can you elaborate on why would you want to pass the class name as a string? The instantiating mechanism comes with a host of security issues and your example use case makes no sense as you already know the exact class you are instantiating." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T11:33:14.763", "Id": "533325", "Score": "0", "body": "That’s 33 lines of code , but the actual logic can be expressed concisely in one single line (and, notably, *more concisely* than your implementation). Why would the caller use your class rather than using `Class.forName(\"Jim.Newpager\").newInstance();` directly? Your class doesn’t even make usage easier — on the contrary." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T17:34:36.040", "Id": "533360", "Score": "0", "body": ".newInstance(); is deprecated. Don't you think I would want to continue using it if it wasn't deprecated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T09:33:22.187", "Id": "533405", "Score": "0", "body": "@JimWhitaker Fair point, I should have used `getConstructor().newInstance()` instead of abbreviating. I still don’t see the point of wrapping this straightforward logic into a singleton whose verbose usage doesn’t make the calling code any more concise." } ]
[ { "body": "<p>The concept is odd to me and I've made a comment about clarifications. In the mean time... a few pointers about code style.</p>\n<p>The method name <code>getClass</code> suggests that you are getting a class, when in fact you are returning an instance. To better convey the purpose of the method, you should rename it to <code>instantiateClass</code> or <code>newInstance</code> etc.</p>\n<p>The name prefx <code>my</code> (as in <code>myclass</code> parameter) is the de facto naming style when you can not bother to think about an actually good and useful name. <strong>Never use the &quot;my&quot; prefix. Ever.</strong> It is always a sign that you are skipping an important part of your work. In this case, just use <code>className</code>, because that's what the parameter represents.</p>\n<p>The <code>getClass</code> method is a helper method that shortens the instantiation boiler plate. It would be helpful to the user if you also wrapped the exceptions into a single generic exception that signals failure to instantiate the class. They all result in the same action in you code, right? So no point in making the caller handle each case separately.</p>\n<p>Since you are using the <code>getClass</code> method via the instance retrieved with <code>getInstance()</code> there is no point in <code>getClass</code> to be static. Either drop the <code>static</code> qualifier of delete the <code>getInstance()</code> method.</p>\n<p>Package names are writte in lower case letters. So make it <code>jim</code> instead of <code>Jim</code>. Capitalized initial letter is reserved for classes so the &quot;pearl necklace&quot; <code>Jim.Jiminject.getInstance</code> makes me look for a class named <code>Jim</code> to get to the start of the code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T17:41:01.380", "Id": "533362", "Score": "0", "body": "I will do the renaming. This is meant as a dependency injection class. The getDeclaredConstructor().newInstance(); comes direct from Oracle as the recommended way. The exceptions was an ide netbeans suggestion to add those in. I also have another with try catch. How would you do a DYI dependency injection. This is to get an instance of any needed class, not just the paginator, that's why I need to pass in a string." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T09:07:47.810", "Id": "533402", "Score": "0", "body": "I wouldn't do DIY dependency injection, I would use Spring or some other library. :) Or seriously, let's just say that there is not enough context for me to answer the question properly. Clearly you have a very specific use case that handles class names represented as strings. But I don't know enough about it to say anything useful." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T06:22:00.087", "Id": "270138", "ParentId": "270131", "Score": "4" } }, { "body": "<p><code>Class#newInstance</code> is deprecated as it does not handle the checked exceptions of the default constructor call. So getting the default constructor (no arguments) and using <code>Constructor#newInstance</code> is the correct way.</p>\n<p>Only problem: there might not exist a default constructor, only some constructor with parameters.</p>\n<pre><code>public static Object instantiate(String classFullName) throws ClassNotFoundException,\n NoSuchMethodException,\n InstantiationException,\n IllegalAccessException,\n IllegalArgumentException,\n InvocationTargetException {\n Class&lt;?&gt; type = Class.forName(classFullName);\n return type.getDeclaredConstructor().newInstance();\n}\n</code></pre>\n<p>You might use Exception instead of the entire list.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T12:06:06.727", "Id": "533415", "Score": "1", "body": "\"bypasses the default constructor\" isn't exactly correct. It calls the default constructor, only it lets checked exceptions from that constructor escape the compiler checks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T12:58:41.790", "Id": "533418", "Score": "0", "body": "@RalfKleberhoff of course you are right and I corrected the text." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T18:40:42.427", "Id": "533446", "Score": "0", "body": "@Joop Eggan after reading your reply, I tried changing to a simple try catch and it works perfect, thanks. I never pass parameters to a constructor anyway, I only pass to methods needing the parameters. So if the class exist, there should be no errors. I tried to vote up on your reply, but I am no allowed yet." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T20:22:50.687", "Id": "533452", "Score": "0", "body": "@JimWhitaker `try { ... } catch (NS;E | InE | IllAE | IllArE | ITE e) { throw new IllegalStateException(e); }` is feasible too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T19:59:40.957", "Id": "533545", "Score": "0", "body": "A side question, does anyone know where the actual source code is that makes @Inject, jakarta.inject.Inject work, I have searched Github and Google, haven't fount it yet." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T08:19:49.617", "Id": "270187", "ParentId": "270131", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-16T22:43:30.380", "Id": "270131", "Score": "0", "Tags": [ "java" ], "Title": "Java class loader for new instance" }
270131
<p>I am working with OpenSSL and writing an AES256 encryption module. My knowledge of cybersecurity is not vast and I would like to know whether there are any obvious holes I'm leaving. The intent is for the user to construct an instance of <code>AESEncDec</code> passing a key. With that instance, they may encrypt and decrypt files using that key with methods defined in the class.</p> <p>My main concerns:</p> <ol> <li>In what ways could an attacker potentially compromise this program while it's running?</li> <li>Does the module's class-based nature somehow weaken its security due to having instances of the class which could be inspected by another process?</li> <li>To further test myself, I was considering adding another two layers of AES, encrypting somewhat like <code>Cipher = ENC(K1, (ENC(K2, (ENC(K1, Plaintext))))</code>. Would such a change aid security in any way?</li> </ol> <p>Notes:</p> <ul> <li><p>I am aware that the encrypt and decrypt methods can be combined into one using different EVP functions, I only learned that a bit far into the process and decided to keep the functions separate for now.</p> </li> <li><p>I reviewed a <a href="/q/138194">similar question</a>, but the poster appeared to be using a different library, though I did note some of the responses such as adding validation functions for input as well as expanding the class to enable other sized keys. Since I had some additional questions, I made this review request.</p> </li> </ul> <h2><code>aes_enc_dec_class.h:</code></h2> <pre class="lang-cpp prettyprint-override"><code>#include &lt;fstream&gt; #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;cstring&gt; #include &lt;openssl/evp.h&gt; #include &lt;openssl/err.h&gt; #include &lt;openssl/aes.h&gt; #include &lt;openssl/rand.h&gt; #include &lt;sstream&gt; void handleErrors() { ERR_print_errors_fp(stderr); abort(); } /** * @brief An instance of AESEncDec is tied to a key, with which * files can be encrypted or decrypted as desired. */ class AESEncDec { static const int KEYLEN = 32; static const int BLOCKSIZE = 16; static const int ITER_COUNT = 10000; unsigned char key[KEYLEN]; unsigned char iv[BLOCKSIZE]; public: AESEncDec(unsigned char* keybase); int encrypt_file(const char* path, const char* out); int decrypt_file(const char* path, const char* out); }; AESEncDec::AESEncDec(unsigned char* keybase) { // set key from keybase if (!(EVP_BytesToKey(EVP_aes_256_cbc(), EVP_md5(), NULL, keybase, strlen((const char *) keybase), ITER_COUNT, key, iv))) { fprintf(stderr, &quot;Invalid key base.\n&quot;); } } int AESEncDec::encrypt_file(const char* path, const char* out) { // initialize/open file streams std::ifstream plaintext_file; std::ofstream ciphertext_file; plaintext_file.open(path, std::ios::in | std::ios::binary); ciphertext_file.open(out, std::ios::out | std::ios::binary | std::ios::trunc); // ensure file is open, exit otherwise if (!plaintext_file.is_open()) { fprintf(stderr, &quot;Failed to open plaintext.\n&quot;); return -1; } // initialize encryption buffers unsigned char plaintext[BLOCKSIZE]; unsigned char ciphertext[BLOCKSIZE + BLOCKSIZE]; // extra space for padding // initialize encryption context EVP_CIPHER_CTX *ctx; if (!(ctx = EVP_CIPHER_CTX_new())) handleErrors(); // reinitialize iv to avoid reuse if (!RAND_bytes(iv, BLOCKSIZE)) { fprintf(stderr, &quot;Failed to initialize IV&quot;); return -1; } // set cipher/key/iv if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv)) handleErrors(); // for keeping track of result length int len; int cipherlen = 0; int bytes_read; // read and encrypt a block at a time, write to file while (1) { plaintext_file.read((char *) plaintext, BLOCKSIZE); bytes_read = plaintext_file.gcount(); if (1 != EVP_EncryptUpdate(ctx, ciphertext, &amp;len, plaintext, bytes_read)) handleErrors(); ciphertext_file.write((char *) ciphertext, len); cipherlen+=len; if (bytes_read &lt; BLOCKSIZE) break; } // finalize encryption if (1 != EVP_EncryptFinal_ex(ctx, ciphertext, &amp;len)) handleErrors(); // write final block ciphertext_file.write((char *) ciphertext, len); cipherlen += bytes_read; // clean up ciphertext_file.close(); plaintext_file.close(); EVP_CIPHER_CTX_free(ctx); return cipherlen; } int AESEncDec::decrypt_file(const char* path, const char* out) { // open files for reading and writing std::ifstream ciphertext_file; std::ofstream plaintext_file; ciphertext_file.open(path, std::ios::in | std::ios::binary); plaintext_file.open(out, std::ios::out | std::ios::binary | std::ios::trunc); // if opening failed, exit if (!ciphertext_file.is_open() || !plaintext_file.is_open()) { fprintf(stderr, &quot;One of the files is already open.\n&quot;); return -1; } // initialize cipher context EVP_CIPHER_CTX *ctx; if (!(ctx = EVP_CIPHER_CTX_new())) handleErrors(); // reinitialize iv to avoid reuse if (!RAND_bytes(iv, BLOCKSIZE)) { fprintf(stderr, &quot;Failed to initialize IV&quot;); return -1; } // initialize decryption if (1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv)) handleErrors(); // keeping track of length of result int len; int plaintext_len = 0; // initialize cipher/plaintext buffers unsigned char plaintext[BLOCKSIZE+BLOCKSIZE], ciphertext[BLOCKSIZE]; int bytes_read; // go through the file one block at a time while (1) { ciphertext_file.read((char *) ciphertext, BLOCKSIZE); bytes_read = ciphertext_file.gcount(); // decrypt block if (1 != EVP_DecryptUpdate(ctx, plaintext, &amp;len, ciphertext, bytes_read)) handleErrors(); plaintext_len += len; plaintext_file.write((char *) plaintext, len); if (bytes_read &lt; BLOCKSIZE) break; } if (1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &amp;len)) handleErrors(); plaintext_file.write((char*) plaintext, len); plaintext_len += len; // clean up EVP_CIPHER_CTX_free(ctx); plaintext_file.close(); ciphertext_file.close(); return plaintext_len; } </code></pre> <h2><code>test_aes_enc_dec.cc</code>:</h2> <pre class="lang-cpp prettyprint-override"><code>#include &quot;aes_enc_dec_class.h&quot; #include &lt;iostream&gt; #include &lt;stdio.h&gt; #include &lt;string&gt; #include &lt;fstream&gt; int main (void) { unsigned char *key = (unsigned char *) &quot;HardcodedKey!&quot;; AESEncDec cipher(key); const char* test_file_path = &quot;test.txt&quot;; // open test file for writing, clearing it std::ofstream test_file; test_file.open(test_file_path, std::ios::out | std::ios::trunc); // put a test string into the file const char *test_string = &quot;This is our test string!&quot;; const int test_len = strlen(test_string); test_file.write(test_string, test_len); test_file.close(); // encrypt the file int enc_result = cipher.encrypt_file(&quot;test.txt&quot;, &quot;test.enc&quot;); printf(&quot;Encrypted %d bytes.\n&quot;, enc_result); // decrypt the file int dec_result = cipher.decrypt_file(&quot;test.enc&quot;, &quot;test.dec&quot;); printf(&quot;Decrypted %d bytes.\n&quot;, dec_result); // check output contents std::ifstream result; result.open(&quot;test.dec&quot;, std::ios::in | std::ios::binary); char in[test_len + 1]; result.read(in, test_len); in[test_len] = '\0'; printf(&quot;Plaintext: %s\n&quot; &quot;Decrypted plaintext: %s\n&quot;, test_string, in); // report results int diff; if ((diff = strcmp(test_string, in)) != 0) { printf(&quot;Test failed: difference %d\n&quot;, diff); return -1 } else printf(&quot;Test passed.\n&quot;); return 0; } </code></pre> <h2><code>Makefile</code></h2> <pre><code>LIBS = -lssl -lcrypto CFLAGS = -g -o all: clean test_AES test_AES: g++ $(CFLAGS) test_AES test_aes_enc_dec.cc $(LIBS) clean: rm -f test_AES test.txt test.enc test.dec </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T10:40:34.393", "Id": "533319", "Score": "2", "body": "Don't use `EVP_BytesToKey`. It's considered legacy and out of date. Use PBKDF2 instead. You don't say what version of OpenSSL you are using. In 3.0 you can use the EVP_KDF APIs for this. In older versions you can use PKCS5_PBKDF2_HMAC. You only need to do any of this if you are creating the key from a password. It's not clear that that is what you are doing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T10:41:04.323", "Id": "533320", "Score": "3", "body": "Don't use MD5. Its broken. Use a more modern hash, e.g. SHA256." } ]
[ { "body": "<h1>Makefile review</h1>\n<p>Make more use of built-in rules.</p>\n<p>We should be assigning <code>CXX</code> and <code>CXXFLAGS</code> (instead of <code>CFLAGS</code>), then we can use the built-in rule to compile C++ code from source.</p>\n<p><code>-o</code> on its own isn't a valid flag, and will break as soon as we write <code>CXXFLAGS += -Wall</code> on a later line. That's why the built-in rule has <code>-o $@</code>, so the option and its argument can't be separated.</p>\n<p>The program won't be rebuilt if its source or the header is updated, because we haven't specified any dependencies. If we give the source file the same name as the program, but with <code>.cc</code> appended, then we can let Make use its built-in rule and pick up the source file dependency, and we'll only have to tell it about the header.</p>\n<p>Assuming we have <code>pkg-config</code>, we should be using that to specify the compilation flags for OpenSSL, so that there's nothing to do if those change next time we upgrade.</p>\n<p>And we should turn on more compilation warnings. GCC supports lots of warnings, and we should be using them to help us improve the code.</p>\n<p>The <code>clean</code> target should be marked <code>.PHONY</code> so that its commands will run even if files of those names are present.</p>\n<hr />\n<h1>Improved Makefile</h1>\n<pre><code>all: test_aes_enc_dec\n\nCXX = g++\nCXXFLAGS += -std=c++20\nCXXFLAGS += -g\nCXXFLAGS += -Wall -Wextra -Wwrite-strings -Weffc++\nCXXFLAGS += -Wpedantic -Warray-bounds -Wconversion\nCXXFLAGS += -Wno-parentheses\nCXXFLAGS += $(shell pkg-config --cflags openssl)\nLINK.o = $(LINK.cc)\nLDLIBS += $(shell pkg-config --libs openssl)\n\ntest_aes_enc_dec.o: aes_enc_dec_class.h\n\nclean:\n $(RM) test_aes_enc_dec *.o test.*\n\n.PHONY: clean\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T08:47:53.583", "Id": "270140", "ParentId": "270139", "Score": "3" } }, { "body": "<blockquote>\n<p>To further test myself, I was considering adding another two layers of AES, encrypting somewhat like Cipher = ENC(K1, (ENC(K2, (ENC(K1, Plaintext)))). Would such a change aid security in any way?</p>\n</blockquote>\n<p>Maybe. It depends on whether the ENC(k) forms a group. Perhaps there is a single ENC(K3, Plaintext) that gives the same transformation, in which case an attacker will not notice your multiple stages at all.</p>\n<p>The right way is to compute two different keystreams using the different encryptions (with block cyphers, can use counter mode to turn it into a stream cypher), then XOR the two keystreams together and use that to encode the plaintext. Read <a href=\"https://www.goodreads.com/book/show/351301.Applied_Cryptography\" rel=\"nofollow noreferrer\"><em>Applied Cryptography</em></a> for details.</p>\n<p>This is provably at least as secure as the more secure of the two individual encodings. That is, it will protect against one of the keys being weak, and will force the attacker to crack both keys. It's probably <strong>far harder</strong> since they have to be solved together.</p>\n<p>However, this is best done using two <em>different</em> encryption algorithms or implementations, to protect against one of them being broken. For example, use AES and TwoFish which is unrelated and probably doesn't share the same weaknesses.</p>\n<hr />\n<pre><code>fprintf(stderr, &quot;Failed to initialize IV&quot;);\n</code></pre>\n<p>Isn't this supposed to be C++? Why would you use a C function, and for that matter one that scans for format replacement codes when it's just a plain string?</p>\n<pre><code>NULL\n</code></pre>\n<p>Likewise, don't use the C <code>NULL</code> macro. C++ has a real null pointer, <code>nullptr</code>.</p>\n<p>Use <code>std::filesystem::path</code> for the file names, not <code>const char*</code>. Don't pass around <code>const char*</code> at all; use <code>string_view</code> instead, generally.</p>\n<p>Use <code>constexpr</code> instead of <code>static const</code> when you mean for the value to be known at compile time.</p>\n<p>Don't use <code>int</code> for sizes. Here, you want <a href=\"https://en.cppreference.com/w/cpp/io/streamsize\" rel=\"nofollow noreferrer\"><code>streamsize</code></a>.</p>\n<p><code>int main (void) {</code></p>\n<p>Don't <strong>ever</strong> write <code>(void)</code> for a parameter list in C++. That accepted only for C compatibility, and Strustrup calls it &quot;an abomination&quot;. See <a href=\"https://en.cppreference.com/w/cpp/language/main_function\" rel=\"nofollow noreferrer\">https://en.cppreference.com/w/cpp/language/main_function</a> for the two ways to declare <code>main</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T18:52:22.297", "Id": "533447", "Score": "0", "body": "@G.Sliepen yea... I think it's XORing the key streams and then applying it to the plaintext. Have to look it up in _Applied Cryptography_." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T16:56:25.147", "Id": "270168", "ParentId": "270139", "Score": "4" } }, { "body": "<h1>Use authenticated encryption</h1>\n<p>Your code uses CBC mode to encrypt the file, without adding any authentication code. This means that if an attacker flips some bits in the encrypted file, then decryption still works without any errors, but the decrypted file will no longer match the original plaintext. Therefore, an attacker can perform a <a href=\"https://crypto.stackexchange.com/questions/66085/bit-flipping-attack-on-cbc-mode\">bit-flipping attack</a> that goes unnoticed.</p>\n<p>The typical solution is to add a <a href=\"https://en.wikipedia.org/wiki/Message_authentication_code\" rel=\"noreferrer\">message authentication code</a> to the ciphertext, or as is more common nowadays, using an <a href=\"https://en.wikipedia.org/wiki/Authenticated_encryption\" rel=\"noreferrer\">authenticated encryption mode</a> instead. This ensures that when decoding, you can verify that the ciphertext was not modified in any way.</p>\n<h1>Missing error checking</h1>\n<p>You are only checking if a file was opened correctly, not whether it was completely read or written succesfully. For reading, check that <code>file.eof()</code> is <code>true</code> after reading all data, if not you did not reach the end of the file. For writing, check that <code>file.good()</code> is <code>true</code>.</p>\n<h1>Reduce the responsibility of each function</h1>\n<p><code>encrypt_file()</code> takes two filenames, and is in charge of both opening those files, reading and writing to them, and the actual encryption. I would try to reduce the number of things that function does. Instead of passing filenames, consider passing a <code>std::istream</code> and a <code>std::ostream</code> instead, so <code>encrypt_file()</code> no longer has to open and close files, and will then also work for any stream object, like a <code>std::stringstream</code>, or even read from <code>std::cin</code> and write to <code>std::cout</code> directly.</p>\n<h1>Be careful when modifying crypto algorithms</h1>\n<blockquote>\n<p>To further test myself, I was considering adding another two layers of AES, encrypting somewhat like Cipher = ENC(K1, (ENC(K2, (ENC(K1, Plaintext)))). Would such a change aid security in any way?</p>\n</blockquote>\n<p>You should be very careful when you start doing things like that. As JDługosz already mentioned, this might not be better than just having a single layer of encryption. Furthermore, some combinations might actually reduce security. Also consider that internally most encryption algorithms already apply cryptographic operations multiple times already, called &quot;rounds&quot;. The number of rounds is chosen so it offers a decent margin of protection against attacks to the encryption algorithm.</p>\n<p>Encrypting with multiple <em>independent</em> encryption algorithms might be fine, and protects against a fatal flaw in a single algorithm, although this will also complicate things, which in itself is an undesired property for security-conscious programs.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T10:02:13.807", "Id": "533491", "Score": "0", "body": "\"some combinations might actually reduce security\" That's a myth, unless two keys are the same (because AES=inv(AES)). Such a combination would be an attack against AES. It's still a bad idea to mix algorithm due to the increased risk of adding bugs or not respecting requirements for the safe use of the algorithms." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T10:11:25.693", "Id": "533493", "Score": "0", "body": "@A.Hersean I meant different ways to combine multiple encryptions, instead of just chaining them like ENC(K1, ENC(K2, ...))." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T10:45:02.723", "Id": "533495", "Score": "0", "body": "OK, then. Maybe it could be word better to reduce ambiguity." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T18:38:58.187", "Id": "270173", "ParentId": "270139", "Score": "6" } }, { "body": "<blockquote>\n<p>To further test myself, I was considering adding another two layers of AES, encrypting somewhat like Cipher = ENC(K1, (ENC(K2, (ENC(K1, Plaintext)))). Would such a change aid security in any way?</p>\n</blockquote>\n<p>This is overkill for AES-256 which is secure for more than twenty years of attacks. Triple encryption is suggested for weak cipher like DES which has already another weak property of having small blocksize (64-bit block size and 56-bit key size) to be applicable for the <a href=\"https://sweet32.info/\" rel=\"nofollow noreferrer\">sweet32</a> type birthday attacks.</p>\n<p>AES-256 is bruteforce, multi-target, and quantum safe.</p>\n<ul>\n<li>Searching 256-bit space is impossible.</li>\n<li>Multi-target attacks become infeasible when the keys size is 256</li>\n<li>Grover's quantum search attack can reduce the security 128-bit yet the number of oracle calls is infeasible to implement.</li>\n</ul>\n<p>So you don't need triple encryption that will require you to store two independent keys, two. One AES-256 is enough.</p>\n<p>Actually, any good block cipher like ChaCha20 with 256-bits of the key is safe.</p>\n<blockquote>\n<p>EVP_aes_256_cbc</p>\n</blockquote>\n<p>You are using AES in CBC mode that requires <strong>random</strong> and <strong>unpredictable</strong> IV. With CBC mode you can have at most Ind-CPA secure. CBC mode needs padding like PKCS#7. This padding can cause <a href=\"https://en.wikipedia.org/wiki/Padding_oracle_attack\" rel=\"nofollow noreferrer\">padding oracle attacks</a>, which are applied many times. Since TLS 1.3 we don't have CBC, it is gone forever.</p>\n<p>You should use modern cipher modes as TLS 1.3 does. All of the TLS 1.3 modes internally use CTR mode together with an authentication mechanism like AES-GCM and ChaCha20-1305. If properly used they can provide confidentiality, integrity, and authentication whereas CBC can only provide confidentiality.</p>\n<p>Neither <a href=\"https://crypto.stackexchange.com/a/84359/18298\">AES-GCM</a> nor ChaCha20-Poly1305 is perfect, however, apart from the AES-NI performance, <a href=\"https://crypto.stackexchange.com/q/70894/18298\">ChaCha20-Poly1305 is faster, easy to use, and easy to implement side-channel resisted than AES</a>. If not restricted to AES, use <a href=\"https://datatracker.ietf.org/doc/html/draft-arciszewski-xchacha\" rel=\"nofollow noreferrer\">xChaCha20-Poly1305</a> that supports 192-bit random nonces that enable to use of a single key for a long time.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T21:23:45.900", "Id": "270179", "ParentId": "270139", "Score": "4" } }, { "body": "<h2>Interface</h2>\n<blockquote>\n<pre><code> int encrypt_file(const char* path,\n const char* out);\n int decrypt_file(const char* path,\n const char* out);\n</code></pre>\n</blockquote>\n<p>As well as being a poor separation of concerns, this interface is very limiting, because we can only read from and write to named files. We could be more flexible if we provide functions that accept a <code>std::ostream&amp;</code> and a <code>std::istream&amp;</code>; we'd be able to build the above functions from those, as well as to work with network streams and to create real unit tests. A test that depends on external resources such as filesystem isn't a <em>unit</em> test.</p>\n<p>In fact, the convenience functions that open files could even be a single function - pass in the stream operation as a pointer to member function.</p>\n<p>The return type <code>int</code> is likely too small for file sizes in general - prefer <code>std::streamsize</code> for that.</p>\n<hr />\n<blockquote>\n<pre><code> AESEncDec(unsigned char* keybase);\n</code></pre>\n</blockquote>\n<p>Is there a good reason we can't accept <code>const unsigned char*</code> here?</p>\n<p>In the definition, I'd prefer to see a proper C++ cast where we convert to <code>const char*</code>, as that protects against casting away the <code>const</code>.</p>\n<hr />\n<h2>Error handler</h2>\n<blockquote>\n<pre><code>void handleErrors() {\n ERR_print_errors_fp(stderr);\n abort();\n}\n</code></pre>\n</blockquote>\n<p>That's a very inflexible way to deal with errors - the calling program might have a much better strategy (e.g. asking user for a different output file, rather than losing all their work).</p>\n<p>We haven't included <code>&lt;cstdio&gt;</code> for the definition of <code>stderr</code>.</p>\n<p>We haven't included <code>&lt;cstdlib&gt;</code> (I'm assuming <code>abort()</code> is meant to be <code>std::abort()</code>), and in any case this is a dangerous function to use in C++, because it immediately exits without running any destructors or atexit functions.</p>\n<hr />\n<blockquote>\n<pre><code> fprintf(stderr, &quot;Failed to open plaintext.\\n&quot;);\n</code></pre>\n</blockquote>\n<p>We haven't included <code>&lt;cstdio&gt;</code> for a definition of <code>std::printf()</code>. But why not just stream to <code>std::cerr</code>? That's in <code>&lt;iostream&gt;</code>, which we have already included.</p>\n<hr />\n<h2>File handling</h2>\n<blockquote>\n<pre><code>std::ifstream plaintext_file;\nstd::ofstream ciphertext_file;\nplaintext_file.open(path, std::ios::in | std::ios::binary);\nciphertext_file.open(out, std::ios::out | std::ios::binary | std::ios::trunc);\n</code></pre>\n</blockquote>\n<p>Input and output streams automatically include <code>std::ios::in</code> and <code>std::ios::out</code> (respectively) in their options, so no need to specify those.</p>\n<p>More importantly, although we check that we open the input file, that seems to be the <em>only</em> operation that's checked. There's no error handling for failed reads, and no checking at all on the output file (and writing is more likely to fail, e.g. due to permissions or device-full).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T08:31:17.187", "Id": "270189", "ParentId": "270139", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T07:24:44.890", "Id": "270139", "Score": "4", "Tags": [ "c++", "cryptography", "aes", "openssl" ], "Title": "C++ AES Encryption Class" }
270139
<p>There are 1.3M documents in my collection (5.0 and hosted directly on mongodb.com) and there is an index on &quot;topic&quot; and a combined index on &quot;topic&quot; and another field. However the pymongo query of</p> <pre><code>mng.distinct('topic', {&quot;topic&quot;: {&quot;$regex&quot;: &quot;XXX-XXX/XX/X/XXX/.*&quot;}}) </code></pre> <p>takes extremely long. I tried speeding it up by using case insensitive regex queries etc. but the speed stays the same (about 30 - 45 seconds per query). What is weird too is how inefficient the regex of MongoDB is. If I just get the distinct first and then do regex in python like this:</p> <pre><code>for topic in mongo.distinct('topic'): if re.search(self.gen_topic_base(), str(topic)): pass </code></pre> <p>it only takes a fraction of the time (about 1s per query). However this is inefficient and also to slow. Is there a more efficient way to do this that I am unaware of? I tried an aggregation pipeline, but it was even slower.</p> <p>Those are the <code>executionStats</code>:</p> <pre><code>{ executionStats: { executionSuccess: true, nReturned: 9110, executionTimeMillis: 1501, totalKeysExamined: 9111, totalDocsExamined: 9110, executionStages: { stage: 'FETCH', nReturned: 9110, executionTimeMillisEstimate: 1400, works: 9112, advanced: 9110, needTime: 1, needYield: 0, saveState: 14, restoreState: 14, isEOF: 1, docsExamined: 9110, alreadyHasObj: 0, inputStage: { stage: 'IXSCAN', filter: { topic: BSONRegExp(&quot;^XXX-XXX-XXX/XX/0/XX/.*&quot;, &quot;&quot;) }, nReturned: 9110, executionTimeMillisEstimate: 573, works: 9112, advanced: 9110, needTime: 1, needYield: 0, saveState: 14, restoreState: 14, isEOF: 1, keyPattern: { topic: 1 }, indexName: 'topic_index', isMultiKey: false, multiKeyPaths: { topic: [] }, isUnique: false, isSparse: false, isPartial: false, indexVersion: 2, direction: 'forward', indexBounds: { topic: [ '[&quot;XXX-XXX-XXX/XX/0/XX/&quot;, &quot;XXX-XXX-XXX/XX/0/XX0&quot;)', '[/^XXX-XXX-XXX/XX/0/XX/.*/, /^XXX-XXX-XXX/XX/0/XX/.*/]' ] }, keysExamined: 9111, seeks: 2, dupsTested: 0, dupsDropped: 0 } } }, command: { distinct: 'XXX-XXX-XXX', key: 'topic', query: { topic: BSONRegExp(&quot;^XXX-XXX-XXX/XX/0/XX/.*&quot;, &quot;&quot;) }, '$db': 'prod' }, serverInfo: { host: 'XXXXXX.mongodb.net', port: XXXXX, version: '5.0.3', gitVersion: 'XXXXXX' }, serverParameters: { internalQueryFacetBufferSizeBytes: 104857600, internalQueryFacetMaxOutputDocSizeBytes: 104857600, internalLookupStageIntermediateDocumentMaxSizeBytes: 104857600, internalDocumentSourceGroupMaxMemoryBytes: 104857600, internalQueryMaxBlockingSortMemoryUsageBytes: 104857600, internalQueryProhibitBlockingMergeOnMongoS: 0, internalQueryMaxAddToSetBytes: 104857600, internalDocumentSourceSetWindowFieldsMaxMemoryBytes: 104857600 }, ok: 1, '$clusterTime': { clusterTime: Timestamp({ t: 1637139518, i: 1 }), signature: { hash: Binary(Buffer.from(&quot;HASH&quot;, &quot;hex&quot;), 0), keyId: KEY_ID } }, operationTime: Timestamp({ t: 1637139518, i: 1 }) } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T09:38:30.727", "Id": "270145", "Score": "0", "Tags": [ "python", "performance", "regex", "database", "mongodb" ], "Title": "Why is this MongoDB query so slow in comparison to python + in general?" }
270145
<p>In my class the constructor queries data from the database. In the database there is a table containing more than <strong>400k records</strong>. After the query I tested memory size- it uses more than <strong>10m++ bytes</strong>. so this query makes it very very slow.</p> <p>This my class contructor</p> <pre><code>$this-&gt;projectMappings = Project::select('project_id','name') -&gt;get(); </code></pre> <p>And there is this method that used that property:</p> <pre><code>public function searchProjectIdFromProjectName(?string $name): void { $projectId = $this-&gt;projectMappings-&gt;where('name', '=', $name)-&gt;first(); $this-&gt;setProjectId($projectId-&gt;project_id ?? null); } </code></pre> <p>for more detail</p> <p>this variable <code>$this-&gt;projectMappings</code> use only function <code>searchProjectIdFromProjectName()</code></p> <p>So when I sync many data every use <code>searchProjectIdFromProject()</code> this function will return <code>projectId</code> to object for <code>save</code> data to the database.</p> <p>loop = data -&gt; search project id -&gt; object data -&gt; insert database</p> <p>I hope it's good enough.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T12:24:19.207", "Id": "533330", "Score": "2", "body": "This question is of very poor quality. I'm not sure it is ready for review. Can you flesh it out a bit more? Which framework are you using? What is your code used for? What should it achieve and how have you solved that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T16:53:20.127", "Id": "533350", "Score": "0", "body": "Looks more like a querstion for stackoverflow... As a hint tho, to enhance performance check indexing and could read data in chunks rather than trying to fetch 10s of 1000s of rows (if thats the kind of volume you expect the query to return)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T17:04:35.207", "Id": "533353", "Score": "1", "body": "Going along with Kiko's comment - where is `$this->projectMappings` used other than in `searchProjectIdFromProjectName()`? It would benefit reviewers to have a bit more information about the code in the description. From [the help center page _How to ask_](https://codereview.stackexchange.com/help/how-to-ask): \"_You will get more insightful reviews if you not only provide your code, but also give an explanation of what it does. The more detail, the better._\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T14:14:31.850", "Id": "533425", "Score": "0", "body": "Thank you for adding a bit of information. Your query is searching on `name` and my guess is that this is slow because it is a non-indexed text field. [Adding an index](https://www.mysqltutorial.org/mysql-index/) there could help a lot, just like Brian suggested. You can index text fields if you fix the length." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T19:48:03.923", "Id": "533451", "Score": "0", "body": "Roughly how many records are returned by the query in the constructor? and with respect to that number, how many times is `searchProjectIdFromProjectName()` called?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T03:14:49.727", "Id": "533468", "Score": "0", "body": "In __constructor has 400k records sample `[{'name','1'}, ...]` “…how many times is searchProjectIdFromProjectName() called?” Example I call api get json response data 1000-2000 records and every record use searchProjectIdFromProjectName() ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T13:34:35.040", "Id": "533510", "Score": "0", "body": "How does it know which 1000-2000 records to get? Query string or POST parameter? It would be helpful to have the post [edit]ed to show any route configuration posted, as well as functions (e.g. controller methods?) that handle those routes" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-22T02:22:57.007", "Id": "533660", "Score": "0", "body": "In API no parameter or query string. API get from another site I can't design function or data recieve." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T10:01:31.030", "Id": "270147", "Score": "0", "Tags": [ "php", "laravel" ], "Title": "query data from mapping name but use many memory" }
270147
<p>I consume a RestApi with few Combine Publishers and want to visually represent ongoing progress with UIActivityIndicatorView. My current logic uses <code>handleEvents-&gt;receiveSubscription</code> closure to start an animation and <code>handleEvents-&gt;receiveCancel</code> and <code>sink-&gt;completion</code> to stop an animation of the activityIndicatorView. I ask for a review because it looks strange that a <code>stop animation</code> must be called from two different closures which looks like I am missing something</p> <pre><code> let first = URLSession.shared.dataTaskPublisher(for: .init(string: &quot;http://httpbin.org/delay/10&quot;)!) .tryMap { (data: Data, response: URLResponse) in return data } let second = URLSession.shared.dataTaskPublisher(for: .init(string: &quot;http://httpbin.org/delay/5&quot;)!) .tryMap { (data: Data, response: URLResponse) in return data } cancellable = Publishers.Zip(first,second) .flatMap { _ in first } .handleEvents(receiveSubscription: { subscription in print(&quot;receiveCancel: activityIndicatorView.startAnimating()&quot;) }, receiveCancel: { print(&quot;receiveCancel: activityIndicatorView.stopAnimating()&quot;) }) .sink { _ in print(&quot;sink completion: activityIndicatorView.stopAnimating()&quot;) } receiveValue: { _ in } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T10:51:55.747", "Id": "270152", "Score": "0", "Tags": [ "swift" ], "Title": "Start / stop animating activityIndicatorView for many dataTaskPublishers" }
270152
<p>I have this code that writes the initial configuration of a simulator I'm writing to <code>stdout</code>. <code>args</code> is an instance of type <code>struct Arguments</code>, and all the members of said struct are used in the singular function below. I was hoping for some hints to simplify the code and get the alignment correct.</p> <p>I have considered using <code>&lt;cstdio&gt;</code> and simply writing the output I need to a buffer string with <code>sprintf</code> (this code is <em>guaranteed</em> to be shorter) and then writing to the console with either <code>std::cout</code> or <code>printf</code>. However, I have tried my best to avoid using any C libraries in this project.</p> <pre><code>struct Arguments { std::string_view protocol{&quot;MESI&quot;}; std::filesystem::path benchmark{&quot;data/bodytrack&quot;}; uint32_t cacheSize{4096}; uint8_t associativity{2}; uint16_t blockSize{32}; uint32_t numBlocks{4096 / 32}; Arguments() = default; explicit Arguments(const char* argv[]); }; void Runner::printConfig() const { std::stringstream ss; ss &lt;&lt; &quot;====================================&quot; &lt;&lt; std::endl &lt;&lt; &quot;Cache protocol:\t\t&quot; &lt;&lt; args.protocol &lt;&lt; std::endl &lt;&lt; &quot;Cache size:\t\t&quot; &lt;&lt; args.cacheSize &lt;&lt; &quot; B&quot;; if (args.cacheSize &gt; (1 &lt;&lt; 10) &amp;&amp; args.cacheSize &lt; (1 &lt;&lt; 20)) ss &lt;&lt; &quot; (&quot; &lt;&lt; std::setprecision(4) &lt;&lt; static_cast&lt;double&gt;(args.cacheSize) / static_cast&lt;double&gt;(1 &lt;&lt; 10) &lt;&lt; &quot; KiB)&quot; &lt;&lt; std::endl; else if (args.cacheSize &gt; (1 &lt;&lt; 20)) ss &lt;&lt; &quot; (&quot; &lt;&lt; std::setprecision(4) &lt;&lt; static_cast&lt;double&gt;(args.cacheSize) / static_cast&lt;double&gt;(1 &lt;&lt; 20) &lt;&lt; &quot; MiB)&quot; &lt;&lt; std::endl; else ss &lt;&lt; std::endl; ss &lt;&lt; &quot;Block size:\t\t&quot; &lt;&lt; args.blockSize &lt;&lt; &quot; B&quot; &lt;&lt; std::endl; ss &lt;&lt; &quot;Associativity:\t\t&quot;; if (args.associativity == 1) ss &lt;&lt; &quot;direct-mapped&quot; &lt;&lt; std::endl; else if (args.associativity == args.numBlocks) ss &lt;&lt; &quot;fully associative&quot; &lt;&lt; std::endl; else { ss &lt;&lt; std::to_string(args.associativity) &lt;&lt; &quot;-way set-associative&quot; &lt;&lt; std::endl &lt;&lt; &quot;Cache blocks:\t\t&quot; &lt;&lt; args.numBlocks &lt;&lt; &quot; (&quot; &lt;&lt; (args.numBlocks / args.associativity) &lt;&lt; &quot; per set)&quot; &lt;&lt; std::endl &lt;&lt; &quot;====================================&quot;; std::cout &lt;&lt; ss.view() &lt;&lt; std::endl; return; } ss &lt;&lt; &quot;Cache blocks:\t\t&quot; &lt;&lt; args.numBlocks &lt;&lt; std::endl &lt;&lt; &quot;====================================&quot;; std::cout &lt;&lt; ss.view() &lt;&lt; std::endl; } </code></pre> <p>Run with the arguments <code>Dragon bodytrack 1024 2 16</code>, this outputs:</p> <pre><code>==================================== Cache protocol: Dragon Cache size: 1024 B (1 KiB) Block size: 16 B Associativity: 2-way set-associative Cache blocks: 4 (2 per set) ==================================== </code></pre> <p><strong>N.B.</strong></p> <ol> <li>I'm aware that the separators are not long enough: that's also in the pipeline).</li> <li>I wish I could use <code>&lt;format&gt;</code>, but this project is cross-platform and only MSVC has implemented it at all.</li> <li>Ideally no large third-party libraries (Boost, etc).</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T12:21:11.080", "Id": "533327", "Score": "0", "body": "You're missing the definition of `args`. Without that, it's very hard to review this code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T13:14:45.177", "Id": "533336", "Score": "1", "body": "Have a look at fmt - https://github.com/fmtlib/fmt" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T17:13:11.403", "Id": "533357", "Score": "0", "body": "Welcome to Code Review@SE. Please heed [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask), especially in picking a title for your question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T22:57:12.497", "Id": "533378", "Score": "0", "body": "There are several C++ formatting libraries out there. [Boost Format](https://www.boost.org/doc/libs/1_31_0/libs/format/doc/format.html) I even wrote one [ThorIOUtil](https://github.com/Loki-Astari/ThorsIOUtil/tree/042e5f73935c91d38b9df94488b00fd00e2b2be2)" } ]
[ { "body": "<ul>\n<li><p>Don't use <code>std::endl</code> unless you actually need flushing behavior. For a newline, just output <code>&quot;\\n&quot;</code>.</p>\n</li>\n<li><p>Use the manipulators from <a href=\"https://en.cppreference.com/w/cpp/io/manip\" rel=\"nofollow noreferrer\"><code>&lt;iomanip&gt;</code></a> to get fixed column sizes. Specifically <code>std::setw(n)</code> to set the output width to size <code>n</code>, and <code>std::left</code> or <code>std::right</code> align things if necessary.</p>\n</li>\n<li><p>Consider sticking to one line of output per <code>ss &lt;&lt; ...</code> chain (except where it's necessary to break a line up).</p>\n</li>\n<li><p>As mentioned by upkajdt in the comments, you could use <a href=\"https://github.com/fmtlib/fmt\" rel=\"nofollow noreferrer\"><code>fmtlib</code></a> where <code>std::format</code> isn't implemented yet. (The two should be functionally equivalent, so you could use a wrapper function to forward calls to the appropriate backend).</p>\n</li>\n</ul>\n<hr />\n<pre><code> if (args.cacheSize &gt; (1 &lt;&lt; 10) &amp;&amp; args.cacheSize &lt; (1 &lt;&lt; 20))\n ss &lt;&lt; &quot; (&quot; &lt;&lt; std::setprecision(4) &lt;&lt; static_cast&lt;double&gt;(args.cacheSize) / static_cast&lt;double&gt;(1 &lt;&lt; 10) &lt;&lt; &quot; KiB)&quot;\n &lt;&lt; std::endl;\n else if (args.cacheSize &gt; (1 &lt;&lt; 20))\n ss &lt;&lt; &quot; (&quot; &lt;&lt; std::setprecision(4) &lt;&lt; static_cast&lt;double&gt;(args.cacheSize) / static_cast&lt;double&gt;(1 &lt;&lt; 20) &lt;&lt; &quot; MiB)&quot;\n &lt;&lt; std::endl;\n else ss &lt;&lt; std::endl;\n</code></pre>\n<p>We can simplify this slightly by checking for the largest size first, and moving the newline out of the condition:</p>\n<pre><code>if (args.cacheSize &gt; (1 &lt;&lt; 20))\n ss &lt;&lt; &quot; (&quot; &lt;&lt; std::setprecision(4) &lt;&lt; static_cast&lt;double&gt;(args.cacheSize) / static_cast&lt;double&gt;(1 &lt;&lt; 20) &lt;&lt; &quot; MiB)&quot;;\nelse if (args.cacheSize &gt; (1 &lt;&lt; 10))\n ss &lt;&lt; &quot; (&quot; &lt;&lt; std::setprecision(4) &lt;&lt; static_cast&lt;double&gt;(args.cacheSize) / static_cast&lt;double&gt;(1 &lt;&lt; 10) &lt;&lt; &quot; KiB)&quot;;\n\nss &lt;&lt; &quot;\\n&quot;;\n</code></pre>\n<p>Converting to KiB / MiB could perhaps be done in a separate function.</p>\n<hr />\n<pre><code> ss &lt;&lt; &quot;Associativity:\\t\\t&quot;;\n if (args.associativity == 1) ss &lt;&lt; &quot;direct-mapped&quot; &lt;&lt; std::endl;\n else if (args.associativity == args.numBlocks) ss &lt;&lt; &quot;fully associative&quot; &lt;&lt; std::endl;\n else {\n ss &lt;&lt; std::to_string(args.associativity) &lt;&lt; &quot;-way set-associative&quot; &lt;&lt; std::endl\n &lt;&lt; &quot;Cache blocks:\\t\\t&quot; &lt;&lt; args.numBlocks &lt;&lt; &quot; (&quot; &lt;&lt; (args.numBlocks / args.associativity) &lt;&lt; &quot; per set)&quot;\n &lt;&lt; std::endl\n &lt;&lt; &quot;====================================&quot;;\n std::cout &lt;&lt; ss.view() &lt;&lt; std::endl;\n return;\n }\n ss &lt;&lt; &quot;Cache blocks:\\t\\t&quot; &lt;&lt; args.numBlocks &lt;&lt; std::endl &lt;&lt; &quot;====================================&quot;;\n\n std::cout &lt;&lt; ss.view() &lt;&lt; std::endl;\n</code></pre>\n<p>Is it really necessary to conditionally output the blocks?</p>\n<pre><code>ss &lt;&lt; std::setw(20) &lt;&lt; &quot;Associativity:&quot;;\n\nif (args.associativity == 1) ss &lt;&lt; &quot;direct-mapped&quot;;\nelse if (args.associativity == args.numBlocks) ss &lt;&lt; &quot;fully associative&quot;;\nelse ss &lt;&lt; std::to_string(args.associativity) &lt;&lt; &quot;-way set-associative&quot;;\n\nss &lt;&lt; &quot;\\n&quot;;\n\nss &lt;&lt; std::setw(20) &lt;&lt; &quot;Cache blocks:&quot; &lt;&lt; args.numBlocks &lt;&lt; &quot; (&quot; &lt;&lt; (args.numBlocks / args.associativity) &lt;&lt; &quot; per set)&quot; &lt;&lt; &quot;\\n&quot;;\nss &lt;&lt; &quot;====================================&quot;;\n\nstd::cout &lt;&lt; ss.view() &lt;&lt; std::endl;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T13:46:42.267", "Id": "270161", "ParentId": "270155", "Score": "4" } }, { "body": "<p>Use a helper function:</p>\n<pre><code>void print_KorM (std::ostream&amp; o, double val)\n{\n o.precision(4);\n constexpr double K = 1.0 &lt;&lt; 10;\n constexpr double M = 1.0 &lt;&lt; 20;\n if (val &gt; M) o &lt;&lt; (val/M) &lt;&lt; &quot;MiB&quot;;\n else if (val &gt; K) o &lt;&lt; (val/K) &lt;&lt; &quot;KiB&quot;;\n else o &lt;&lt; val;\n}\n</code></pre>\n<p>Note that there is <strong>no casting</strong> needed in the implementation or by the caller.</p>\n<p>In general, break out all the complicated <em>format it this way or that way depending on the range or other values</em> into their own functions, even if they are only used once. Then your principal function is just outputting captions and a simple statement for each value. (e.g. <code>numBlocks</code>)</p>\n<hr />\n<p>You write: <code>ss &lt;&lt; std::to_string(args.associativity)</code><br />\nThis is inefficient as you create a string object, rather than formatting directly into the stream. I'm guessing you do this because writing <code>ss &lt;&lt; args.associativity</code> directly formats it as a character rather than an integer? The simple, zero-overhead fix for that is to write: <code>ss &lt;&lt; 0+args.associativity</code>.</p>\n<p>You could write <code>int(args.associativity)</code> but this begs the question of what is the proper type to use actually. By using <code>0+</code> it will invoke the promotion rules to give a type that we know is <em>at least</em> an <code>int</code> (since the literal <code>0</code> is of type <code>int</code>) thus not a char-sized type that causes issues. It will also continue to work unchanged if you ever change the definition of <code>associativity</code> to a different type, such as <code>uint32_t</code>, as the arithmetic promotion rules will cover that.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T19:37:43.460", "Id": "270201", "ParentId": "270155", "Score": "1" } } ]
{ "AcceptedAnswerId": "270161", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T11:41:04.417", "Id": "270155", "Score": "0", "Tags": [ "c++", "formatting" ], "Title": "Is there a neater, more elegant way to format this output?" }
270155
<p>The following code log INFO in terminal and WARNING, ERROR or CRITICAL in file.</p> <p>my python file looks like:</p> <pre><code>import logging import os import logging.config import yaml DEFAULT_LEVEL = logging.DEBUG class infoFilter(logging.Filter): def filter(self, log_record): return log_record.levelno == logging.INFO class warningerrorcriticalFilter(logging.Filter): def filter(self, log_record): if log_record.levelno in {logging.WARNING, logging.ERROR, logging.CRITICAL}: return True else: return False def log_setup(log_cfg_path='config.yaml'): if os.path.exists(log_cfg_path): with open(log_cfg_path, 'r') as f: try: config = yaml.safe_load(f.read()) logging.config.dictConfig(config) except Exception as e: print('Error with file, using Default logging') logging.basicConfig(level=DEFAULT_LEVEL) else: logging.basicConfig(level=DEFAULT_LEVEL) print('Config file not found, using Default logging') log_setup() logger = logging.getLogger('dev') logger.debug('debug message') logger.info('info message') logger.warning('warn message') logger.error(&quot;error message&quot;) logger.critical('critical message') </code></pre> <p>my <code>config.yaml</code> file:</p> <pre><code>version: 1 formatters: extended: format: '%(asctime)-20s :: %(levelname)-8s :: [%(process)d]%(processName)s :: %(threadName)s[%(thread)d] :: %(pathname)s :: %(lineno)d :: %(message)s' simple: format: &quot;%(asctime)s :: %(name)s :: %(message)s&quot; filters: show_only_info: (): __main__.infoFilter show_only_warningerrorcritical: (): __main__.warningerrorcriticalFilter handlers: console: class: logging.StreamHandler level: DEBUG formatter: simple stream: ext://sys.stdout filters: [show_only_info] file_handler: class: logging.FileHandler filename: my_app.log formatter: extended level: DEBUG filters: [show_only_warningerrorcritical] loggers: dev: handlers: [console, file_handler] propagate: false prod: handlers: [file_handler] root: level: DEBUG handlers: [console] </code></pre> <p>As far I know, I should use <code>logger = logging.getLogger(__name__)</code> instead of <code>logger = logging.getLogger('dev')</code>. I think I should also use <code>if __name__ == &quot;__main__&quot;:</code>. However, I am not sure how these will work with my current code. I am also not sure if I could push more info from the python code to <code>config.yaml</code> file. I would like to have maximum stuff on the config file.</p> <p>I saw somewhere (not sure) that they are using lambda in config file. It would be great if I could send the complete <code>infoFilter</code> and <code>warningerrorcriticalFilter</code> class to <code>config.yaml</code> file.</p> <p>I am sure there are lot more lacking in my code.</p> <p>I will be grateful if you kindly point out the issues in my code.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T12:21:17.110", "Id": "270156", "Score": "0", "Tags": [ "python", "python-3.x" ], "Title": "view only INFO in console and save CRITICAL, ERROR, WARNING to log file" }
270156
<p>Relatively new to the Design patterns, Generally my works are writing function for the needs. But now i need to implement a undo redo functionality, so i just read about the different patterns which i can use for that and found that, memento pattern is the one we can go for. So try to write the code to implement that, It's worked, but not sure about the code quality. Also not actually follow the JAVA style Memento pattern, Here i am understand the concept and add code my own way.</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>const Calculator = () =&gt; { const mementos = []; let redos = []; let sum = 0; const add = (num) =&gt; { setState(sum); sum += num; }; const sub = (num) =&gt; { setState(sum); sum -= num; } const mul = (num) =&gt; { setState(sum); sum *= num; } const div = (num) =&gt; { setState(sum); sum /= num; } const setState = (state) =&gt; { mementos.push({ state }); }; const restore = state =&gt; state.state; const undo = () =&gt; { redos = []; if (mementos.length &lt;= 0) { return null; } redos.push({ state: sum }); const memento = mementos.pop(); sum = restore(memento); return sum; }; const redo = () =&gt; { if (redos.length &lt;= 0) { const obj = redos.pop(); sum = restore(obj); } }; return { add, sub, mul, div, undo, redo, dispaly: () =&gt; { console.log(sum); } }; }; const { sub, mul, div, dispaly, add, undo, redo } = Calculator(); add(10); dispaly(); add(50); dispaly(); sub(10); dispaly(); mul(2); dispaly(); undo(); dispaly();</code></pre> </div> </div> </p> <p>Any issues with this coding style or any improvements i can add on this to make this pattern is maintainable. Thank You</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T13:05:55.593", "Id": "270159", "Score": "2", "Tags": [ "javascript", "design-patterns", "node.js" ], "Title": "Undo/Redo implementation using Memento pattern Javascript" }
270159
<p>I have an application using Django Rest Framework and a <code>ListModelView</code> for a model which I basically need to filter for in a MongoDB. The call for MongoDB is made in a model method of the model and referenced as a SerializerMethodField in the serializer. So when requesting the list endpoint there are n calls to the MongoDB. However I would love to make this more efficient by only using one call. Is this somehow possible?</p> <pre><code>class Model(models.Model): ... def get_topics(self): return self.gateway.get_mongo_collection().distinct('topic', {&quot;topic&quot;: {&quot;$regex&quot;: '^' + self.gen_topic()}}) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T13:40:04.757", "Id": "270160", "Score": "0", "Tags": [ "python", "django", "rest", "mongodb" ], "Title": "Possible to merge model method database calls?" }
270160
<p>The program is a <a href="https://en.wikipedia.org/wiki/Caesar_cipher" rel="nofollow noreferrer">Caesar's cipher</a> decoder. It compiles and works ok, but in Valgrind, I receive a lot of errors and I have no idea how to solve them.</p> <p>I have tried with --track-origins=yes, but I still have no clue what's wrong.</p> <p>Example to test: xUbbemehbT, XYlloworld -&gt; Helloworld.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdbool.h&gt; #include &lt;string.h&gt; #include &lt;ctype.h&gt; #define MODE_1 1 #define MODE_2 2 enum Error { ERROR_INPUT = 100, ERROR_LENGTH = 101 }; enum Msg { DEFAULT_LEN = 10, LAST_LOWER = 26, LAST_UPPER = 52 }; int mandatory(void); int optional(void); void sub_shift(char *message, char mode); char *shift(char *original, char *misheard); int compute_shift(char *original, char *misheard, size_t len, int shift_1); int compare_by_symbol(const char *msg1, const char *msg2, int length); int free_and_exit(char *msg1, char *msg2, int error); int main(int argc, char *argv[]) { int ret = EXIT_SUCCESS; bool prp_optional = argc &gt; 1 ? strcmp(argv[1], &quot;-prp-optional&quot;) == 0 : false; prp_optional ? optional(), ret = optional() : mandatory(), ret = mandatory(); return ret; } void sub_shift(char *message, char mode) { size_t len = strlen(message) - 1; // -1 Because of '\0' if (mode == MODE_1) { for (size_t letter = 0; letter &lt; len; letter++) { if (message[letter] &gt; 'Z' + 1) { message[letter] -= 'G'; } else { message[letter] -= 'A'; } } } else { for (size_t letter = 0; letter &lt; len; letter++) { if (message[letter] &gt; LAST_LOWER) { message[letter] += 'G'; } else { message[letter] += 'A'; } } } } char *shift(char *original, char *misheard) { int shift_1 = 0; size_t len = strlen(original) - 1; // -1 Because of '\0' sub_shift(original, MODE_1); sub_shift(misheard, MODE_1); shift_1 = compute_shift(original, misheard, len, shift_1); for (size_t letter = 0; letter &lt; len; letter++) { original[letter] += shift_1; original[letter] %= LAST_UPPER; } sub_shift(original, MODE_2); original[len] = '\0'; // Remove the last character return original; } int compute_shift(char *original, char *misheard, size_t len, int shift_1) { int off = 0; for (int index = 0; index &lt;= LAST_UPPER; index++) { int offset = 0; for (size_t letter = 0; letter &lt; len; letter++) { original[letter]++; original[letter] %= LAST_UPPER; if (original[letter] == misheard[letter]) { offset++; } } if (off &lt; offset) { off = offset; shift_1 = index; } } return shift_1; } int compare_by_symbol(const char *msg1, const char *msg2, int length) { int equal_counter = 0; for (int i = 0; i &lt; length; i++) { if (msg1[i] == msg2[i]) { equal_counter++; } } return equal_counter; } int free_and_exit(char *msg1, char *msg2, int error) { free(msg1); free(msg2); msg1 = NULL; msg2 = NULL; if (error == ERROR_INPUT) { fprintf(stderr, &quot;Error: Wrong input!\n&quot;); exit(ERROR_INPUT); } else if (error == ERROR_LENGTH) { fprintf(stderr, &quot;Error: Wrong input length!\n&quot;); exit(ERROR_LENGTH); } else { free(msg1); free(msg2); msg1 = NULL; msg2 = NULL; exit(EXIT_SUCCESS); } } int mandatory(void) { int ret = EXIT_SUCCESS; size_t capacity = DEFAULT_LEN; int positions[LAST_UPPER]; size_t len1 = 0; size_t len2 = 0; char *msg1 = (char *)malloc(capacity); char *msg2 = (char *)malloc(capacity); while ((msg1[len1] = getchar()) != EOF &amp;&amp; msg1[len1] != '\n') { // If is not in an alphabet (not a letter a-zA-Z) if (!isalpha(msg1[len1])) { ret = free_and_exit(msg1, msg2, ERROR_INPUT); } // Extend if exceed capacity if (++len1 == capacity) { msg1 = (char *)realloc(msg1, capacity * 2); } } while ((msg2[len2] = getchar()) != EOF &amp;&amp; msg2[len2] != '\n') { // If is not in an alphabet (not a letter a-zA-Z) if (!isalpha(msg2[len2])) { ret = free_and_exit(msg1, msg2, ERROR_INPUT); } // Extend if exceed capacity if (++len2 == capacity) { msg2 = (char *)realloc(msg2, capacity * 2); } } if (len1 != len2) { ret = free_and_exit(msg1, msg2, ERROR_LENGTH); } char *msg_temp = (char *)malloc(len1); for (int offset = 0; offset &lt; LAST_UPPER; offset++) { strcpy(msg_temp, msg1); positions[offset] = compare_by_symbol(msg_temp, msg2, len2); } int last_offset = 0; for (int i = 0; i &lt; LAST_UPPER; i++) { if (positions[i] &gt; last_offset) { last_offset = i; } } // Final decode msg1 = shift(msg1, msg2); // Print decoded message printf(&quot;%s\n&quot;, msg1); free(msg_temp); msg_temp = NULL; ret = free_and_exit(msg1, msg2, EXIT_SUCCESS); return ret; } int optional(void) { /* Same as mandatory, only length comparison check is removed */ int ret = EXIT_SUCCESS size_t capacity = DEFAULT_LEN; int positions[LAST_UPPER]; size_t len1 = 0; size_t len2 = 0; char *msg1 = (char *)malloc(capacity); char *msg2 = (char *)malloc(capacity); while ((msg1[len1] = getchar()) != EOF &amp;&amp; msg1[len1] != '\n') { // If is not in an alphabet (not a letter) if (!isalpha(msg1[len1])) { ret = free_and_exit(msg1, msg2, ERROR_INPUT); } // Extend if exceed capacity if (++len1 == capacity) { msg1 = (char *)realloc(msg1, capacity * 2); } } while ((msg2[len2] = getchar()) != EOF &amp;&amp; msg2[len2] != '\n') { // If is not in an alphabet (not a letter) if (!isalpha(msg2[len2])) { ret = free_and_exit(msg1, msg2, ERROR_INPUT); } // Extend if exceed capacity if (++len2 == capacity) { msg2 = (char *)realloc(msg2, capacity * 2); } } char *msg_temp = (char *)malloc(len1); for (int offset = 0; offset &lt; LAST_UPPER; offset++) { strcpy(msg_temp, msg1); positions[offset] = compare_by_symbol(msg_temp, msg2, len2); } int last_offset = 0; for (int i = 0; i &lt; LAST_UPPER; i++) { if (positions[i] &gt; last_offset) { last_offset = i; } } // Final decode msg1 = shift(msg1, msg2); // Print decoded message printf(&quot;%s\n&quot;, msg1); free(msg_temp); msg_temp = NULL; ret = free_and_exit(msg1, msg2, EXIT_SUCCESS); return ret; } </code></pre> <p>EDIT: Valgrind output.</p> <blockquote> <p>==1308== Memcheck, a memory error detector<br /> ==1308== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.<br /> ==1308== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info<br /> ==1308== Command: ./main<br /> ==1308== \ xUbbemehbT\ XYlloworld<br /> ==1308== Conditional jump or move depends on uninitialised value(s)<br /> ==1308== at 0x483F0B7: strcpy (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)<br /> ==1308== by 0x10BAB2: strcpy (string_fortified.h:90)<br /> ==1308== by 0x10BAB2: mandatory (main.c:214)<br /> ==1308== by 0x1091CC: main (main.c:38)<br /> ==1308== Uninitialised value was created by a heap allocation<br /> ==1308== at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)<br /> ==1308== by 0x10B9B7: mandatory (main.c:176)<br /> ==1308== by 0x1091CC: main (main.c:38)<br /> ==1308== <br /> ==1308== Invalid write of size 1<br /> ==1308== at 0x483F0BE: strcpy (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)<br /> ==1308== by 0x10BAB2: strcpy (string_fortified.h:90)<br /> ==1308== by 0x10BAB2: mandatory (main.c:214)<br /> ==1308== by 0x1091CC: main (main.c:38)<br /> ==1308== Address 0x4a495eb is 0 bytes after a block of size 11 alloc'd<br /> ==1308== at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)<br /> ==1308== by 0x10BA9F: mandatory (main.c:210)<br /> ==1308== by 0x1091CC: main (main.c:38)<br /> ==1308== <br /> ==1308== Conditional jump or move depends on uninitialised value(s)<br /> ==1308== at 0x483EF58: strlen (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)<br /> ==1308== by 0x10983F: shift (main.c:79)<br /> ==1308== by 0x10BAC2: mandatory (main.c:228)<br /> ==1308== by 0x1091CC: main (main.c:38)<br /> ==1308== Uninitialised value was created by a heap allocation<br /> ==1308== at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)<br /> ==1308== by 0x10B9B7: mandatory (main.c:176)<br /> ==1308== by 0x1091CC: main (main.c:38)<br /> ==1308== <br /> ==1308== Conditional jump or move depends on uninitialised value(s)<br /> ==1308== at 0x483EF58: strlen (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)<br /> ==1308== by 0x109AB8: sub_shift (main.c:45)<br /> ==1308== by 0x109AB8: shift (main.c:82)<br /> ==1308== by 0x10BAC2: mandatory (main.c:228)<br /> ==1308== by 0x1091CC: main (main.c:38)<br /> ==1308== Uninitialised value was created by a heap allocation<br /> ==1308== at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)<br /> ==1308== by 0x10B9C4: mandatory (main.c:177)<br /> ==1308== by 0x1091CC: main (main.c:38)<br /> ==1308== <br /> ==1308== Conditional jump or move depends on uninitialised value(s)<br /> ==1308== at 0x483EF58: strlen (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)<br /> ==1308== by 0x10AA4E: sub_shift (main.c:45)<br /> ==1308== by 0x10AA4E: shift (main.c:92)<br /> ==1308== by 0x10BAC2: mandatory (main.c:228)<br /> ==1308== by 0x1091CC: main (main.c:38)<br /> ==1308== Uninitialised value was created by a heap allocation<br /> ==1308== at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)<br /> ==1308== by 0x10B9B7: mandatory (main.c:176)<br /> ==1308== by 0x1091CC: main (main.c:38)<br /> ==1308== \ Helloworld<br /> ==1308== <br /> ==1308== HEAP SUMMARY:<br /> ==1308== in use at exit: 0 bytes in 0 blocks<br /> ==1308== total heap usage: 5 allocs, 5 frees, 2,261 bytes allocated<br /> ==1308== <br /> ==1308== All heap blocks were freed -- no leaks are possible<br /> ==1308== <br /> ==1308== For lists of detected and suppressed errors, rerun with: -s<br /> ==1308== ERROR SUMMARY: 107 errors from 5 contexts (suppressed: 0 from 0)</p> </blockquote>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T16:41:20.043", "Id": "533344", "Score": "1", "body": "`size_t len = strlen(message) - 1; // -1 Because of '\\0'` That doesn't make sense, since `strlen` does not count the terminator." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T16:44:55.700", "Id": "533346", "Score": "0", "body": "Here's one problem: `char *msg_temp = (char *)malloc(len1);` It appears `len1` is the count of characters, and does not include room for the terminator." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T16:45:16.897", "Id": "533347", "Score": "0", "body": "Please tell us more about the purpose of the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T16:51:52.497", "Id": "533348", "Score": "0", "body": "Code decodes first input based on how it is similar to the second input which is changed original message. Thanks JDlugosz, now there are a bit less errors" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T16:54:25.730", "Id": "533351", "Score": "0", "body": "Welcome to CR! I am too lazy to compile and run in Valgrind, can you share the Valgrind output at the bottom of your question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T17:12:03.297", "Id": "533356", "Score": "0", "body": "Added valgrind output" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T07:55:13.017", "Id": "533393", "Score": "0", "body": "When you have fixed the code to work to your satisfaction, please do bring it back for review - there are many problems (including bugs) in this code, only some of which are addressed in the existing answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T20:55:26.467", "Id": "533440", "Score": "0", "body": "Solved: Added msg1[len1] = '\\0'; lines after while ((msg1[len1] = getchar()) != EOF && msg1[len1] != '\\n') loops in mandatory and optional functions" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T18:11:15.867", "Id": "533442", "Score": "2", "body": "@sznailc given your update from 21 hours ago, Are you open to [feedback about any or all facets of the code](https://codereview.stackexchange.com/help/on-topic)? If so, then please [edit] the post to contain the working code (with errors removed)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T19:06:24.240", "Id": "533449", "Score": "0", "body": "I really don't understand what this program is supposed to do. Comparing two inputs? I expect a Ceasar Cypher decoder/encoder to take a string and a shift count, and produce the transformed string." } ]
[ { "body": "<pre><code> /* Same as mandatory, only length comparison check is removed */\n</code></pre>\n<p>Don't do that. You duplicated the entire (complex) function to make minor changes; specifically to skip error checks.</p>\n<p>Write one copy of the function. Put the optional checks in another preliminary function that's called first, or pass a boolean parameter to enable/disable the tests.</p>\n<p>You might reconsider whether you want a version that doesn't do error checking. Are these tests super expensive compared to the work being done?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T16:53:16.027", "Id": "533349", "Score": "0", "body": "I'll change it, but it is not the main problem now" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T16:48:08.363", "Id": "270167", "ParentId": "270163", "Score": "1" } }, { "body": "<p><strong>Avoid subtraction with <em>unsigned</em> math</strong></p>\n<p>When <code>message[0] == 0</code> and <code>size_t len = strlen(message) - 1;</code>, <code>len</code> takes on the value of <code>SIZE_MAX</code>. Instead:</p>\n<pre><code>void sub_shift(char *message, char mode) {\n // size_t len = strlen(message) - 1;\n size_t len = strlen(message);\n if (mode == MODE_1)\n {\n // for (size_t letter = 0; letter &lt; len; letter++)\n for (size_t letter = 0; letter + 1 &lt; len; letter++)\n</code></pre>\n<p><strong>Use consistent types</strong></p>\n<p><code>length</code> deserves to be <code>size_t</code> to match calling code and for the best type to use with string lengths.</p>\n<pre><code>size_t compare_by_symbol(const char *msg1, const char *msg2, size_t length) {\n size_t equal_counter = 0;\n for (size_t i = 0; i &lt; length; i++) {\n if (msg1[i] == msg2[i]) {\n equal_counter++;\n }\n }\n return equal_counter;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T00:45:16.800", "Id": "270185", "ParentId": "270163", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T15:15:47.990", "Id": "270163", "Score": "-1", "Tags": [ "c", "caesar-cipher" ], "Title": "Caesar's cipher decoder works but Valgrind shows many errors" }
270163
<p>I wanted to see how simple it would be to implement a stack-based interpreter in C# based on this question: <a href="https://codereview.stackexchange.com/questions/270065/simple-stack-based-interpreter">Simple stack based interpreter</a></p> <p>The program works with the command line arguments which can either be a <code>double</code> or a function from the following table:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>instruction</th> <th>op1</th> <th>op2</th> <th>op3</th> </tr> </thead> <tbody> <tr> <td>abs</td> <td>a</td> <td></td> <td></td> </tr> <tr> <td>acos</td> <td>a</td> <td></td> <td></td> </tr> <tr> <td>acosh</td> <td>a</td> <td></td> <td></td> </tr> <tr> <td>add</td> <td>a</td> <td>b</td> <td></td> </tr> <tr> <td>asin</td> <td>a</td> <td></td> <td></td> </tr> <tr> <td>asinh</td> <td>a</td> <td></td> <td></td> </tr> <tr> <td>atan</td> <td>a</td> <td></td> <td></td> </tr> <tr> <td>atan2</td> <td>a</td> <td>b</td> <td></td> </tr> <tr> <td>atanh</td> <td>a</td> <td></td> <td></td> </tr> <tr> <td>bitdecrement</td> <td>a</td> <td></td> <td></td> </tr> <tr> <td>bitincrement</td> <td>a</td> <td></td> <td></td> </tr> <tr> <td>cbrt</td> <td>a</td> <td></td> <td></td> </tr> <tr> <td>ceiling</td> <td>a</td> <td></td> <td></td> </tr> <tr> <td>clamp</td> <td>a</td> <td>b</td> <td>c</td> </tr> <tr> <td>copysign</td> <td>a</td> <td>b</td> <td></td> </tr> <tr> <td>cos</td> <td>a</td> <td></td> <td></td> </tr> <tr> <td>cosh</td> <td>a</td> <td></td> <td></td> </tr> <tr> <td>div</td> <td>a</td> <td>b</td> <td></td> </tr> <tr> <td>exp</td> <td>a</td> <td></td> <td></td> </tr> <tr> <td>floor</td> <td>a</td> <td></td> <td></td> </tr> <tr> <td>fusedmultiplyadd</td> <td>a</td> <td>b</td> <td>c</td> </tr> <tr> <td>ieeeremainder</td> <td>a</td> <td>b</td> <td></td> </tr> <tr> <td>log</td> <td>a</td> <td>b</td> <td></td> </tr> <tr> <td>log10</td> <td>a</td> <td></td> <td></td> </tr> <tr> <td>log2</td> <td>a</td> <td></td> <td></td> </tr> <tr> <td>max</td> <td>a</td> <td>b</td> <td></td> </tr> <tr> <td>maxmagnitude</td> <td>a</td> <td>b</td> <td></td> </tr> <tr> <td>min</td> <td>a</td> <td>b</td> <td></td> </tr> <tr> <td>minmagnitude</td> <td>a</td> <td>b</td> <td></td> </tr> <tr> <td>mul</td> <td>a</td> <td>b</td> <td></td> </tr> <tr> <td>pow</td> <td>a</td> <td>b</td> <td></td> </tr> <tr> <td>round</td> <td>a</td> <td></td> <td></td> </tr> <tr> <td>sin</td> <td>a</td> <td></td> <td></td> </tr> <tr> <td>sinh</td> <td>a</td> <td></td> <td></td> </tr> <tr> <td>sqrt</td> <td>a</td> <td></td> <td></td> </tr> <tr> <td>sub</td> <td>a</td> <td>b</td> <td></td> </tr> <tr> <td>tan</td> <td>a</td> <td></td> <td></td> </tr> <tr> <td>tanh</td> <td>a</td> <td></td> <td></td> </tr> <tr> <td>truncate</td> <td>a</td> <td></td> <td></td> </tr> </tbody> </table> </div> <p>Example programs:</p> <p>hypot: expected result: 5</p> <pre class="lang-python prettyprint-override"><code>4 2 pow 3 2 pow add sqrt </code></pre> <p>After having some fun with <code>Reflection</code> and <code>Linq</code> I came up with the following code:</p> <pre class="lang-cs prettyprint-override"><code>using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace StackProg { class SimpleMath { public static double add(double a, double b) { return a + b; } public static double sub(double a, double b) { return a - b; } public static double mul(double a, double b) { return a * b; } public static double div(double a, double b) { return a / b; } } class Program { static void Main(string[] args) { var methods = new SortedDictionary&lt;string, Tuple&lt;int, MethodInfo&gt;&gt;(); foreach (var type in new Type[] {typeof(SimpleMath), typeof(Math)}) { foreach (var method in type.GetMethods().Where(m =&gt; m.ReturnType == typeof(double))) { var margs = method.GetParameters(); if (margs.Any(p =&gt; p.ParameterType != typeof(double)) == false) methods[method.Name.ToLower()] = new Tuple&lt;int, MethodInfo&gt;(margs.Length, method); } } var stack = new Stack&lt;double&gt;(); foreach (var arg in args) { if (double.TryParse(arg, out var val)) { stack.Push(val); } else if (methods.TryGetValue(arg, out var method)) { stack.Push((double)method.Item2.Invoke(null, PopStack(stack, method.Item1))); } else { Console.WriteLine(&quot;Invalid instruction: &quot; + arg); return; } } Console.Write(stack.Pop()); } private static object[] PopStack(Stack&lt;double&gt; stack, int count) { var list = new List&lt;object&gt;(count); for (int i = 0; i &lt; count; i++) list.Insert(0, stack.Pop()); return list.ToArray(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T09:58:40.990", "Id": "533407", "Score": "1", "body": "I would suggest to use [ValueTuple with named fields](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-tuples#tuple-field-names) to increase readability. `Item1` and `Item2` are not really coder friendly names" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T10:00:34.010", "Id": "533408", "Score": "1", "body": "Also in case of `PopStack` you know the `count` so you can create an array with the specified length and you don't have to use an intermediate List collection." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T14:37:05.740", "Id": "533427", "Score": "0", "body": "@PeterCsala, Thanks for the nice tips! `PopStack` sort of bugged me. I considered using a `ConcurrentStack` which has `TryPopRange` but that looked ugly :-)" } ]
[ { "body": "<h3><code>PopStack</code></h3>\n<ul>\n<li>This can be rewritten like this using LINQ:</li>\n</ul>\n<pre><code>private static object[] PopStack(Stack&lt;double&gt; stack, int count)\n =&gt; Enumerable.Range(0, count).Select(_ =&gt; stack.Pop()).Cast&lt;object&gt;().ToArray();\n</code></pre>\n<h3><code>SimpleMath</code></h3>\n<ul>\n<li>This class can be marked as <code>static</code> since all of its members are <code>static</code></li>\n<li>This class looks a bit weird/odd to me\n<ul>\n<li>You have defined a class just to expose built-in operators</li>\n<li>The methods' naming do not follow C# standards</li>\n</ul>\n</li>\n<li>My alternative solution relies on lambda expressions:</li>\n</ul>\n<pre><code>static Dictionary&lt;string, Func&lt;double, double, double&gt;&gt; simpleMath = new()\n{\n { &quot;add&quot;, (a, b) =&gt; a + b },\n { &quot;sub&quot;, (a, b) =&gt; a - b },\n { &quot;mul&quot;, (a, b) =&gt; a * b },\n { &quot;div&quot;, (a, b) =&gt; a / b },\n};\n</code></pre>\n<ul>\n<li>Yes I know, the <code>simpleMath</code>'s type is ugly as hell\n<ul>\n<li>But we have avoided to repeat this: <code>public static double (double , double ) { return ; }</code></li>\n<li>Here the naming can be arbitrary, it does not have to follow any standard</li>\n</ul>\n</li>\n<li>Because these methods are not <code>static</code> that's why they need an <em>invocation target</em> as well.\n<ul>\n<li>So, we need to store that information next to the name and method info</li>\n<li>I've defined a <code>record</code> structure for that</li>\n</ul>\n</li>\n</ul>\n<pre><code>record MethodInvocation(int ParameterCount, MethodInfo Method, object Target)\n{\n}\n</code></pre>\n<ul>\n<li>Finally let's transform the <code>simpleMath</code> to the desired form</li>\n</ul>\n<pre><code>static IEnumerable&lt;KeyValuePair&lt;string, MethodInvocation&gt;&gt; GetSimpleMath()\n{\n foreach (var operation in simpleMath)\n {\n var mi = operation.Value.Method;\n yield return new (operation.Key, new MethodInvocation(mi.GetParameters().Length, mi, operation.Value.Target));\n }\n}\n</code></pre>\n<h3>AdvancedMath</h3>\n<ul>\n<li>Following the same pattern as above we can do the same with the built-in methods:</li>\n</ul>\n<pre><code>static IEnumerable&lt;KeyValuePair&lt;string, MethodInvocation&gt;&gt; GetAdvancedMath()\n{\n foreach (var method in typeof(Math).GetMethods().Where(m =&gt; m.ReturnType == typeof(double)))\n {\n var @params = method.GetParameters();\n if (@params.Any(p =&gt; p.ParameterType != typeof(double)) is not true)\n yield return new (method.Name.ToLower(), new MethodInvocation(@params.Length, method, null));\n }\n}\n</code></pre>\n<h3>Main</h3>\n<ul>\n<li>With these in our hand we can simplify the first part of the <code>Main</code> method like this</li>\n</ul>\n<pre><code>static void Main(string[] args)\n{\n var methods = new SortedDictionary&lt;string, MethodInvocation&gt;();\n\n foreach (var operation in GetSimpleMath())\n methods.Add(operation.Key, operation.Value);\n\n foreach (var operation in GetAdvancedMath())\n methods.TryAdd(operation.Key, operation.Value);\n\n var operationStack = new Stack&lt;double&gt;();\n \n foreach (var arg in args)\n {\n if (double.TryParse(arg, out var val))\n {\n operationStack.Push(val);\n }\n else if (methods.TryGetValue(arg, out var method))\n {\n var @params = PopStack(operationStack, method.ParameterCount);\n var result = (double)method.Method.Invoke(method.Target, @params);\n operationStack.Push(result);\n }\n else\n {\n Console.WriteLine(&quot;Invalid instruction: &quot; + arg);\n return;\n }\n }\n Console.Write(operationStack.Pop());\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T17:55:25.610", "Id": "270199", "ParentId": "270164", "Score": "2" } } ]
{ "AcceptedAnswerId": "270199", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T16:03:04.923", "Id": "270164", "Score": "2", "Tags": [ "c#" ], "Title": "Simple stack based interpreter, C# style" }
270164
<p>I'm just learning how to allow interconnected apps via Sockets, watched a tutorial last night and based on that this is what I've gotten:</p> <pre><code>Server.cs </code></pre> <p>Code:</p> <pre><code>using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; namespace SocketsLiveTest { internal class Server { private static void Main(string[] args) { //listener to handle incoming connections TcpListener listener = new TcpListener(IPAddress.Any, &lt;redacted port&gt;); listener.Start(); //log that it started Console.WriteLine(&quot;Server started, waiting for connections...&quot;); TcpClient client; while (true) { //connect the client client = listener.AcceptTcpClient(); //log client connected Console.WriteLine(&quot;Client connected @ {0} - {1}&quot;, ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString(), DateTime.Now.ToString()); //send to another thread to allow other connections, probably won't be necessary as there should only be 1 client ThreadPool.QueueUserWorkItem(DoClientWork, client); } } private static void DoClientWork(object obj) { //get client var client = (TcpClient)obj; //NetworkStream clientStream = client.GetStream(); //initialize stream writer to send data to client StreamWriter clientWriter = new StreamWriter(client.GetStream()); clientWriter.AutoFlush = true; //for testing purposes, will probably manually flush in final int breakAmount = 1; //prevent looping during testing while (true) { //junk message for testing clientWriter.WriteLine(&quot;DID THIS WORK? Push {0}&quot;, breakAmount); //more testing stuff breakAmount++; if (breakAmount &gt;= 10) break; } } } } </code></pre> <p>The <code>breakAmount</code> portion of <code>DoClientWork</code> is purely to prevent a loop as currently I haven't thought of a close reason. This will be used in some sort of pub/sub service eventually to push some serialized objects over to the client. I'm thinking I will just have it infinitely loop and check a database for new info to send, since this should really always be running unless manually shutdown. Would that be the appropriate way to handle a pub/sub relationship? Get them connected and then continuously loop for data to queue up and send to the client?</p> <p>This is a client I wrote to just test functionality:</p> <pre><code>Client.cs </code></pre> <p>Code:</p> <pre><code>using System; using System.IO; using System.Net.Sockets; namespace SocketsClientLiveTest { internal class Client { private static void Main(string[] args) { int connectionAttempts = 1; int allowedAttempts = 10; bool connectionSuccess = false; TcpClient client = new TcpClient(); while (connectionAttempts &lt;= allowedAttempts) { Console.WriteLine(&quot;Attempting connection, attempt: {0} of {1}&quot;, connectionAttempts.ToString(), allowedAttempts.ToString()); try { client = new TcpClient(&quot;192.168.15.32&quot;, 4040); Console.WriteLine(&quot;Successful connection on attempt {0}&quot;, connectionAttempts); Console.WriteLine(&quot;Attempting to read...&quot;); connectionSuccess = true; break; } catch (Exception) { connectionAttempts++; Console.WriteLine(&quot;Failed to connect, retrying...&quot;); } } if (connectionSuccess) { bool doneReading = false; int readAttempts = 1; while (!doneReading) { StreamReader serverReader = new StreamReader(client.GetStream()); string serverMessage = serverReader.ReadLine(); Console.WriteLine(&quot;Server message received: {0}&quot;, serverMessage); readAttempts++; if (readAttempts &gt; 3) { doneReading = true; } } } } } } </code></pre> <p>I'm not entirely concerned about <code>Client.cs</code> since, as I said, I'm not going to be responsible for it. If you have ideas on it though, I'd love to hear them for educational purposes, but like the server <code>breakAmount</code>, it does just have some junk in there to prevent looping forever.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T17:37:47.633", "Id": "533361", "Score": "1", "body": "After reading the title, I thought you were trying to implement some sort of artificial intelligence machine learning socket ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T17:45:52.507", "Id": "533363", "Score": "1", "body": "If only @upkajdt! The solution to AI was to just slap as many applications together!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T03:47:22.177", "Id": "533387", "Score": "0", "body": "Is there a reason why you declare `client` outside of the server loop instead of using `var client = listener.AcceptTcpClient();` or `TcpClient client = listener.AcceptTcpClient();`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T14:28:44.193", "Id": "533426", "Score": "0", "body": "@user No specific reason, that's just how the example handling multiple connections I followed was set up, and didn't bother moving it around." } ]
[ { "body": "<h1>Disposing of Disposables</h1>\n<p>The main problem in your code is that you are not disposing of <code>clientWriter</code>. A good rule to remember is that you should <b>always</b> dispose of disposable objects. If you do not dispose of <code>clientWriter</code> then it will never be flushed or closed and will result in a bucket of hurt.</p>\n<p>Consider using <code>using</code> to automatically dispose of <code>clientWriter</code></p>\n<pre><code>using StreamWriter clientWriter = new StreamWriter(client.GetStream());\nclientWriter.AutoFlush = true;\n</code></pre>\n<h1>Infinite Loops</h1>\n<p>In <code>DoClientWork</code> you have an infinite loop and break out when <code>breakAmount</code> is &gt;= 10</p>\n<p>Consider changing it to the following:</p>\n<pre><code>while (breakAmount &lt; 10)\n</code></pre>\n<p>Or, even better, use a <code>for</code> loop:</p>\n<pre><code>for (int i=1; i &lt;= 10; i++)\n{\n //junk message for testing\n clientWriter.WriteLine(&quot;DID THIS WORK? Push {0}&quot;, i);\n}\n</code></pre>\n<h1>Reading all the text in the stream</h1>\n<p>In the client code, you are simply repeating calls to <code>serverReader.ReadLine</code> instead of checking if there is anything left in the stream. Consider changing to the following:</p>\n<pre><code>if (connectionSuccess)\n{\n StreamReader serverReader = new StreamReader(client.GetStream());\n while (serverReader.EndOfStream == false)\n {\n Console.WriteLine(serverReader.ReadLine());\n }\n}\n</code></pre>\n<h1>Two-way communication</h1>\n<p>You can easily add two-way communication by using the following code</p>\n<p><b>Server</b></p>\n<pre><code>private static void DoClientWork(object obj)\n{\n using var client = (TcpClient)obj;\n using var writer = new StreamWriter(client.GetStream());\n using var reader = new StreamReader(client.GetStream());\n for (int i=1; i &lt;= 10; i++)\n {\n writer.WriteLine(&quot;DID THIS WORK? Push {0}&quot;, i);\n writer.Flush();\n // read response\n string response = reader.ReadLine();\n Console.WriteLine(response);\n }\n}\n</code></pre>\n<p><b>Client</b></p>\n<pre><code>if (connectionSuccess)\n{\n using var reader = new StreamReader(client.GetStream());\n using var writer = new StreamWriter(client.GetStream());\n while (reader.EndOfStream == false)\n {\n string line = reader.ReadLine();\n Console.WriteLine(line);\n // write response\n writer.WriteLine(line.Replace(&quot;DID THIS WORK?&quot;, &quot;YES IT DID!&quot;));\n writer.Flush();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T20:28:27.123", "Id": "533369", "Score": "1", "body": "Unfortunately, I'm using C# 7.3, so I can't use the `using var reader` syntax. The infinite loops were also a purposeful design while I mess with some stuff, those will likely get stripped out with an entirely different looping mechanism. I do think two way communication will be useful though! And I'm glad to have all of this for future reference on, thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T21:19:17.667", "Id": "533373", "Score": "0", "body": "@Austin, for older versions of C# you need to use curly braces to define the scope of `using` like the [this](https://tio.run/##dZBNbsIwEIX3OcU0K1tqwwFQ1AXQErUSEomEWFrOUCwZJ7IdskA5e@ofNgkwG9vj9755Njcf3PBxNJZZweHaiBp0p0jF25UUqCzwsNDkloCrzgj1B@TKNGhkNWrIQWEPpXXHyz60SLRk32hjm1BKgzsyZpxeCzvjHELrNWfK8tWfhUQgMVO2UfXuFD2Q53Bi0iCd6KduX8ZqH0kKhS7LHeQf9Os6hC4fDKtGmUZiFsIGkfc@ES4W8Y0OalpnwgdF/IIZyQ1vJeNI0nWxhmpblHDY7X8@03dIj5sSigrcxVtKn4y8A79kZ87z7EMy3Q3JMI7/). Ps I had some fun playing with sockets." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T21:20:56.183", "Id": "533374", "Score": "0", "body": "I'm aware for the braces, but I'd rather not try to wrap everything into those two layer right at this point. I have a feeling that's what it will come to once this is fleshed out in the full TCP server though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T00:03:54.827", "Id": "533382", "Score": "0", "body": "@Austin Cool I get that =) The thing is that we are not reviewing you as a programmer, but only the code in question. Some of the observations and tips may be things that you know but may be helpful to other people purely looking at the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T00:22:56.853", "Id": "533383", "Score": "1", "body": "Haha I see. Thanks for the feedback, I definitely learned a few things!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T03:45:05.200", "Id": "533386", "Score": "1", "body": "You'll probably also want to dispose of the client in the `DoClientWork` function (`using TcpClient client = (TcpClient)obj;` or similar)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T12:29:07.593", "Id": "533416", "Score": "0", "body": "@user, I think you're correct although it looks a bit odd to dispose of something that you are \ntechnically not the owner of?" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T18:30:32.447", "Id": "270171", "ParentId": "270165", "Score": "5" } } ]
{ "AcceptedAnswerId": "270171", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T16:11:31.873", "Id": "270165", "Score": "3", "Tags": [ "c#", ".net", "socket", "tcp" ], "Title": "Learning Sockets in C# (.Net Framework), Suggested Improvements?" }
270165
<h3>The Goal</h3> <h5>Current PHP version 7.3.5</h5> <p>The block will have a function that sources a defined set of illustrations that are stored in <code>{themeName}/images/illustrations</code>. Those file names are then used to populate a list in the block editor (<code>index.js</code>) as well as be assigned to an attribute. Those attributes will be used in the <code>output.php</code> file to display the selected image.</p> <p>This functionality is part of a larger block operation, which I have omitted to focus on the original question/request (it can be added if required).</p> <h3>How I have approached it</h3> <p>So I am aware of the ability to localize a script and use it in the editor. I have opted for this to <code>get_template_directory</code> and navigate to the required directory. once there I am using <code>scandir()</code> to get the contents, as well as removing the '.' and '..' files from the beginning.</p> <p>Once that is done I am converting the array to a string, then use this string as my localized script.</p> <p>In <code>index.js</code> I am converting the string to an array at the &quot;|&quot;. Then iterating over the array and pushing 'value' and 'label' keys to the <code>illustrationChoices</code> array. This array is then being used as options in the <code>selectControl</code> further down the file.</p> <p>It is this section I am very new to and do not know if I have added extra parts that can be omitted. There are probably other areas that need attention but this, in particular, was the part that took the most effort. It is a bit of a hodge-podge of code I have come across through various searches and code I have access to.</p> <p>As always, any guidance is much appreciated.</p> <pre class="lang-php prettyprint-override"><code>function core_banner_image_block_init() { $dir = get_template_directory() . '/gutenberg'; $index_js = 'banner-image/index.js'; wp_register_script( 'core-banner-image-block-editor', get_template_directory_uri() . &quot;/gutenberg/$index_js&quot;, array( 'wp-block-editor', 'wp-blocks', 'wp-i18n', 'wp-element', ), filemtime( &quot;$dir/$index_js&quot; ) ); wp_set_script_translations( 'core-banner-image-block-editor', 'banner-image' ); // Ready the script to be localized // Get the directory and its content $illustrationsDir = get_template_directory() . '/images/illustrations/'; $dirContents = array_diff(scandir($illustrationsDir), array('.', '..')); // Convert to a string with | separator $dirContents = implode(&quot;|&quot;, $dirContents); // Localize the script in index.js wp_localize_script('core-banner-image-block-editor', 'bannerImageLocalizedVariables', [ 'illustrationsDir' =&gt; $dirContents, ]); $editor_css = 'banner-image/editor.css'; wp_register_style( 'core-banner-image-block-editor', get_template_directory_uri() . &quot;/gutenberg/$editor_css&quot;, array(), filemtime( &quot;$dir/$editor_css&quot; ) ); $style_css = 'banner-image/style.css'; wp_register_style( 'core-banner-image-block', get_template_directory_uri() . &quot;/gutenberg/$style_css&quot;, array(), filemtime( &quot;$dir/$style_css&quot; ) ); register_block_type( 'core/banner-image', array( 'editor_script' =&gt; 'core-banner-image-block-editor', 'editor_style' =&gt; 'core-banner-image-block-editor', 'style' =&gt; 'core-banner-image-block', 'render_callback' =&gt; 'core_banner_image_render' ) ); } add_action( 'init', 'core_banner_image_block_init' ); function core_banner_image_render($attr, $content) { $html = ''; $selectedillustration = ''; $illustrationMarkup = ''; $modifers = array(); $modifers[] = $illustration = (isset($attr['includeillustration']) ? $attr['includeillustration'] : ''); if($illustration) { $selectedillustration = $attr['selectedillustration']; $modifers[] = $selectedIllustrationType = 'illustration__type--' . $selectedillustration; $modifers[] = $illustrationAlignment = (isset($attr['illustrationalignment']) ? $attr['illustrationalignment'] : 'illustration__align--left'); $illustrationMarkup = '&lt;div class=&quot;bannerimage__illustration&quot;&gt; &lt;picture&gt; &lt;img loading=&quot;lazy&quot; src=&quot;' . get_template_directory_uri() . '/images/illustrations/' . $selectedillustration .'.png&quot; alt=&quot;' . $selectedillustration . ' illustration&quot; /&gt; &lt;/picture&gt; &lt;/div&gt;'; } $html = '&lt;div class=&quot;bannerimage ' . implode(&quot; &quot;, $modifers) . '&quot;&gt;'; if($illustration) { $html .= $illustrationMarkup; } $html .= '&lt;/div&gt;'; return $html; } </code></pre> <pre class="lang-js prettyprint-override"><code>( function( wp ) { var registerBlockType = wp.blocks.registerBlockType; var el = wp.element.createElement; var __ = wp.i18n.__; const { illustrationsDir } = bannerImageLocalizedVariables; const { RadioControl, ToggleControl, SelectControl, PanelBody, Button } = wp.components; const { useBlockProps, InspectorControls, MediaUpload } = wp.blockEditor; registerBlockType( 'core/banner-image', { apiVersion: 2, title: __( 'Banner Image', 'banner-image' ), description: __( 'Displays a full-width banner image', 'banner-image' ), category: 'design', icon: 'format-image', supports: { html: false, }, attributes: { includeillustration: { type: 'string', default: '' }, selectedillustration: { type: 'string', default: '' }, illustrationalignment: { type: 'string', default: 'illustration__align--left' } }, edit: function(props) { const { attributes, setAttributes } = props; const { includeillustration, selectedillustration, illustrationalignment } = attributes; // Get the localized script and split it at | and convert to an array let illustrationFileNames = illustrationsDir.split(&quot;|&quot;); let illustrationChoices = []; // For each item in the array // Split the filename into two parts - [0] name - [1] extension // Push a value and label key to use in the options selector illustrationFileNames.forEach(fileItem =&gt; { let fileItemParts = fileItem.match(/[^\.]+/); illustrationChoices.push({ value: fileItemParts[0], label: fileItemParts[0].charAt(0).toUpperCase() + fileItemParts[0].slice(1) }); }); return el( 'div', useBlockProps(attributes), el( 'p', { className: 'block__title' }, __( 'Banner Image', 'banner-image' ) ), // INSPECTOR CONTROLS BEGIN el( InspectorControls, null, // BLOCK STYLING el( PanelBody, { title: 'Banner Image Styling' }, el( ToggleControl, { label: 'Include Illustration?', checked: includeillustration, onChange: () =&gt; setAttributes({ includeillustration: includeillustration ? '' : 'include__illustration' }) } ), includeillustration &amp;&amp; el( SelectControl, { label: 'Select an Illustration', options: illustrationChoices, value: selectedillustration, onChange: value =&gt; setAttributes({ selectedillustration: value }) } ), includeillustration &amp;&amp; el( RadioControl, { label: 'Illustration Alignment', selected: illustrationalignment, options: [ { label: 'Left', value: 'illustration__align--left' }, { label: 'Center', value: 'illustration__align--center' }, { label: 'Right', value: 'illustration__align--right' }, ], onChange: value =&gt; setAttributes({ illustrationalignment: value }) } ) ), ), // INSPECTOR CONTROLS END // BLOCK PREVIEW BEGINS el( 'div', { className: 'bannerimage' }, el( 'p', null, &quot;Just a preview init?&quot; ), ), // BLOCK PREVIEW ENDS ) }, save: function() { return null; }, } ); }( window.wp ) ); <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T17:37:55.653", "Id": "270169", "Score": "0", "Tags": [ "javascript", "php", "wordpress" ], "Title": "Wordpress Custom Block that sources files from the theme images directory" }
270169
<p>[edit acc. a comment:]</p> <p>Goal: clean <strong>correct</strong> powers of ten acc. IEEE 754 definition <strong>'nearest'.</strong> Useable also in a 'C' environment.</p> <p>As far as I could test evaluation of '1Ei' strings <strong>is</strong> nearest with most compilers / options,</p> <p>To what end: I'm testing / investigating to which extent reliable rounding could be performed, and there - at the limit of capabilities - every bit counts.</p> <p>[/edit]</p> <p>Besides it's solved for the range urgently needed by workarounds (but slow since 'string-math'), and besides most powers are inexact due to representation restrictions with finite binary figures, I am still curious why we couldn't get any usual compiler to calculate 'clean' powers of 10 for integer exponents and 80-bit long doubles. 'clean' here: matching the respective 'E-string':</p> <p>TIA for any help.</p> <pre><code>'10L^n' = '1En' or '10L**n' = '1En' or 'powl( 10L, n )' = '1En' or 'pow10l( n )' = '1En' or 'exp10l( n )' = '1En' ... </code></pre> <p>doesn't matter, one functioning function would do.</p> <p>I cannot simply use the results of icpx shown below because i need them in a 'pure C' project compiled with gcc.</p> <p>I'd like to either gcc achieve the same good results, yet alone already g++ produces 988 fails, or the results from icpx wrapped into a shared library which i can call from 'standard C' functions. But I couldn't get '-cc1' to work together with '-shared' + '-fpic'.</p> <p>The following code compiled with Intel's 'icpx' compiler from the 'oneAPI' suite</p> <pre><code>icpx -Ofast -march=native powers10l.cpp -o powers10l </code></pre> <p>results in 'error count 0', while any other compilers produce ... less optimal results. icpx is not compiling itself but using clang++ for it, with a big bunch of options, settings and includes, i tried to boil it down, see below.</p> <p>code:</p> <pre><code> /*---------------------------------------------------*/ /* Check different calculations for powers of ten */ /* e.g. mostly 'POW( 10, x )' != '1Ex' != '=10^x' */ /* depending on compiler and options. */ /*---------------------------------------------------*/ // this program is part of my 'deco-Math' project. // issue_I0005a_weak_powers_of_ten // - WIP! -, striving for DEcimal COrrect calculations. // ( also with FP numbers acc. IEEE 754). // Copyright (c) 2021 ... Bernhard Samtleben, Hamburg, Germany. // all rights reserved, for the moment company secret.. // contact: see README #include &lt;iostream&gt; #include &lt;iomanip&gt; // reg. std::setprecision, #include &lt;math.h&gt; // reg. pow, pow10, exp10, ...,powl, pow10l, exp10l, ..., // #include &lt;mathcalls.h&gt; // reg. __exp10l, ..., // #include &quot;libpowers10l.h&quot; int main( void ) { // mynamespace::helloWorld(); /// helloWorld(); int error_count = 0; char btxt[ 10 ]; for( int i = -4952; i &lt; 4933; i++ ) // full range, // for( int i = -10; i &lt; 11; i++ ) // reduced range, { // long double a = mynamespace::power10l( i ); long double a = exp10l( i ); /// long double a = power10l( i ); /// long double a = __exp10l( i ); sprintf( btxt, &quot;1e%d&quot;, i ); // scientific string, long double b = strtold( btxt, NULL ); // value of scientific string, seems not needing 'L' suffix, std::cout &lt;&lt; std::scientific &lt;&lt; std::setprecision( 25 ) &lt;&lt; &quot;power10l( &quot; &lt;&lt; i &lt;&lt; &quot; ) per 'exp10l'= &quot; &lt;&lt; a &lt;&lt; std::endl; // just to have some output, if ( a != b ) { std::cout &lt;&lt; std::scientific &lt;&lt; std::setprecision( 25 ) &lt;&lt; &quot;power10l( &quot; &lt;&lt; i &lt;&lt; &quot; ) per 'exp10l'= &quot; &lt;&lt; a &lt;&lt; std::endl; // std::cout &lt;&lt; std::scientific &lt;&lt; std::setprecision( 25 ) &lt;&lt; &quot;power10l( &quot; &lt;&lt; i &lt;&lt; &quot; ) per 'powl()'= &quot; &lt;&lt; powl( 10, i ) &lt;&lt; std::endl &lt;&lt; std::endl; std::cout &lt;&lt; std::scientific &lt;&lt; std::setprecision( 25 ) &lt;&lt; &quot;power10l( &quot; &lt;&lt; i &lt;&lt; &quot; ) per '1Ei'= &quot; &lt;&lt; b &lt;&lt; std::endl &lt;&lt; std::endl; error_count++; } } std::cout &lt;&lt; std::fixed &lt;&lt; std::setprecision( 0 ) &lt;&lt; &quot;error_count = &quot; &lt;&lt; error_count &lt;&lt; std::endl; printf( &quot;error_count = %d\n &quot;, error_count ); return( 0 ); } </code></pre> <p>the compiler call, i'd catch it with '-v' and strip everything which wasn't really required:</p> <pre><code>#!/usr/bin/env bash # this couple of commands compiles a standalone program,. # with options which do produce clean powers of ten,. # alas i can't yet call it from other modules. # // this program is part of my 'deco-Math' project, # // issue_I0005a_weak_powers_of_ten # # // Copyright (c) 2021 ... Bernhard Samtleben, Hamburg, Germany # # // this program / collection is provided in hope it can be useful, # // but WITHOUT ANY WARRANTY, to the extent permitted by law, without # // even the implied warranty of MERCHANTABILITY or FITNESS FOR ANY # // OR A PARTICULAR PURPOSE. # // !!! --- CHECK BEFORE USE, USE AT YOUR OWN RISK --- !!! # # // this program is free software, private use or use in free software # // acc. Apache or GNU Licenses is free, # // use in profit oriented businesses requires agreeing about a fee # // with the author in advance. # # // further info: see README clang++ -cc1 -emit-obj \ \ \ -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 \ -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 \ \ -internal-isystem /opt/intel/oneapi/compiler/2021.4.0/linux/lib/clang/13.0.0/include \ \ \ -internal-externc-isystem /usr/include/x86_64-linux-gnu \ \ -internal-externc-isystem /usr/include \ -o powers10l.o -x c++ powers10l.cpp ld --eh-frame-hdr -m elf_x86_64 -dynamic-linker /lib64/ld-linux-x86-64.so.2 -o powers10l /lib/x86_64-linux-gnu/crt1.o /lib/x86_64-linux-gnu/crti.o /usr/lib/gcc/x86_64-linux-gnu/10/crtbegin.o \ -L/opt/intel/oneapi/compiler/2021.4.0/linux/bin/../compiler/lib/intel64_lin -L/opt/intel/oneapi/compiler/2021.4.0/linux/bin/../lib -L/opt/intel/oneapi/compiler/2021.4.0/linux/bin/../compiler/lib/intel64_ powers10l.o -Bstatic -limf -Bdynamic -lm -Bstatic -lsvml -Bdynamic -Bstatic -lirng -Bdynamic -lstdc++ -Bstatic -limf -Bdynamic -lm -lgcc_s -lgcc -Bstatic -lirc -Bdynamic -ldl -lgcc_s -lgcc -lc -lgcc_s -l ./powers10l </code></pre> <p>you might see in the residues in the code: i tried hard and plenty of possibilities and options,<br /> if anything wrong with this posting or stupidities in the code, pls. be indulgent, 'newbie' ...</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T08:59:48.513", "Id": "533399", "Score": "1", "body": "At Code Review we only review complete and working code. This question is better suited for [StackOverflow](https://stackoverflow.com/questions)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T10:55:08.613", "Id": "533411", "Score": "0", "body": "hello @G.Sliepen, 'working' - it is! working, just has a shortcoming for which I'd like to have an improvement | 'SO' - yes, but the 'downvoting culture' there turned out not to be compatible with my creative questions :-(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-18T12:57:12.223", "Id": "533417", "Score": "2", "body": "The \"shortcoming\" is just the code not working as expected, and that clearly means your question is off-topic for Code Review. Also see this [guide to asking questions on Code Review](https://codereview.meta.stackexchange.com/q/2436). I suggest you simplify the question to something like \"why is `strtold(\"1eXX\")` not equal to `exp10l(XX)` with these compilers?\" and do try it on StackOverflow. If they do downvote, try to understand their reasoning for it and adjust your questions accordingly; this will help you get your questions upvoted in the future." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T08:39:53.260", "Id": "533490", "Score": "0", "body": "For the amount of paraphernalia shown and the sequence of presentation, it is very hard to get what you are trying to achieve. Please state the goal near the top of the question body, define what *is* a `clean power of ten` and tell to what end it/they would be used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T14:19:37.440", "Id": "533520", "Score": "0", "body": "hello @greybeard, thanks for the hint, i really had tried to explain the goal and problem in an understandable way, and therefore placed the key points where they fit into the flow / logic ..." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-17T18:25:49.617", "Id": "270170", "Score": "-1", "Tags": [ "c", "mathematics", "compiler" ], "Title": "get clean powers of ten, with C or as 'with C shareable library', for integer exponents, for 80-bit long doubles" }
270170