body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I need simple caching for one of my web-services so I use the <code>Microsoft.Extensions.Caching.Memory</code> package. I wrapped it with <code>SemaphoreSlim</code> to make sure reading and writing are <em>safe</em>. I'm not sure what I'm doing here is entirely correct. What do you think? Is this wrapper OK or can I turn <code>GetOrCreateAsync</code> into an extension for <code>IMemoryCache</code> and it'll handle everything?</p> <pre><code>public class CacheService { private static readonly SemaphoreSlim Locker = new SemaphoreSlim(1, 1); private readonly IMemoryCache _cache; public CacheService(IMemoryCache cache) { _cache = cache; } public async Task&lt;T&gt; GetOrCreateAsync&lt;T&gt;(object key, Func&lt;Task&lt;T&gt;&gt; create) { await Locker.WaitAsync(); try { if (_cache.TryGetValue(key, out var entry)) { return (T)entry; } else { return _cache.Set(key, await create(), new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(17) }); } } finally { Locker.Release(); } } } </code></pre>
[]
[ { "body": "<p>Sorry this is a bit of a ramble, but a few things jump out at me:</p>\n\n<ol>\n<li><p><code>17</code>?!?! I don't have to tell <em>you</em> about magic numbers! This should probably be configurable... somehow...</p></li>\n<li><p>Why is <code>Locker</code> static? It doesn't make sense to restrict access to one cache because a totally different cache is currently in use.</p></li>\n<li><p>Locking the cache while you create an item isn't necessarily going to end well: it would be all too easy for <code>create</code> to try to access the cache, and now you have a deadlock. The 'easiest' way to resolve this would be to slightly abuse the cache, and instead of storing the values themselves store some wrapper which indicates whether the value is written yet with a different concurrency mechanism. This way, you can add a 'pending' value to the cache immediately, which can be initialised outside the lock. </p>\n\n<p>This increases the complexity of dealing with <code>create</code> failures, because you have to communicate between threads with some other object, but now you can only dead-lock yourself by trying to access the object your are currently creating. It would be nice to detect this, but I think it might be impossible, so you probably want to give whatever mechanism awaits the pending entry a time-out. I don't think you can do better than this without passing the complexity off to the caller, which of course would ruin the nice API.</p>\n\n<p>A better solution would probably be to provide a completely separate concurrency mechanism for handling 'pending' values, so that there is less overhead and complexity accessing the cache (presumably the more common operation). It wouldn't store the values, but rather just provide a mechanism to wait for them to appear in the proper cache (on a key-by-key basis).</p></li>\n<li><p>I'd prefer that the cast to <code>(T)</code> was checked first, so that you can throw a highly-specific exception explaining that whatever was in the cache was not what the caller was expecting.</p></li>\n<li><p>Since you are providing the access control, your class is probably also responsible for disposing the cache: it should provide this facility. Disposing <code>Locker</code> is also a concern. This adds to the opportunity for a consumer to get cryptic error messages if they are trying to access the cache as it is disposed.</p></li>\n<li><p>Public APIs should have inline documentation (<code>///</code>), so that the maintainer knows what it's meant to do, and consumers can find out how to use them correctly without consulting the source-code.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T13:08:03.393", "Id": "437143", "Score": "0", "body": "1) haha, the magic number is really magic. I picked it because I like primes, it's not configurable; I just thought it's nither to long nor too short :-P 2) oh, I sometimes make too many assumptions; I register this with Autofac as `SingleInstance` but you're right, making it `static` was pretty stupid of me 3) this is pure rocket-sciene ;-o I really had hoped that this library could do better than just be a dictionary with a timer :-\\ 4) oops, need to improve that; 5) oops, I didn't notice it was disposable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T13:09:59.137", "Id": "437145", "Score": "0", "body": "Could there really be a deadlock? The `Locker` allows only a single access at a time, doesn't it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T13:13:03.663", "Id": "437146", "Score": "3", "body": "@t3chb0t I don't see why there couldn't be a deadlock (but maybe I'm confused, I haven't got much sleep lately!): if `create` calls `GetOrCreateAsync`, then he's not going to get through." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T13:14:57.160", "Id": "437147", "Score": "1", "body": "crappy-crapp, you're absolutely right! o_O I feel so dumb :-]" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T12:47:39.250", "Id": "225189", "ParentId": "225187", "Score": "8" } }, { "body": "<p>You can simplify <code>GetOrCreateAsync()</code> a bit, because <code>IMemoryCache</code> has an extension called <code>Microsoft.Extensions.Caching.Memory.GetOrCreateAsync()</code>:</p>\n\n<pre><code>public async Task&lt;T&gt; GetOrCreateAsync&lt;T&gt;(object key, Func&lt;ICacheEntry, Task&lt;T&gt;&gt; create)\n{\n await Locker.WaitAsync();\n try\n {\n return await _cache.GetOrCreateAsync(key, create);\n }\n finally\n {\n Locker.Release();\n }\n}\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>public async Task&lt;T&gt; GetOrCreateAsync&lt;T&gt;(object key, Func&lt;Task&lt;T&gt;&gt; create)\n{\n await Locker.WaitAsync();\n try\n {\n return await _cache.GetOrCreateAsync(key, ice =&gt; {\n ice.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(17);\n return create();\n });\n }\n finally\n {\n Locker.Release();\n }\n}\n</code></pre>\n\n<p>if you want to control the expiration as in your original.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T13:49:41.513", "Id": "437150", "Score": "5", "body": "oh boy, me dumb**3 I probably should get some sleep ;-]" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T13:47:31.850", "Id": "225192", "ParentId": "225187", "Score": "7" } } ]
{ "AcceptedAnswerId": "225189", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T11:55:16.170", "Id": "225187", "Score": "7", "Tags": [ "c#", "thread-safety", "cache" ], "Title": "Wrapping IMemoryCache with SemaphoreSlim" }
225187
<p>I've done this parser to scrape all footwear data, but I don't know if it is good to use OOP in this case. Can you please check this out and give me the strongest feedback? I'm working on improving my coding style and looking for an opportunity to do coding better. How can I make this parser more maintainable for the future?</p> <pre><code>#!/usr/bin/env python3 # coding=utf-8 import re from datetime import datetime from bs4 import BeautifulSoup import http import requests import urllib.request html_hdrs = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (' 'KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'Accept-Encoding': 'none', 'Accept-Language': 'en-US,en;q=0.8', 'X-Requested-With': 'XMLHttpRequest', 'Connection': 'keep-alive'} def make_soup(input_url): try: req = urllib.request.Request(input_url, headers=html_hdrs) html = urllib.request.urlopen(req).read() except http.client.IncompleteRead as e: html = e.partial return BeautifulSoup(html, "html.parser") class Items(object): """Exporting all Matches Fashion website items to a list of soups""" def __init__(self): self._ul_tag = 'ul' self._li_tag = 'li' self._href_attr = 'href' self.main_url = 'https://www.matchesfashion.com' self._gender_urls = ('https://www.matchesfashion.com/intl/mens/shop/shoes', 'https://www.matchesfashion.com/intl/womens/shop/shoes', 'https://www.matchesfashion.com/intl/mens/sale/shoes', 'https://www.matchesfashion.com/intl/womens/sale/shoes') def _get_categories(self): category_box_class = 'filter__box__list' sale_category_box_class = 'innerFilterMobile catLevel3' out_categories = set() for gender in self._gender_urls: if '/sale' in gender: raw_page = make_soup(gender) raw_categories = raw_page.findAll(name=self._ul_tag, class_=sale_category_box_class) raw_categories = raw_categories[0].findAll(name=self._li_tag) for raw_category in raw_categories: out_categories.add('{}{}'.format(self.main_url, raw_category.a[self._href_attr])) else: raw_page = make_soup(gender) raw_categories = raw_page.findAll(name=self._ul_tag, class_=category_box_class) raw_categories = raw_categories[0].findAll(name=self._li_tag) for raw_category in raw_categories: out_categories.add('{}{}'.format(self.main_url, raw_category.a[self._href_attr])) self._category_urls = out_categories def _get_pages(self): pagination_class = 'redefine__right__pager' self._pages = list() def _paginate(input_url, input_num): out_url = '{}?page={}&amp;noOfRecordsPerPage=240&amp;sort='.format(input_url, input_num) return out_url for url in self._category_urls: page_soup = make_soup(url) last_page_num = page_soup.findAll(name=self._ul_tag, class_=pagination_class) if len(last_page_num) != 0: last_page_num = int(last_page_num[0].findAll(name=self._li_tag)[-3].text) for page_num in range(1, last_page_num+1): page_list_url = _paginate(url, page_num) self._pages.append(page_list_url) else: self._pages.append(url) def get(self): def get_gender(input_url): if '/womens/' in input_url: return 'women' elif '/mens/' in input_url: return 'men' def is_sale(input_url): if '/sale' in input_url: return True else: return False def get_category(input_url): if '?page=' in input_url: out_category = re.search(r'/shoes/(.*)(\?)', input_url).group(1) else: out_category = re.search(r'/shoes/(.*)', input_url).group(1) return out_category out_items = list() item_class = 'lister__item' self._get_categories() self._get_pages() for url in self._pages: gender = get_gender(url) category = get_category(url) sale = is_sale(url) url_soup = make_soup(url) url_soup = url_soup.findAll(name=self._li_tag, class_=item_class) for item_soup in url_soup: out_items.append((sale, gender, category, item_soup)) return out_items class Info(object): """Getting item info out of soup to an Info object""" def __init__(self, input_item): self._div_tag = 'div' self._strike_tag = 'strike' self._span_tag = 'span' self._li_tag = 'li' self._alt_attr = 'alt' self._pic_attr = 'data-original' self._href_attr = 'href' self._shop_name = 'Matches Fashion' self.sale, self.gender, self.category, self.item_soup = input_item def _get_raw_info(self): vendor_class = 'lister__item__title' self.title = self.item_soup.img[self._alt_attr] self.description = self.title self.model = self.title self.time = datetime.now(timezone('Europe/Moscow')).strftime('%Y-%m-%d %H:%M:%S') self.picture = 'https:{}'.format(self.item_soup.img[self._pic_attr]) self.url = 'https://www.matchesfashion.com{}'.format(self.item_soup.a[self._href_attr]) self.vendor = self.item_soup.findAll(name=self._div_tag, class_=vendor_class)[0].text self.shop = self._shop_name self.freeship = False def _get_prices(self): full_price_class = 'lister__item__price-full' new_price_class = 'lister__item__price-down' discount_class = 'lister__item__price-save' try: self.price = self.item_soup.findAll(name=self._span_tag, class_=full_price_class)[0].text self.oldprice = self.price self.discount = 0 except IndexError: self.price = self.item_soup.findAll(name=self._span_tag, class_=new_price_class)[0].text self.oldprice = self.item_soup.findAll(name=self._strike_tag)[0].text self.discount = self.item_soup.findAll(name=self._span_tag, class_=discount_class)[0].text def _get_sizes(self): no_stock_class = 'noStock' raw_sizes = self.item_soup.select("{}[class!={}]".format(self._li_tag, no_stock_class)) self.sizes = [] for raw_size in raw_sizes: size = raw_size.text self.sizes.append(size) if len(raw_sizes) != 0: size = raw_sizes[0].text if 'eu' in size.lower(): self.sizetype = 'eu' if 'us' in size.lower(): self.sizetype = 'us' if 'uk' in size.lower(): self.sizetype = 'uk' def get(self): self._get_raw_info() self._get_prices() self._get_sizes() raw_items = Items() items = raw_items.get() for item in items: info = Info(item) info.get() </code></pre> <p>This code is a bit raw, but the only thing that is left is the one more <code>class Process(object)</code> to process all data left.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T12:47:03.357", "Id": "437135", "Score": "0", "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**](https://CodeReview.StackExchange.com/q/2436) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T12:52:20.027", "Id": "437138", "Score": "0", "body": "@BCdotWEB Thanks! I've tried to change the title, but I'm more interested in a feedback and advises of how to make this code better to be readable and to maintain." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T12:53:57.897", "Id": "437139", "Score": "0", "body": "Such expectations belong in the body of your question, not your title. As I state in my comment: \"**the site standard**, which is for the title to simply state the task accomplished by the code\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T13:02:16.413", "Id": "437142", "Score": "0", "body": "Welcome to Code Review! What Python version did you write this for and why doesn't it seem like this code ever exports its data?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T13:09:24.510", "Id": "437144", "Score": "1", "body": "@Mast Thank you! it's Python 3.6 and it doesn't exports the data just because I haven't written the Process class yet. The data has to be processed before export. But the last lines of code creates objects with data inside." } ]
[ { "body": "<p>It looks very procedural at a glance, it might just not be useful to\nuse custom objects here. In any case you don't need to explicitly\ninherit from <code>object</code>, <code>class Process:</code> is fine already.</p>\n\n<p>So, more maintainable, well, the headers look dubious, but obviously\nchosen from a real-life browser. The character set / encoding values\nwould be the most concerning to me wrt. maintenance, but likely the\nencoding detection will take care of that. Similarly the <code>Connection</code>\nprobably doesn't belong there and should be handled by the HTTP client\ninstead (like most of them, except the user agent I suppose).</p>\n\n<p><code>_ul_tag</code>, <code>_li_tag</code>, <code>_href_attr</code> those are <em>way</em> unlikely to change.\nIf defined at all they should be global constants instead.</p>\n\n<p>The <code>_gender_urls</code> should be constructed from the <code>main_url</code>.</p>\n\n<p><code>_get_categories</code> has two almost identical blocks, better unify them\ninto a new method.</p>\n\n<p>I'd perhaps consider move all of the named classes etc. that might\nchange into constants at the start of the class or file so changing some\ndoesn't require having to look all over the file. Then again, minor\ncomplaint and perhaps not worth it if they're really only used once.\nGiving them good names is nice.</p>\n\n<p><code>_paginate</code> can just <code>return '...'.format(...)</code> instead of having the\nvariable? Goes for some more places in the code too. If the variable\nis only used once and the line is short enough, just inline them.</p>\n\n<p><code>get_gender</code> - what if neither is in the input?</p>\n\n<p><code>is_sale</code> can simply be <code>return '/sale' in input_url</code>.</p>\n\n<p><code>get_category</code> can be simplified for sure. Also the regex can be\nprecompiled with <code>compile</code> once and globally instead of every time the\nmethod runs. Also the two branches can be simplified into a single\nregex, look for \"non-greedy\" matching in the <code>re</code> documentation.</p>\n\n<p><code>_get_sizes</code> - the <code>append</code> bit could be a for comprehension,\n<code>self.sizes = [raw_size.text for raw_size in raw_sizes]</code>. For most\n(all?) objects <code>if len(x) != 0</code> will mean exactly the same as <code>if x:</code>,\nthough that might be a stylistic thing. Hmm and the whole\n<code>if ... in size.lower():</code> part, well firstly, what about if none of them\nmatch? Or more than one? Actually I'd suggest a loop here,\n<code>lower = size.lower(); for x in ['eu', 'us', 'uk']: if x in lower: self.sizetype = x</code>.</p>\n\n<p>You probably also want <code>if __name__ == '__main__': ...</code> at the bottom\ninstead of just running code whenever the file is loaded.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-23T12:45:25.183", "Id": "440665", "Score": "1", "body": "These are really useful to me, thanks! By the way, what do you think about using inheritance to create more parsers with other shops? I mean, what if I create new parser with such OOP style, but is it good to inherit these classes? Or it's better to create just the same ones? Or maybe it's a good idea to use OOP at all?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-23T15:49:05.700", "Id": "440713", "Score": "1", "body": "Right, well I can see that being useful if there's common functionality between different parsers. Do you think that will be the case for other shops? I imagine the structure might be too different. I'd first do one more then see if you can share code on the whole class level and if not extract helper functions etc. as you notice duplication or patterns occurring." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T22:51:13.247", "Id": "226603", "ParentId": "225188", "Score": "1" } } ]
{ "AcceptedAnswerId": "226603", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T12:44:08.243", "Id": "225188", "Score": "4", "Tags": [ "python", "python-3.x", "object-oriented", "parsing", "beautifulsoup" ], "Title": "Footwear scraper" }
225188
<p>This is a piece of a chess - engine which accomplishes the generation of all (yet unvalidated) moves given a legal board. However, I have the strong doubt this is well written. The following action are not yet included:</p> <ol> <li>Promoting</li> <li>Castling </li> <li>En passant.</li> </ol> <p>This code:</p> <pre><code>#include "chess.h" #include "odinutilities.h" #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; /* * Stores all moves given a pawns position,the pawns color, and a valid board position in move_info * Returns 0 if failed, otherwise 1. If a error occured, some valid moves might still be stored. * e.p not added yet. */ char store_all_moves_of_pawn(char copy_board[8][8], char from_x, char from_y, MOVE_DATA* move_info, char color) { const char dy = (color + 1) ? 1 : -1; const char to_y = from_y + dy; for (char m = -1; m &lt; 2; m++) { const char to_x = from_x + m; if ((to_x &lt; 0) | (to_x &gt; 7)) { continue; } if (m != 0) { //check if pawn can take left and right if (((to_y &gt;= 0) &amp; (to_y &lt;= 7)) &amp; (to_x &gt;= 0) &amp; (to_x &lt;= 7) &amp; ((copy_board[(int) to_y][(int) to_x] * color) &lt; 0)) { add_move_to_data(move_info, create_move_string(from_x, from_y, to_x, to_y, (char) 0)); } } else { //can pawn move forward if (copy_board[(int) to_y][(int) to_x] == 0) { add_move_to_data(move_info, create_move_string(from_x, from_y, to_x, to_y, (char) 0)); } } } return 1; } /* * Stores all moves given a rocks position, the rocks color, and a valid board position in move_info * Returns 0 if failed, otherwise 1. If a error occured, some valid moves might still be stored. */ char store_all_moves_of_knight(char copy_board[8][8], char from_x, char from_y, MOVE_DATA* move_info, char color) { char no_error = 1; char dx; char dy; char* p1 = &amp;dx; char* p2 = &amp;dy; //Compressed code using pointer arithmetic: for (char i = 0; i &lt; 2; i++) { for (*p1 = -2; *p1 &lt; 3; *p1 = *p1 + 4) { for (*p2 = -1; *p2 &lt; 2; *p2 = *p2 + 2) { char to_x = from_x + dx; char to_y = from_y + dy; if (0 &lt;= to_x &amp; to_x &lt; 8 &amp; 0 &lt;= to_y &amp; to_y &lt; 8) { no_error = add_move_if_unused_by_equal_color(copy_board, from_x, from_y, move_info, color, to_x, to_y); if (!no_error) return no_error; } } } p1 = &amp;dy; p2 = &amp;dx; } return no_error; } /* * Stores all moves given a rocks position, the rocks color, and a valid board position in move_info * Returns 0 if failed, otherwise 1. If a error occured, some valid moves might still be stored. */ char store_all_moves_of_rock(char copy_board[8][8], char from_x, char from_y, MOVE_DATA* move_info, char color) { //Vertikal //Up char no_error = 1; for (char dy = 1; from_y + dy &lt; 8; dy++) { char temp_field = copy_board[(int) from_y + dy][(int) from_x]; if (temp_field == 0) { no_error = add_move_to_data(move_info, create_move_string(from_x, from_y, from_x, from_y + dy, (char) 0)); if (!no_error) { return 0; } } else { if ((!color &amp; (temp_field &gt; 0)) || (color &amp; !(temp_field &gt; 0))) { no_error = add_move_to_data(move_info, create_move_string(from_x, from_y, from_x, from_y + dy, (char) 0)); } if (!no_error) { return 0; } break; } } //Down for (char dy = -1; from_y + dy &gt;= 0; dy--) { char temp_field = copy_board[(int) from_y + dy][(int) from_x]; if (temp_field == 0) { no_error = add_move_to_data(move_info, create_move_string(from_x, from_y, from_x, from_y + dy, (char) 0)); if (!no_error) { return 0; } } else { if ((!color &amp; (temp_field &gt; 0)) || (color &amp; !(temp_field &gt; 0))) { no_error = add_move_to_data(move_info, create_move_string(from_x, from_y, from_x, from_y + dy, (char) 0)); } if (!no_error) { return 0; } break; } } //Horizontal //Right for (char dx = 1; from_x + dx &lt; 8; dx++) { char temp_field = copy_board[(int) from_y][(int) from_x + dx]; if (temp_field == 0) { no_error = add_move_to_data(move_info, create_move_string(from_x, from_y, from_x + dx, from_y, (char) 0)); if (!no_error) { return 0; } } else { if ((!color &amp; (temp_field &gt; 0)) || (color &amp; !(temp_field &gt; 0))) { add_move_to_data(move_info, create_move_string(from_x, from_y, from_x + dx, from_y, (char) 0)); } if (!no_error) { return 0; } break; } } //Left for (char dx = -1; from_x + dx &gt;= 0; dx--) { char temp_field = copy_board[(int) from_y][(int) from_x + dx]; if (temp_field == 0) { no_error = add_move_to_data(move_info, create_move_string(from_x, from_y, from_x + dx, from_y, (char) 0)); if (!no_error) { return 0; } } else { if ((!color &amp; (temp_field &gt; 0)) || (color &amp; !(temp_field &gt; 0))) { no_error = add_move_to_data(move_info, create_move_string(from_x, from_y, from_x + dx, from_y, (char) 0)); } if (!no_error) { return 0; } break; } } return 1; } /* * Stores all moves given a bishops position, the bishops color, and a valid board position in move_info * Returns 0 if failed, otherwise 1. If a error occured, some valid moves might still be stored. */ char store_all_moves_of_bishop(char copy_board[8][8], char from_x, char from_y, MOVE_DATA* move_info, char color) { char no_error = generate_all_moves_of_bishops_direction(copy_board, from_x, from_y, move_info, color, -1, -1); if (!no_error) return no_error; no_error = generate_all_moves_of_bishops_direction(copy_board, from_x, from_y, move_info, color, -1, 1); if (!no_error) return no_error; no_error = generate_all_moves_of_bishops_direction(copy_board, from_x, from_y, move_info, color, 1, -1); if (!no_error) return no_error; no_error = generate_all_moves_of_bishops_direction(copy_board, from_x, from_y, move_info, color, 1, 1); return no_error; } /* * Stores all moves given a queens position, the queens color, and a valid board position in move_info * Returns 0 if failed, otherwise 1. If a error occured, some valid moves might still be stored. */ char store_all_moves_of_queen(char copy_board[8][8], char from_x, char from_y, MOVE_DATA* move_info, char color) { char no_error = store_all_moves_of_rock(copy_board, from_x, from_y, move_info, color); if (!no_error) return no_error; no_error = store_all_moves_of_bishop(copy_board, from_x, from_y, move_info, color); return no_error; } /* * Stores all moves given a queens position, the queens color, and a valid board position in move_info * Returns 0 if failed, otherwise 1. If a error occured, some valid moves might still be stored. */ char store_all_moves_of_king(char copy_board[8][8], char from_x, char from_y, MOVE_DATA* move_info, char color) { char no_error; for (int i = -1; i &lt; 2; i++) { for (int k = -1; k &lt; 2; k++) { char to_x = from_x + k; char to_y = from_y + i; if (0 &lt;= to_x &amp; to_x &lt; 8 &amp; 0 &lt;= to_y &amp; to_y &lt; 8) { no_error = add_move_if_unused_by_equal_color(copy_board, from_x, from_y, move_info, color, to_x, to_y); if (!no_error) return no_error; } } } return 1; } /* * Returns all moves given a Board-State, including a legal board position. For illegal positions the * behaviour is undefined. However, it is allowed to pass a position, where the color to move is checked. */ MOVE_DATA return_all_moves(BOARD_STATE* plegal_board_state, char ignore_check) { MOVE_DATA move_data; move_data.array_size = MOVE_ARRAY_SIZE_BY_INIT; move_data.used_array_size = 0; move_data.moves = (char**) malloc(move_data.array_size * sizeof(char*)); char copy_board[8][8]; memcpy(copy_board, (plegal_board_state-&gt;board), sizeof(copy_board)); for (int i = 0; i &lt; BOARD_LEN; i++) { for (int k = 0; k &lt; BOARD_LEN; k++) { char piece = copy_board[i][k]; char color = piece &gt; 0 ? 1 : -1; if (color != plegal_board_state-&gt;to_move) { continue; } switch (piece * color) { char c; case free_piece: continue; case pawn: c = store_all_moves_of_pawn(copy_board, k, i, &amp;move_data, color); if (!c) { perror("OutOfMemoryException."); exit(EXIT_FAILURE); } continue; case knight: c = store_all_moves_of_knight(copy_board, k, i, &amp;move_data, color); if (!c) { perror("OutOfMemoryException."); exit(EXIT_FAILURE); } continue; case bishop: c = store_all_moves_of_bishop(copy_board, k, i, &amp;move_data, color); if (!c) { perror("OutOfMemoryException."); exit(EXIT_FAILURE); } continue; case rock: ; //this is an empty statement since a label is not allowed before a declaration c = store_all_moves_of_rock(copy_board, k, i, &amp;move_data, color); if (!c) { perror("OutOfMemoryException."); exit(EXIT_FAILURE); } continue; case queen: c = store_all_moves_of_queen(copy_board, k, i, &amp;move_data, color); if (!c) { perror("OutOfMemoryException."); exit(EXIT_FAILURE); } continue; case king: c = store_all_moves_of_king(copy_board, k, i, &amp;move_data, color); if (!c) { perror("OutOfMemoryException."); exit(EXIT_FAILURE); } continue; default: fprintf(stderr, "Unknown piece: %c on the board\nError.", piece); exit(EXIT_FAILURE); } } } return move_data; } /*Merges to_be_added into to dest. * If successful, to_be_added moves will be freed. * Returns 1, if successful * Returns 0, OutOfMemoryException */ char merge(MOVE_DATA* dest, MOVE_DATA* to_be_merged) { void* c; if (dest-&gt;array_size &lt; dest-&gt;used_array_size + to_be_merged-&gt;used_array_size) { c = realloc(dest-&gt;moves, (dest-&gt;used_array_size + to_be_merged-&gt;used_array_size) * sizeof(char*)); if (!c) { return 0; } else { dest-&gt;moves = (char**) c; } dest-&gt;array_size = dest-&gt;used_array_size + to_be_merged-&gt;used_array_size; } c = memcpy((dest-&gt;moves) + dest-&gt;used_array_size, to_be_merged-&gt;moves, to_be_merged-&gt;used_array_size); if (!c) { return 0; } return 1; } /* Adds a move string to a MOVE_DATA * If there is no more space left, space of the MOVE_DATA will be doubled. * Returns 1, if successful * Returns 0, OutOfMemoryException */ char add_move_to_data(MOVE_DATA* move_info, char* move) { if (move_info-&gt;array_size == move_info-&gt;used_array_size) { char** p = realloc(move_info-&gt;moves, 2 * (move_info-&gt;array_size) * sizeof(char*)); move_info-&gt;array_size = 2 * (move_info-&gt;array_size); if (!p) { return 0; } else { move_info-&gt;moves = (char**) p; } } move_info-&gt;moves[move_info-&gt;used_array_size++] = move; return 1; } char generate_all_moves_of_bishops_direction(char copy_board[8][8], char from_x, char from_y, MOVE_DATA* move_info, char color, char dhorizontal, char dvertical) { char n = 1; char to_x; char to_y; char no_error = 1; while (((to_x = dhorizontal * n + from_x) &lt; 8 &amp; (to_x &gt;= 0)) &amp; (((to_y = dvertical * n + from_y) &lt; 8) &amp; (to_y &gt;= 0))) { if (copy_board[(int) to_y][(int) to_x] == 0) { no_error = add_move_to_data(move_info, create_move_string(from_x, from_y, to_x, to_y, (char) 0)); } else { if (color * copy_board[(int) to_y][(int) to_x] &lt; 0) { no_error = add_move_to_data(move_info, create_move_string(from_x, from_y, to_x, to_y, (char) 0)); } break; } n++; } return no_error; } //Returns 1 if successful, else 0 /* * NOTE THIS FUNCTION IS NOT CHECKING IF THE MOVE IS LEGAL. IT IS ONLY LOOKING IF THE FIELD IS USED BY ANOTHER * PIECE OF EQUAL COLOR AND THEN ADDS THE MOVE OR NOT. IN BOTH CASES 1 WILL BE RETURNED. */ char add_move_if_unused_by_equal_color(char copy_board[8][8], char from_x, char from_y, MOVE_DATA* move_info, char color, char to_x, char to_y) { if (copy_board[to_y][to_x] * color &lt;= 0) { char no_error = add_move_to_data(move_info, create_move_string(from_x, from_y, to_x, to_y, (char) 0)); return no_error; } return 1; } </code></pre> <p>This is the header-file:</p> <pre><code>#ifndef BOARD_H #define BOARD_H #define BOARD_LEN 8 #define MOVE_ARRAY_SIZE_BY_INIT 20 #include &lt;stdlib.h&gt; typedef struct { char board[8][8]; char to_move; char pieces_moved[6]; } BOARD_STATE; typedef struct { char** moves; size_t array_size; size_t used_array_size; } MOVE_DATA; char** return_all_moves(BOARD_STATE* pstate); MOVE_DATA return_all_legal_moves(BOARD_STATE* pstate, char ignore_check); char board_is_legal(BOARD_STATE* pstate); char store_all_moves_of_pawn(char copy_board[8][8], char from_x, char from_y, MOVE_DATA* move_info, char color); char store_all_moves_of_bishop(char copy_board[8][8], char from_x, char from_y, MOVE_DATA* move_info, char color); char store_all_moves_of_rock(char copy_board[8][8], char from_x, char from_y, MOVE_DATA* move_info, char color); char store_all_moves_of_queen(char copy_board[8][8], char from_x, char from_y, MOVE_DATA* move_info, char color); char store_all_moves_of_king(char copy_board[8][8], char from_x, char from_y, MOVE_DATA* move_info, char color); char add_move_to_data(MOVE_DATA* move_info, char* move); char merge(MOVE_DATA* dest, MOVE_DATA* to_be_merged); char generate_all_moves_of_bishops_direction(char copy_board[8][8], char from_x, char from_y, MOVE_DATA* move_info, char color, char dhorizontal, char dvertical); char add_move_if_unused_by_equal_color(char copy_board[8][8], char from_x, char from_y, MOVE_DATA* move_info, char color, char to_x, char to_y); #endif </code></pre> <ol> <li>I am searching for a general advice for a better desgin of the engine. </li> <li>I am not looking for any optimizations yet.</li> <li>I would also love your comments about readability.</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T04:48:20.463", "Id": "437233", "Score": "1", "body": "You have a lot of [primitive obsession](https://refactoring.guru/smells/primitive-obsession). Make a lot more data types, and replace all these raw types being passed around everywhere. I see a dire need for at least `Board`, `Point`, `TeamColor` (an enum, iffy on the name), and possibly quite a few more." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T07:39:32.877", "Id": "437259", "Score": "1", "body": "\"which accomplishes the generation of all (yet unvalidated) moves\" That's a lot of moves. Did you mean all moves possible in one turn instead?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T14:59:57.423", "Id": "437327", "Score": "1", "body": "It's not enough for an answer, but I think you copied and pasted your comment from the rook function on to the knight one and forgot to change 'rook' to 'knight'." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T12:46:44.360", "Id": "437521", "Score": "0", "body": "@Mast Yes, I thought this was kinda obvious. I will change it :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T12:47:06.270", "Id": "437522", "Score": "0", "body": "@JohnGowers Exactly, thanky you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T12:48:00.127", "Id": "437524", "Score": "0", "body": "@Alexander Could you further explain the phenomenon? What you would do exactly? I fear that structure hugely slow down the computation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T15:05:44.843", "Id": "437556", "Score": "0", "body": "@TVSuchty First let me introduce some terminology. \"Strong\" types are types whose set of \"valid\" values (in the business sense) are as close to the set of possible values. For example, using a `bool` to model `true` and `false` makes it very strong type. All of it possible values are legal. On the other hand, using a string, `int`, or `char` to model a boolean (as `\"true\"`/`\"false\"`, `1`/`0`, `'t'`/`'f'`) would make them very weak types. Because what happens if you have `\"foo\"`, `2`, `'Z'`? As far as C is concerned, all those are valid strings/ints/chars, respectively. But if your logic is..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T15:07:52.480", "Id": "437557", "Score": "0", "body": "...relying on them to model bools, and each type has only 2 valid values, then you have a lot of *possible* but *logically illegal* values. That's an opportunity for a bug. Now everywhere you use (for example), a char to model a boolean, you need to ensure that the char is only `t`, `f` or otherwise handle the error case when it's something else. If you used a strong type (boolean, in this example), *the error case is simply not possible*, so there's no validation necessary. If anything this *speeds* things up (less checks = less branches)..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T15:10:18.707", "Id": "437559", "Score": "0", "body": "... It also means you can't forget to check for illegal values (as there are none), which reduces bugs. In your example, you're using `char` to model the state of squares on the board, rather than something like an `enum SquareColor`. Furthermore, your use of separate x/y params (like `char from_x, char from_y`) is not only annoying (more typing), it's also more error prone. Everytim you want to forward that point to another function call, you have to fill in both `from_x` and `from_y`. If you copy/paste, you might accidentally paste `from_x` twice, causing a frustrating to debug logic error." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T15:10:23.593", "Id": "437560", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/96916/discussion-between-alexander-and-tvsuchty)." } ]
[ { "body": "<h2><code>return</code> type</h2>\n\n<p><code>char</code> should only be user for characters, as it's name says. <code>unsigned char</code> for characters or for aliasing other types. For everything else, use anything else.</p>\n\n<p>If you want <code>(u)int8_t</code>, use <code>&lt;stdint.h&gt;</code>, and if you don't have that header, feel free to write your own <code>typedef</code> (enclosed in an <code>#if</code>).</p>\n\n<p>But for error codes, the best is to use good old <code>int</code>. Everybody uses <code>int</code> for error codes, so you won't mess with their brains when they wonder why you did use <code>char</code> :)</p>\n\n<hr>\n\n<h2>Function return values and names (source: <a href=\"https://www.kernel.org/doc/html/v4.10/process/coding-style.html#function-return-values-and-names\" rel=\"nofollow noreferrer\">Linux Kernel Coding Style</a>)</h2>\n\n<p>Functions can return values of many different kinds, and one of the most common is a value indicating whether the function succeeded or failed. Such a value can be represented as an error-code integer (-Exxx = failure, 0 = success) or a succeeded boolean (0 = failure, non-zero = success).</p>\n\n<p>Mixing up these two sorts of representations is a fertile source of difficult-to-find bugs. If the C language included a strong distinction between integers and booleans then the compiler would find these mistakes for us... but it doesn’t. To help prevent such bugs, always follow this convention:</p>\n\n<pre><code>If the name of a function is an action or an\n imperative command, the function should\n return an error-code integer. If the name is a\n predicate, the function should return a\n \"succeeded\" boolean. \n</code></pre>\n\n<p>For example, <code>add work</code> is a command, and the <code>add_work()</code> function returns 0 for success or <code>-EBUSY</code> for failure. In the same way, <code>PCI device present</code> is a predicate, and the <code>pci_dev_present()</code> function returns <code>true</code> if it succeeds in finding a matching device or <code>false</code> if it doesn’t.</p>\n\n<hr>\n\n<h2><code>no_error</code></h2>\n\n<p>The variable <code>no_error</code> is misleading: it can hold an error code. Probably the origin of the name was the inverted error return codes. With non-zero error codes better names are: <code>error</code> or <code>status</code>.</p>\n\n<hr>\n\n<h2><code>copy_board</code></h2>\n\n<p>The name of the parameter <code>copy_board</code> is misleading, given that it's not a copy, but a pointer to the original board.</p>\n\n<hr>\n\n<h2>function names short</h2>\n\n<p>For making function names shorter, you can omit prepositions in them (when they are obvious). For example, <code>store_all_moves_of_pawn()</code> -> <code>store_moves_pawn()</code></p>\n\n<hr>\n\n<h2><code>#pragma once</code></h2>\n\n<p>Although it has its own problems (only if your build configuration is completely broken, actually), it is less error-prone than typical <code>#ifndef</code>&amp;<code>#define</code> include guards.</p>\n\n<p>It's not standard, but most compilers accept it.</p>\n\n<p>Just write this line at the beginning of the header:</p>\n\n<pre><code>#pragma once\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/q/1143936/6872717\">#pragma once vs include guards</a></p>\n\n<hr>\n\n<h2>Names and Order of Includes (source: <a href=\"https://google.github.io/styleguide/cppguide.html#Names_and_Order_of_Includes\" rel=\"nofollow noreferrer\">Google C++ Style Guide</a>)</h2>\n\n<p>Use standard order for readability and to avoid hidden dependencies: Related header, C library, C++ library, other libraries' .h, your project's .h.</p>\n\n<p>All of a project's header files should be listed as descendants of the project's source directory without use of UNIX directory shortcuts <code>.</code> (the current directory) or <code>..</code> (the parent directory). For example, <code>google-awesome-project/src/base/logging.h</code> should be included as:</p>\n\n<pre><code>#include \"base/logging.h\" \n</code></pre>\n\n<p>In <code>dir/foo.cc</code> or <code>dir/foo_test.cc</code>, whose main purpose is to implement or test the stuff in <code>dir2/foo2.h</code>, order your includes as follows:</p>\n\n<p>dir2/foo2.h.</p>\n\n<p>A blank line</p>\n\n<p>C system files.</p>\n\n<p>C++ system files.</p>\n\n<p>A blank line</p>\n\n<p>Other libraries' .h files.</p>\n\n<p>Your project's .h files.</p>\n\n<p>Note that any adjacent blank lines should be collapsed.</p>\n\n<p>With the preferred ordering, if <code>dir2/foo2.h</code> omits any necessary includes, the build of <code>dir/foo.cc</code> or <code>dir/foo_test.cc</code> will break. Thus, this rule ensures that build breaks show up first for the people working on these files, not for innocent people in other packages.</p>\n\n<p><code>dir/foo.cc</code> and <code>dir2/foo2.h</code> are usually in the same directory (e.g. <code>base/basictypes_test.cc</code> and <code>base/basictypes.h</code>), but may sometimes be in different directories too.</p>\n\n<p>Within each section the includes should be ordered alphabetically.</p>\n\n<ul>\n<li>In your case this would mean this order of includes:</li>\n</ul>\n\n<pre><code>#include \"chess.h\"\n\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n\n#include \"odinutilities.h\"\n</code></pre>\n\n<hr>\n\n<h2>unnecessary casts</h2>\n\n<p>Most (if not all) the casts you use are unnecessary. Casts usually lead to bugs, remove them all if there's not a good reason for them to be.</p>\n\n<hr>\n\n<h2><code>ptrdiff_t</code></h2>\n\n<p>The proper type for pointer arithmetics is <code>ptrdiff_t</code>, not <code>char</code> nor <code>int</code>.</p>\n\n<p>Variables such as <code>to_y</code> should be declared of this type.</p>\n\n<p>You will need <code>#include &lt;stddef.h&gt;</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T14:00:31.853", "Id": "437152", "Score": "0", "body": "Hey! Thanks for your answer!\nI thought a processor will need less time adding chars instead of integers? Is this true?\nIf I typedef it, would not I use char anyway just by an alias?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T14:04:57.997", "Id": "437155", "Score": "0", "body": "@TVSuchty No, it isn't true (unless you have an 8-bit processor ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T14:07:17.627", "Id": "437156", "Score": "0", "body": "@TVSuchty If you did the typedef, you would be using `char`. Actually even if not, because `<stdint.h>` actually does the same `typedef`. But the main problem is not with `char` but with readability (there's another problem with `char`, which isn't guaranteed to be `signed`, but it's not important in this case)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T14:07:25.570", "Id": "437157", "Score": "0", "body": "Guess, I have not :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T14:08:10.650", "Id": "437158", "Score": "1", "body": "@TVSuchty In C the `int` and `unsigned int` type will usually be the word size of the processor so all the native operations for the processor will run faster with int. char and short might be used in arrays where memory is tight." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T14:17:14.900", "Id": "437159", "Score": "0", "body": "@pacmaninbw Still, I would advise against `int` if speed is a concern: in 64 bit processors `int` is still 32 bits (usually). Better use explicit `(u)int_fastN_t` types from `<stdint.h>` for that purpose. However, for error codes, `int` will probably be as fast as possible, and very clear." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T14:34:12.210", "Id": "437162", "Score": "0", "body": "#pragma once - It isn't part of the standard, I prefer the #ifndef FILE_MACRO.which will always work and makes it more portable. Why do you think it is safer?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T14:37:07.583", "Id": "437163", "Score": "1", "body": "@pacmaninbw That's why I put the link. But if the compiler accepts it (most of them, since a decade ago), it's very valid. And when you forget to change the FILE_MACRO_H name after copy&paste (it happened to me more than once), it's a pain in the ass until you find it. #pragma doesn't have that problem. The link provides all this info and discussion, and anyone is of course free to use whatever, and I just pointed to the info just in case he didn't know :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T15:02:34.777", "Id": "437165", "Score": "0", "body": "Hey, thanks for the effort you put in!!!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T15:19:12.483", "Id": "437166", "Score": "0", "body": "@CacahueteFrito It might be better to create your answers in a text editor on your computer and then post it when the answer is complete rather than all the edits. That is what I do." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T04:51:33.913", "Id": "437234", "Score": "3", "body": "This is totally bike shedding, but I disagree on the suggestion to change `store_all_moves_of_pawn()` to `store_moves_pawn()`. Perhaps `store_pawn_moves()` is fine, but my personal fave is `store_all_pawn_moves`. I would recommend a more expressive approach. Keystrokes are free, and monitors are giant, there's really no need to be pinched on character count." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T13:56:45.673", "Id": "225193", "ParentId": "225191", "Score": "10" } }, { "body": "<p>First, interesting code!</p>\n\n<p>I agree with most of what @CacahueteFrito wrote in his review except for the <code>#pragma once</code> item. The method you are using is more portable. I sometimes use <code>#pragma once</code> when the editor defaults to it on windows (Visual Studio), but not for C++.</p>\n\n<p>I will primarily address style.</p>\n\n<p><strong>Code Consistency</strong><br>\nThe code is consistently indented, which is great, but the use of braces (<code>{</code> and <code>}</code>) in if statements is inconsistent. There are many places where braces are used around a single statement, but there are many places where braces aren't used around a single statement. It is more readable and maintainable when the code is consistent. Braces around a single statement are a good practice because quite often a new line of code needs to be inserted during maintenance.</p>\n\n<p><strong>Always Test the Return Value of Memory Allocation Functions</strong><br>\nIn most of the cases where memory is allocated the code is testing the return value, however, in the function <code>MOVE_DATA return_all_moves(BOARD_STATE* plegal_board_state, char ignore_check)</code> there is a call to <code>malloc(size_t size)</code> that is not tested. The function <code>malloc()</code> may also return NULL if there is not enough memory.</p>\n\n<p>It might be better if the code was </p>\n\n<pre><code>char **tmp = malloc(move_data.array_size * sizeof(*p));\nif (tmp) {\n move_data.moves = tmp;\n}\nelse {\n // needs to be defined\n}\n</code></pre>\n\n<p>because only the type of tmp needs to change if the type of <code>move_data.moves</code> is changed. This would be true for all the memory allocation performed in the program.</p>\n\n<p><strong>Casting Malloc</strong><br>\nIn modern C the functions <code>malloc()</code>, <code>calloc()</code> and <code>realloc()</code> return <code>void *</code>. It is not necessary to cast the memory returned by these statement to the proper type.</p>\n\n<p><strong>Readability</strong><br>\nThe code would be easier to read if there were some blank lines between blocks of code, such as after variable declarations at the top of the function, after a <code>if then else</code> block, after each of the cases in the switch statement.</p>\n\n<p><strong>Function Complexity</strong><br>\nThe function <code>char store_all_moves_of_rock(char copy_board[8][8], char from_x, char from_y, MOVE_DATA* move_info, char color)</code> is very complex and could be broken up into at least 4 sub functions, <code>up</code>, <code>down</code>, <code>left</code> and <code>right</code>. This function is probably misnamed, I believe is should be <code>all_moves_of_rook</code> rather than rock.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T15:38:09.943", "Id": "437172", "Score": "0", "body": "Hey, thank you for your critique! Glad you liked it. I will go for it!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T16:22:21.233", "Id": "437185", "Score": "0", "body": "Lol, I never noticed the difference between rock and rook. Thanks for educating me in English :P" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T23:10:24.030", "Id": "437213", "Score": "0", "body": "Just a note that on many 64 bit systems (at least Linux and Mac I think, not sure of Windows), with sane environment settings, any reasonable use of `malloc` will never return NULL. Program(s) will start being killed if system runs out of memory and swap. A reasonable program will not run out of its own 64 bit virtual address space. It's still good to check it of course, but it's not worth putting much effort into handling it gracefully (just `abort()` or something)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T00:46:23.637", "Id": "437216", "Score": "0", "body": "@hyde and if it is an embedded processor that doesn't have all that much memory?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T06:17:16.560", "Id": "437245", "Score": "1", "body": "@pacmaninbw In that case you should really consider if you want to use a real operating system (such as embedded Linux), and research how you can configure and control `malloc` behavior (such as make it return NULL reliably, if your application is such that you can actually do something useful about it)." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T15:26:45.577", "Id": "225205", "ParentId": "225191", "Score": "4" } } ]
{ "AcceptedAnswerId": "225193", "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T13:13:47.003", "Id": "225191", "Score": "10", "Tags": [ "c", "chess" ], "Title": "Piece of chess engine, which accomplishes move generation" }
225191
<p>I was wondering if anyone has any improvement ideas for my code. At the moment it is somewhat sluggish though it does work. This is my first project in VBA; I come from a background in PHP/Python.</p> <pre><code> Option Explicit Private Sub Workbook_Open() ' Set network folder path Const FolderPath As String = "\\JACKSONVILLE-DC\Common\SOP's for JV\SOPs Final" ' Set local folder path 'Const FolderPath As String = "C:\Users\jbishop\Desktop\SOP Audit Excel Prototype\SOPs" ' Set allowed file type(s) Const FileExt As String = "docx" ' Instantiate FSO Dim oFSO As Object Dim oFolder As Object Dim oFiles As Object Dim oFile As Object Set oFSO = CreateObject("Scripting.FileSystemObject") Set oFolder = oFSO.GetFolder(FolderPath) Set oFiles = oFolder.Files Dim v As Variant Dim iSheet As Long ' Clear Worksheets Dim ws As Worksheet For Each ws In ThisWorkbook.Worksheets ws.Cells.ClearContents ws.Cells.Interior.Color = xlNone ws.Range("A1").Value = "SOP ID" ws.Range("B1").Value = "DEPT" ws.Range("C1").Value = "SOP TITLE" ws.Range("D1").Value = "LANG" ws.Range("E1").Value = "JAN" ws.Range("F1").Value = "FEB" ws.Range("G1").Value = "MAR" ws.Range("H1").Value = "APR" ws.Range("I1").Value = "MAY" ws.Range("J1").Value = "JUN" ws.Range("K1").Value = "JUL" ws.Range("L1").Value = "AUG" ws.Range("M1").Value = "SEP" ws.Range("N1").Value = "OCT" ws.Range("O1").Value = "NOV" ws.Range("P1").Value = "DEC" ws.Range("A1:P1").Font.Color = vbBlack ws.Range("A1:P1").Font.Bold = True ws.Range("A1:P1").Font.Underline = False Next ws 'Loop through each file in FSO For Each oFile In oFiles If LCase(Right(oFile.Name, 4)) = FileExt Then 'Split filename v = Split(oFile.Name, "-") 'MsgBox (v(3)) 'Exit Sub 'Use dept code as Select variable Select Case v(3) Case "PNT", "VLG", "SAW" Call pvtPutOnSheet(oFile.Path, 1, v) Case "CRT", "AST", "SHP", "SAW" Call pvtPutOnSheet(oFile.Path, 2, v) Case "CRT", "STW", "CHL", "ALG", "ALW", "ALF", "RTE", "AFB", "SAW" Call pvtPutOnSheet(oFile.Path, 3, v) Case "SCR", "THR", "WSH", "GLW", "PTR", "SAW" Call pvtPutOnSheet(oFile.Path, 4, v) Case "PLB", "SAW" Call pvtPutOnSheet(oFile.Path, 5, v) Case "DES" Call pvtPutOnSheet(oFile.Path, 6, v) Case "AMS" Call pvtPutOnSheet(oFile.Path, 7, v) Case "EST" Call pvtPutOnSheet(oFile.Path, 8, v) Case "PCT" Call pvtPutOnSheet(oFile.Path, 9, v) Case "PUR", "INV" Call pvtPutOnSheet(oFile.Path, 10, v) Case "SAF" Call pvtPutOnSheet(oFile.Path, 11, v) Case "GEN" Call pvtPutOnSheet(oFile.Path, 12, v) End Select End If Next oFile 'Call Sub Procedure that will cross check SOPs with SOP audits Call chkAuditDates End Sub Private Sub chkAuditDates() 'Set path to audits (NETWORK) Const FolderPath As String = "\\JACKSONVILLE-DC\Common\SOP's for JV\SOP Audits\2019" 'Set path to audits (LOCAL) 'Const FolderPath As String = "C:\Users\jbishop\Desktop\SOP Audits with New Names" 'Instantiate the FSO &amp; related vars Dim oFSO As Object: Set oFSO = CreateObject("Scripting.FileSystemObject") Dim oFolder As Object: Set oFolder = oFSO.GetFolder(FolderPath) Dim oFiles As Object: Set oFiles = oFolder.Files Dim oFile As Object Dim i As Integer 'Loop through all worksheets - NEED TO ESTABLISH LOOP/CURRENTLY SET TO ONE SHEET For i = 1 To 4 With Worksheets(i) 'Set cell background color to Red for a range of cells With Range("E1:P" &amp; .Cells(.Rows.Count, 1).End(xlUp).Row) '.Interior.Color = RGB(255, 0, 0) .HorizontalAlignment = xlCenter .Font.Color = vbBlack .Font.Bold = True End With 'Store cells in COL A that have values as a range Dim SOPID As Range: Set SOPID = .Range("A1", .Range("A" &amp; .Rows.Count).End(xlUp)) Dim cel As Range 'Loop through each SOP audit file For Each oFile In oFiles 'Strip audit date out of filename and trim off the file extension Dim auditDate: auditDate = CDate(DateSerial(Right(Left(Split(oFile.Name, "-")(3), 8), 4), _ Left(Left(Split(oFile.Name, "-")(3), 8), 2), _ Mid(Left(Split(oFile.Name, "-")(3), 8), 3, 2))) 'Loop through all SOP IDs stored in COL A For Each cel In SOPID 'See if SOP ID in COL A matches SOP ID in Audit file name If Trim(RemoveLeadingZeroes(Split(oFile.Name, "-")(2))) = Trim(cel) Then 'Insert link to audit, change background color, etc of selected cell With cel.Offset(0, 3 + Month(auditDate)) .Hyperlinks.Add Anchor:=cel.Offset(0, 3 + Month(auditDate)), Address:=oFile.Path, TextToDisplay:="X" .Interior.Color = RGB(34, 139, 34) .Font.Color = vbBlack .Font.Bold = True End With End If Next cel Next oFile 'Autosize columns to best fit inserted data .Columns("A:P").AutoFit End With Next i End Sub Private Sub pvtPutOnSheet(sPath As String, i As Long, v As Variant) Dim r As Range With Worksheets(i) Set r = .Cells(.Rows.Count, 1).End(xlUp) If Len(r.Value) &gt; 0 Then Set r = r.Offset(1, 0) ' next empty cell in Col A If UBound(v) &gt; 3 Then r.Value = v(2) ' Col A = "001" r.Offset(0, 1).Value = v(3) ' Col B = "CHL" 'Create hyperlink in each cell .Hyperlinks.Add Anchor:=r.Offset(0, 2), Address:=sPath, TextToDisplay:=v(4) ' Col C = "Letter Lock for Channel Letters" with link to Path r.Offset(0, 3).Value = Left(v(5), 2) ' Col = "EN" End If End With End Sub Function RemoveLeadingZeroes(ByVal str) Dim tempStr tempStr = str While Left(tempStr, 1) = "0" And tempStr &lt;&gt; "" tempStr = Right(tempStr, Len(tempStr) - 1) Wend RemoveLeadingZeroes = tempStr End Function </code></pre> <p>The filenames look like this:</p> <ul> <li>SOP_Audit-JV-001-05152019</li> <li>SOP-JV-001-CHL-Letter Lock for Channel Letters-EN</li> </ul> <p>Any input is much appreciated. Thank you everyone.</p>
[]
[ { "body": "<p>Many areas to comment here.</p>\n\n<p>Well done on including <code>Option Explicit</code> and good indenting!</p>\n\n<p>I have identified some key themes:</p>\n\n<ul>\n<li>Avoiding repetition</li>\n<li>Avoid magic numbers</li>\n<li>Meaningful variable names</li>\n<li>Avoid switching between Excel and VBA unless really necessary</li>\n<li>Properly qualify calls to Excel objects</li>\n</ul>\n\n<h2>Avoiding repetition</h2>\n\n<p>While there is not a lot of obvious repetition, avoiding it as much as possible makes maintenance easier. A significant example here is in your <code>Select</code> statement:</p>\n\n<pre><code> Case \"PNT\", \"VLG\", \"SAW\"\n Call pvtPutOnSheet(oFile.Path, 1, v)\n</code></pre>\n\n<p>This has multiple sins:</p>\n\n<ul>\n<li>the same call is repeated 12 times</li>\n<li>the call uses magic numbers</li>\n<li>the call uses a variable which is not clear what it does (<code>v</code>)</li>\n</ul>\n\n<p>A way around it is:</p>\n\n<pre><code>Select Case fileNameParts(3)\n Case \"PNT\", \"VLG\", \"SAW\"\n relevantSheet = 1\n' [. . . ]\nEnd Case\nPutOnSheet oFile.Path, relevantSheet, fileNameParts '&lt;-- proper VBA syntax for calling a routine\n</code></pre>\n\n<h2>Avoid magic numbers</h2>\n\n<p>'Magic Numbers' make life harder when returning to code, or if someone else looks at your code. Why do you have '1'? what does '13' mean? What if your filename syntax changes, and you need <code>v(4)</code> instead of <code>v(3)</code>?</p>\n\n<p>In one of my code projects, I have set a module aside (imaginatively called 'MagicNumbers') in which I declare all magic numbers as <code>Public Const</code>. While they may not need to be public (your file path <code>Const</code> is an example here), putting them in once place makes management easier - and makes retiring them easier when you modify your code.</p>\n\n<p>I also use a convention, all Constants are in UPPERCASE, and have meaningful names so the code is self-commenting.</p>\n\n<pre><code>Public Const FINALFILEPATH As String = \"\\\\JACKSONVILLE-DC\\Common\\SOP's for JV\\SOPs Final\"\n</code></pre>\n\n<p>(and an example of use)</p>\n\n<pre><code>Set oFolder = oFSO.GetFolder(FINALFILEPATH)\n</code></pre>\n\n<h2>Meaningful variable names</h2>\n\n<p>You will come back in 3 months and have to work out what <code>v</code>, <code>i</code>, <code>iSheet</code>, <code>r</code>, <code>cel</code>, <code>sPath</code>, <code>SOPID</code> really represent. In this day and age, storage is cheap so using meaningful names makes your life a lot easier.</p>\n\n<ul>\n<li><code>v</code> is an array of <code>fileNameParts</code></li>\n<li><code>i</code> has been used both as an <code>iterator</code> and a <code>relevantWorkSheet</code></li>\n<li><code>iSheet</code> is not a bedcovering sold by Apple, but is also not used in\nthe code</li>\n<li><code>r</code> is the <code>lastCell</code>, but what you are really interesting in is\n<code>nextEmptyCell</code></li>\n<li><code>sPath</code> is <code>filePath</code></li>\n</ul>\n\n<p>And your functions and routines should also be well named. <code>pvtPutOnSheet</code> is really <code>PutOnSheet</code> - no need for a funky Hungarian notation.</p>\n\n<h2>Avoid switching</h2>\n\n<p>Do as much as possible in the VBA environment. Use arrays instead of dealing directly with Excel range values.</p>\n\n<pre><code>For Each ws In ThisWorkbook.Worksheets\n ws.Cells.ClearContents\n ws.Cells.Interior.Color = xlNone\n ws.Range(\"A1\").Value = \"SOP ID\"\n ws.Range(\"B1\").Value = \"DEPT\"\n ws.Range(\"C1\").Value = \"SOP TITLE\"\n ws.Range(\"D1\").Value = \"LANG\"\n ws.Range(\"E1\").Value = \"JAN\"\n ws.Range(\"F1\").Value = \"FEB\"\n ws.Range(\"G1\").Value = \"MAR\"\n ws.Range(\"H1\").Value = \"APR\"\n ws.Range(\"I1\").Value = \"MAY\"\n ws.Range(\"J1\").Value = \"JUN\"\n ws.Range(\"K1\").Value = \"JUL\"\n ws.Range(\"L1\").Value = \"AUG\"\n ws.Range(\"M1\").Value = \"SEP\"\n ws.Range(\"N1\").Value = \"OCT\"\n ws.Range(\"O1\").Value = \"NOV\"\n ws.Range(\"P1\").Value = \"DEC\"\n ws.Range(\"A1:P1\").Font.Color = vbBlack\n ws.Range(\"A1:P1\").Font.Bold = True\n ws.Range(\"A1:P1\").Font.Underline = False\nNext ws\n</code></pre>\n\n<p>Can become:</p>\n\n<pre><code>Dim headings as Variant\nheadings = Array(\"SOP ID\", \"Dept\", \"SOP Title\", \"...\") '&lt;--- etc, you get the idea\nFor Each ws In ThisWorkbook.Worksheets\n ws.Cells.ClearContents\n ws.Cells.Interior.Color = xlNone\n With ws.Range(\"A1:P1\") ' Magic number Const HEADINGRANGE as String = \"A1:P1\"\n .Value = headings '&lt;-- touch Excel once here instead of 16 times.\n .Font.Color = vbBlack\n .Font.Bold = True\n .Font.Underline = False\n End With\nNext ws\n</code></pre>\n\n<h2>Properly qualify calls</h2>\n\n<p>You have a mixture of well qualified calls (ensuring correct behaviour) and unqualified calls (random behaviour depending on active and selected sheets).</p>\n\n<p>The following is an easy omission to make:</p>\n\n<pre><code> With Worksheets(i)\n 'Set cell background color to Red for a range of cells\n With Range(\"E1:P\" &amp; .Cells(.Rows.Count, 1).End(xlUp).Row)\n</code></pre>\n\n<p>I think you meant <code>.Range</code>, but that now works on the active sheet, and not <code>Worksheets(i)</code></p>\n\n<h2>Miscellaneous</h2>\n\n<p>Functions should return something, and better coding practice is to strongly type this, rather than leaving an implied variant.</p>\n\n<pre><code>Function RemoveLeadingZeroes(ByVal str) as String\n</code></pre>\n\n<p>Early bind instead of late bind - it is more efficient (except when working across different Windows versions or different Office versions). It also allows for intellisense which makes coding and debugging a lot easier!</p>\n\n<pre><code>' Add reference to Scripting so you can natively access the FileSystemObject\nDim oFSO As FileSystemObject\nDim oFolder As Folder\nDim oFiles As Files\nDim oFile As File\n\nSet oFSO = New FileSystemObject\nSet oFolder = oFSO.GetFolder(FolderPath)\nSet oFiles = oFolder.Files\n</code></pre>\n\n<p>Put each line of code on a separate line - this makes it easier to find, read and debug. If your code is reaching the VBA IDE maximum, then it is time to review the code and how it is broken up. As an example:</p>\n\n<pre><code>Dim oFSO As Object: Set oFSO = CreateObject(\"Scripting.FileSystemObject\")\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>Dim oFSO As Object\nSet oFSO = CreateObject(\"Scripting.FileSystemObject\")\n</code></pre>\n\n<p>or, in line with previous comment:</p>\n\n<pre><code>Dim oFSO As FileSystemObject\nSet oFSO = New FileSystemObject\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T01:31:32.403", "Id": "225226", "ParentId": "225195", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T14:07:33.813", "Id": "225195", "Score": "2", "Tags": [ "vba", "excel" ], "Title": "Reads files into 12 different sheets & cross compares files with audits and charts it out" }
225195
<p>I created a simple login program that works how I wanted them to work. I separated the GUI and database codes into two different python files. I named the files as <em>login.py</em> and <em>dbaseManip.py</em>. The <strong>login.py</strong> consist of Tkinter syntax and all stuff related to GUI. On the other hand, <strong>dbaseManip.py</strong> holds the database related syntax such as the connection and the queries.</p> <p><strong>login.py</strong></p> <pre><code>import tkinter as tk from tkinter import messagebox from tkinter import ttk import dbaseManip as db class loginForm(ttk.Frame): def __init__(self,parent,*arags,**kwargs): tk.Frame.__init__(self,parent) self.parent = parent self.parent.protocol("WM_DELETE_WINDOW",self.closing_window) window_width = 350 window_height = 100 screen_width = self.parent.winfo_screenwidth() screen_height = self.parent.winfo_screenheight() x_position = int((screen_width/2) - (window_width/2)) y_position = int((screen_height/2) - (window_height/2)) self.parent.geometry("{}x{}+{}+{}".format(window_width,window_height,x_position,y_position)) self.widgeter() def widgeter(self): self.ent_username = ttk.Entry(self.parent) self.ent_username.insert(0,"username") self.ent_username.bind("&lt;FocusIn&gt;",self.foc_in_username) self.ent_username.bind("&lt;FocusOut&gt;",self.foc_out_username) self.ent_password = ttk.Entry(self.parent) self.ent_password.insert(0,"password") self.ent_password.bind("&lt;FocusIn&gt;",self.foc_in_password) self.ent_password.bind("&lt;FocusOut&gt;",self.foc_out_password) btn_login = ttk.Button(self.parent,text="Login",command=self.submit) btn_exit = ttk.Button(self.parent,text="Exit",command=self.closing_window) self.ent_username.grid(row=0,column=0,columnspan=3,sticky="nsew") self.ent_password.grid(row=1,column=0,columnspan=3,sticky="nsew") btn_login.grid(row=2,column=0,sticky="nsw") btn_exit.grid(row=2,column=1,sticky="nse") def foc_in_username(self, *args): if self.ent_username.get() == "username": self.ent_username.delete(0, tk.END) def foc_out_username(self,*args): if not self.ent_username.get(): self.ent_username.insert(0,"username") def foc_in_password(self,*args): if self.ent_password.get() == "password": self.ent_password.delete(0,tk.END) self.ent_password.configure(show="*") def foc_out_password(self,*args): if not self.ent_password.get(): self.ent_password.insert(0,"password") self.ent_password.configure(show="") def closing_window(self): answer = messagebox.askyesno("Exit","You want to exit the program?") if answer == True: self.parent.destroy() def submit(self): __verify = db.DatabaseManip(self.ent_username.get(),self.ent_password.get()) __str_verify = str(__verify) if __str_verify == "correct": self.initialize_mainApplication() elif __str_verify is "incorrect": messagebox.showerror("Incorrect Password","You have entered incorrect password") # add deleter elif __str_verify == "notexist": messagebox.showerror("Username does not exist","The username you entered does not exist") def initialize_mainApplication(self): self.parent.destroy() self.parent = tk.Tk() self.mainApp = mainApplicaiton(self.parent) self.parent.mainloop() class mainApplicaiton(tk.Frame): def __init__(self,parent): self.parent = parent if __name__ == "__main__": root = tk.Tk() loginForm(root) root.mainloop() </code></pre> <p><strong>dbaseManip.py</strong></p> <pre><code>import mysql.connector class DatabaseManip(): def __init__(self,username,password): self.username = username self.password = password # # print(self.username) # print(self.password) self.dbaseInitializer() def dbaseInitializer(self): mydb = mysql.connector.connect( host="127.0.0.1", user="root", password="admin123", database="testdb" ) self.myCursor = mydb.cursor() query_user_exists = "SELECT EXISTS(SELECT * FROM users WHERE username = %s)" self.myCursor.execute(query_user_exists,(self.username,)) tuple_user_exists = self.myCursor.fetchone() total_user_exists = int(tuple_user_exists[0]) if total_user_exists != 0: query_pass_validation = "SELECT password FROM users WHERE username = %s" self.myCursor.execute(query_pass_validation,(self.username,)) __tuple_valid_pass = self.myCursor.fetchone() __password_validation = __tuple_valid_pass[0] if __password_validation == self.password: self.verdict = "correct" else: self.verdict = "incorrect" else: self.verdict = "notexist" def __str__(self): return self.verdict @property def username(self): return self.__username @username.setter def username(self,username): self.__username = username @property def password(self): return self.__password @password.setter def password(self,password): self.__password = password </code></pre> <p>This is how the system works:</p> <ol> <li>The login form will pop up</li> <li>After the user submitting their username and password, it will call the class DatabaseManip() that exists in dbaseManip.py.</li> <li>The DatabaseManip Class will validate the user's account.</li> <li><strong>HERE COMES MY PROBLEM</strong> If the username does not exist in the database, it will assign a string "notexist" to a class variable called <em>verdict</em>. If the password is wrong, it will assign "incorrect". And lastly, if the validation is correct; it will assign "correct".</li> <li>The verdict result (which is either "correct","incorrect" or "notexist") will be returned to the GUI class in <strong>login.py</strong> using the <code>__str__</code> method.</li> <li>In the loginForm class, a conditional statement will determine if the verdict from the databaseManip class is either "correct","incorrect" or "notexist". If it is "correct", a new window will pop-up. On the other hand, if it is either "incorrect" or "notexist", it will show an error message.</li> </ol> <p>I think my way of coding this is extremely bad in terms of security and integrity. I'm not confident in the "correct", "incorrect", and "notexit" part. I would like to ask for advice to make this program more secure and not as wacky as the current state.</p>
[]
[ { "body": "<p>Firstly I'd suggest following <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> and/or using an auto-formatter like <a href=\"https://github.com/psf/black\" rel=\"nofollow noreferrer\">black</a>, but if it's just you working on it\nthat is a bit less of an issue than if other people were involved.\nSuffice to say, most code follows that and it usually gets flagged first\nthing (because it's so noticeable).</p>\n\n<p>Reading the code, is that all there is, you are able to log in via a\nGUI? Then I'd say first thing would probably be not to hardcode the\ncredentials to the database. So what/how's this securing anything? If\nthe program has the credentials ... and the program is being run by the\nuser who's authenticating ... what stops me from connecting directly to\nthe database?</p>\n\n<hr>\n\n<p>Apart from that fundamental issue looks mostly okay, no SQL injection\nsince the <code>execute</code> will handle that.</p>\n\n<p><code>__</code> as prefix for the variable names is unnecessary and confusing. I\ncan't see why it's there at all.</p>\n\n<p>Actually, <code>SELECT password ...</code> ... the password's stored in plaintext?\nBig no-no in anything used by other people. Do not store passwords in\nplaintext.</p>\n\n<p>The properties at the end of <code>DatabaseManip</code> seem not very useful, in\nPython there's no need for them unless you want to control what/how\nvalues are stored in the object / how they're computed if they're not\nstored at all.</p>\n\n<p>The <code>__str__</code> method is there for what reason? That's very much\nconfusing the responsibility of the class. It would somewhat make sense\nif it's being used interactively in a REPL, otherwise I can't see the\nreason for having it. Oh. Oh now I see it. Yeah, don't do that,\nthat's bad style. How I'd expect things to go is something like this:</p>\n\n<pre><code> def submit(self):\n result = db.DatabaseManip().check_credentials(self.ent_username,self.ent_password)\n if result == \"correct\":\n self.initialize_mainApplication()\n elif result == \"incorrect\":\n messagebox.showerror(\"Incorrect Password\",\"You have entered incorrect password\")\n # add deleter\n elif result == \"notexist\":\n messagebox.showerror(\"Username does not exist\",\"The username you entered does not exist\")\n else:\n messagebox.showerror(\"Unexpected validation result\",\"Validation of credentials failed unexpectedly with result\".format(result))\n</code></pre>\n\n<p>So here: Validating is an action, a method. The parameters of which\naren't part of the helper object, but method parameters. The result is\nstill a string (try making this an enumeration, that's more \"correct\" in\na way as you really want to have a fixed set of possible results, not a\nstring that can contain basically anything. Finally, the programmer\nerror case is handled too (the last <code>else</code>).</p>\n\n<p>Also note that <code>... is \"foo\"</code> is <em>likely</em> incorrect, c.f.\n<code>\"foo\" is \"foobar\"[0:3]</code>, <a href=\"https://docs.python.org/3/reference/expressions.html#is-not\" rel=\"nofollow noreferrer\"><code>is</code> does a check for object identity</a>, <a href=\"https://www.geeksforgeeks.org/difference-operator-python/\" rel=\"nofollow noreferrer\">not\nequality</a>! Not even numbers are same via <code>is</code> if they're not interned at\nthe same time:</p>\n\n<pre><code>1000000 == 1000000 # _always_ True\n\nx = 1000000\ny = 1000000\nx is y # _probably_ False\n</code></pre>\n\n<p>Also <code>if x == True</code> can obviously be simplified to <code>if x</code>.</p>\n\n<hr>\n\n<p>So it's not all bad, simply try and stay away from \"stringly\"-typed\nthings, use the language features as they're intended and have a goal\nfor what your security requirements are. I've not gone into more detail\non the last bit simply because I still don't understand the intent\nhere. Suffice to say like this it would only work if the user can't\nexit the UI and open a shell / other means of executing code on the\nmachine (like in a kiosk configuration with limited access to\nperipherals and the machine itself). Or if the actual database access\nwas moved to a separate external service that (again) can't be\ncircumvented by the local user.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T22:29:28.607", "Id": "226601", "ParentId": "225203", "Score": "2" } } ]
{ "AcceptedAnswerId": "226601", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T15:21:21.667", "Id": "225203", "Score": "2", "Tags": [ "python", "python-3.x", "mysql", "authentication", "tkinter" ], "Title": "Python Tkinter login GUI with database" }
225203
<p>I wrote the function below, but I feel it could be improved and so I am open to your wise suggestions.<br> The use case for this is to manipulate Excel data. As a freelance dev, I cannot always choose the architecture nor the source of data I have to manipulate :-/ </p> <pre><code>Sub getAdoRsFromExcel_test() 'with error retrieval' Dim rs As ADODB.Recordset, fName As String, sSql As String fName = ThisWorkbook.FullName sSql = "select * from [countries$a:b] where country like '%a%'" Set rs = getAdoRsFromExcel(fName, sSql) If Not rs Is Nothing Then Debug.Print Now, rs.EOF, rs.BOF, rs.RecordCount Else Debug.Print Now, "Shit happens" End If End Sub Function getAdoRsFromExcel(fileName As String, sSql As String) As ADODB.Recordset 'given Excel full file name and SQL query (in appropriate syntax), returns an ADODB recordset 'in case of error, returns Nothing Dim con As ADODB.Connection, rs As ADODB.Recordset, sConn As String, sConn2 As String sConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" &amp; fileName sConn2 = ";Extended Properties=""Excel 12.0 Xml;HDR=YES"";" On Error GoTo hell Set con = New ADODB.Connection con.Open sConn &amp; sConn2 Set rs = New ADODB.Recordset rs.CursorLocation = adUseClient rs.Open sSql, con, adOpenKeyset 'rather use this so RecordCount works Set getAdoRsFromExcel = rs 'Debug.Print Format$(Now, "hh:mm:ss"), rs.RecordCount, sSql Set rs = Nothing adios: Exit Function hell: Debug.Print Format$(Now, "hh:mm:ss"), Err.Number, Err.Description Select Case Err.Number Case -2147217904: Debug.Print Format$(Now, "hh:mm:ss"), "Wrong field name ?" Case -2147467259: Debug.Print Format$(Now, "hh:mm:ss"), "Wrong file name ?" Case Else: Debug.Print Format$(Now, "hh:mm:ss"), "Shit happens - learn from mistakes" End Select 'On Error Resume Next 'rs.Close 'con.Close Set getAdoRsFromExcel = Nothing Resume adios Resume End Function </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T15:32:40.227", "Id": "437168", "Score": "4", "body": "I'm missing something - if you're going to the trouble of using SQL why not have the data be in SQL Server? If you're getting data in Excel, load it into your SQL Server database?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T08:10:26.930", "Id": "437266", "Score": "0", "body": "@this I cannot always choose my architecture. If my source is an Excel sheet and my output has to be an Excel sheet, I will take the straight line. Also when your client is a bank for instance, they will not always give you access to their db server." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T12:43:45.163", "Id": "437303", "Score": "0", "body": "Just one more if I may - I'm sure you are aware that you are using Access engine to do the SQL querying for you. In which case, why not have the data be in Access database, even if temporarily? Two advantages: 1) you can easily validate the data because Access is strict on types in comparison to Excel and 2) driving the queries from Access means you don't need to have XSLM files; the VBA code stays in ACCDB and you can ship XLSX files easily." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T13:11:32.113", "Id": "437310", "Score": "0", "body": "@this I love Access, but when you are asked to make an Excel macro, you make an Excel macro, unless you can sell another option with serious argument. The function above is one among many in my 'toolbox'. I did not post it here to discuss about the use cases; I am just looking for improvement suggestions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T14:46:26.690", "Id": "437325", "Score": "0", "body": "I completely understand and I apologize for derailing - I'm asking because I want to understand the scenario - it might be useful to give more details about the why as that can help a lot with the code review as we would be aware with the constraints you are dealing with." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T15:28:05.900", "Id": "225206", "Score": "0", "Tags": [ "sql", "vba", "excel" ], "Title": "Excel: read data into ADODB recordset" }
225206
<p>Trying to build a TreeTableView following this guide <a href="https://edvin.gitbooks.io/tornadofx-guide/content/part1/5.%20Data%20Controls.html" rel="nofollow noreferrer">https://edvin.gitbooks.io/tornadofx-guide/content/part1/5.%20Data%20Controls.html</a>. While I managed to use File class as a data source, I still think that there is a room for improvement. I would love to learn what can be improved here in terms of code readability and overall performance. Thanks in advance.</p> <pre><code>class MainView : View("scan your folders") { override val root = HBox() private val controller: FileWalkController by inject() init { with(root){ prefWidth = 640.0 prefHeight = 480.0 button("Target Directory") { tooltip("Select Folder for scanning") action { val dir = chooseDirectory("Select Folder for scanning") if(dir != null){ val dirFileData:FileData = controller.getFileData(dir) treetableview&lt;File&gt;().apply{ root = TreeItem(dir) column("Name", File::getName) column("Files", Long::toString).setCellValueFactory {param-&gt; controller.getFileData(param.value.value).filesCount.toProperty().asString() } column("Size", Double::toString).setCellValueFactory { param -&gt;controller.round(controller.getFileData(param.value.value).fileSize.div(1048576), 1).toProperty().asString()} column("Folders", Long::toString).setCellValueFactory { param -&gt;controller.getFileData(param.value.value).foldersCount.toProperty().asString()} column("% of Parent", Double::toString).setCellValueFactory { param -&gt; controller.percentOf(controller.getFileData(param.value.value).fileSize,dirFileData.fileSize).toProperty().asString() } column("Last Modified", Date::toString).setCellValueFactory { param -&gt; Date(param.value.value.lastModified()).toProperty().asString() } println("before populate: "+ LocalDateTime.now()) populate { controller.buildFilesList(it.value) } println("after populate: "+ LocalDateTime.now()) root.isExpanded = true resizeColumnsToFitContent() setColumnResizePolicy(TreeTableView.CONSTRAINED_RESIZE_POLICY) } } } } } }} </code></pre> <p>FileData class:</p> <pre><code>class FileData(val name: String, val fileSize: Double, val filesCount: Long, val foldersCount: Long, val files: List&lt;FileData&gt; = emptyList()) </code></pre> <p>Controller code:</p> <pre><code>class FileWalkController: Controller(){ fun buildFilesList(file: File):List&lt;File&gt;{ if(file.isDirectory){ return Files.list(file.toPath()).map { path-&gt; path.toFile() }.collect(Collectors.toList()) } return emptyList() } fun getFileData(file: File):FileData{ val utils = FileUtils() Files.walkFileTree(Paths.get(file.path), utils) val foldersCount = if(file.isDirectory) utils.foldersCount-1 else utils.foldersCount return FileData(file.name, utils.fileSize.toDouble(), utils.filesCount, foldersCount) } fun percentOf(first: Double, second: Double):Double{ val percent = 100 * first.div(second) return round(percent, 1) } fun round(value: Double, precision: Int): Double { val scale = Math.pow(10.0, precision.toDouble()).toInt() return Math.round(value * scale).toDouble() / scale }} </code></pre> <p>FileUtils code:</p> <pre><code>class FileUtils : FileVisitor&lt;Path&gt; { var fileSize: Long = 0 private set var filesCount: Long = 0 private set var foldersCount: Long = 0 private set @Throws(IOException::class) override fun preVisitDirectory(dir: Path, attrs: BasicFileAttributes): FileVisitResult { return FileVisitResult.CONTINUE } @Throws(IOException::class) override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult { filesCount++ if(attrs.isRegularFile){ fileSize+=attrs.size() } return FileVisitResult.CONTINUE } @Throws(IOException::class) override fun visitFileFailed(file: Path, exc: IOException): FileVisitResult { return FileVisitResult.CONTINUE } @Throws(IOException::class) override fun postVisitDirectory(dir: Path, exc: IOException?): FileVisitResult { foldersCount++ return FileVisitResult.CONTINUE }} </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T18:30:57.043", "Id": "225211", "Score": "1", "Tags": [ "javafx", "kotlin" ], "Title": "Building treetableview using directory as a datasource" }
225211
<p>I have written this function to create a URL:</p> <pre><code>function createUrl(urlPath) { const endpoint = url.parse(env.config.get('myEndpoint')); endpoint.pathname = path.posix.join(endpoint.pathname, urlPath); return endpoint; } </code></pre> <p><code>const</code> basically creates a mutable object whose properties can still be modified. Here, I need to declare some Object which will only be modified once. Am I correct in declaring <code>endpoint</code> as <code>const</code>? </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T20:14:00.013", "Id": "437204", "Score": "1", "body": "According to me in the field of programming Constant means, in fact, a constant which should never be modified. Now in Javascript I don't understand why but I can modify an object declared as constant. But shouldn't it be that we should only declare a constant when we know for sure it will never be modified? Having a constant and then modifying it directly afterwards is misleading isn't it?\n\n\nPS:- Me and my co-worker had a discussion on this topic and he seems adamant on the fact that JS constants are meant to be used like in the code above. I need your opinions as well on this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T20:37:38.420", "Id": "437209", "Score": "1", "body": "Yeah, it's ok. All `const` means in JS is you can't reassign that \"variable\" to anything else. It doesn't affect mutability of properties (you'd use property descriptors for that). It definitely seems weird at first, but you can't necessarily take meanings from one language and project them onto another." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T21:09:53.650", "Id": "437210", "Score": "1", "body": "See also `Object.freeze` and `Object.seal`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T21:42:38.300", "Id": "437211", "Score": "0", "body": "@user11536834 I was more concerned about the readability of the code. By name `const` means something that you are not planning on changing. Declaring an object as a constant and then updating in the very next line seemed a bit odd to me. Is there any performance drawback if I used a `let` here instead?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T21:56:34.970", "Id": "437212", "Score": "0", "body": "I'd guess the JIT would be smart enough to figure out that you weren't going to change it anyway with a `let` in a case like this, but you never know. Annoyingly, this seems to lead to a situation where you \"should\" use `const` instead of `let` most of the time, because you usually won't be reassigning the value. IMO that goes against the \"nature\" of JS, because historically it tends to favor robustness over pickiness (e.g. implicit conversion, weak typing, etc.). But that's just my opinion; extremely strict languages are a popular thing now days." } ]
[ { "body": "<p>Yes, it's correct to use <code>const</code> here. That would be considered idiomatic Javascript. If you're using <code>const</code> when you shouldn't, you'll notice as it will produce a <code>TypeError</code>.</p>\n\n<p>People coming from other languages might disagree as they think that <code>const</code> means that the variable is constant/immutable (which is not the case, it's just not re-assignable). But that is really a critique of the <em>naming of the keyword</em>, not <em>your usage of the keyword</em> (which is correct).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T16:52:15.343", "Id": "225366", "ParentId": "225214", "Score": "2" } } ]
{ "AcceptedAnswerId": "225366", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T19:55:13.430", "Id": "225214", "Score": "4", "Tags": [ "javascript", "url", "constants" ], "Title": "Function to create URL relative to a configured base URL" }
225214
<p>We're working on some code that involves validating certain UNC paths (specifically looking for things that appear to be subdirectories of other things), and we've gone back and forth on how to best do this. </p> <p>One step of that process looks like this:</p> <ul> <li>Given a UNC path such as <code>\\localhost\c$\some\great\directory</code></li> <li>Transform that to the appropriate rooted path, e.g. <code>C:\some\great\directory</code></li> </ul> <p>You can assume that the UNC path is validated to not be null, empty, whitespace, or to a location that does not exist in a previous step. You can also assume that <code>ParseUncPath</code> is perfect; the contents of that are not relevant to the review, but you can assume that given an input of <code>\\localhost\c$\some\great\path</code> we end up with </p> <ul> <li><code>hostname</code> -> <code>localhost</code></li> <li><code>sharename</code> -> <code>c$</code></li> <li><code>path</code> -> <code>\some\great\path</code></li> </ul> <p>Our existing implementation uses <code>System.Management</code> APIs to accomplish this like so:</p> <pre><code>private static string CheckIfUncPathExistsV1(string fullpath) { ParseUncPath(fullpath, out string hostname, out string sharename, out string path); var scope = new ManagementScope(string.Format(@"\\{0}\root\cimv2", hostname)); var query = new SelectQuery(string.Format("SELECT * FROM Win32_Share WHERE name = '{0}'", sharename)); using (var search = new ManagementObjectSearcher(scope, query)) { return search.Get() .Cast&lt;ManagementBaseObject&gt;() .Select(item =&gt; item["path"].ToString() + path) .First(); } } </code></pre> <p>This is pretty straightforward, but poking around on MSDN reveals a few potential issues:</p> <ul> <li><code>System.Management</code> is apparently slower and not supported relative to <code>Microsoft.Management.Infrastructure</code></li> <li>Its possible that <code>root/CIMv2</code> is not the correct WMI namespace on all machines</li> <li>It just feels kinda gross to me</li> </ul> <p>I dig some digging, and figured out that we could use the <code>Microsoft.Management.Infrastructure</code> APIs instead, which are the hip thing apparently. The only problem is that those get really, really gross:</p> <pre><code>private static string CheckIfUncPathExistsV2(string fullpath) { // https://docs.microsoft.com/en-us/windows/win32/cimwin32prov/win32-share const string wmiClassName = "Win32_Share"; // https://docs.microsoft.com/en-us/windows/win32/wmisdk/constructing-a-moniker-string const string defaultWmiNamespace = "root/CIMv2"; const string registryKeyNamespace = @"HKEY_LOCAL_MACHINE\Software\Microsoft\WBEM\Scripting"; const string registryKey = "Default Namespace"; ParseUncPath(fullpath, out string hostname, out string sharename, out string path); string wmiNamespace = Registry.GetValue(registryKeyNamespace, registryKey, defaultWmiNamespace) as string; using (var session = CimSession.Create(hostname)) { using (var search = new CimInstance(wmiClassName, wmiNamespace)) { var property = CimProperty.Create("Name", sharename, CimFlags.Key); search.CimInstanceProperties.Add(property); using (var searchResults = session.GetInstance(wmiNamespace, search)) { if (searchResults == null) { throw new Exception(string.Format("No share on host {0} could be found with name {1}", hostname, sharename)); } return searchResults.CimInstanceProperties["Path"].Value.ToString() + path; } } } } </code></pre> <p>It seems that the interactions between all of the <code>Cim*</code> classes is really tricky (the fact that you need two <code>CimInstances</code> to get anything blows my mind), so we decided not to use it. I wanted to see if I could make this work better, and came up with the following way to encapsulate the interactions with WMI. First, I made a base class that hides all of the general nastiness:</p> <pre><code>public class Win32WmiClass: IDisposable { #region Wmi Magic // https://docs.microsoft.com/en-us/windows/win32/wmisdk/constructing-a-moniker-string static private string DEFAULT_WMI_NAMESPACE = "root/CIMv2"; static private string REGISTRY_KEY_NAMESPACE = @"HKEY_LOCAL_MACHINE\Software\Microsoft\WBEM\Scripting"; static private string REGISTRY_KEY_VALUE_NAME = "Default Namespace"; protected T GetCimInstanceProperty&lt;T&gt;(string key) { return (T)SearchResults.CimInstanceProperties[key].Value; } private CimSession _session = null; private CimSession Session { get { if (_session == null) { _session = CimSession.Create(HostName); } return _session; } } private string _wmiNamespace; private string WmiNamespace { get { if (string.IsNullOrWhiteSpace(_wmiNamespace)) { _wmiNamespace = Registry.GetValue(REGISTRY_KEY_NAMESPACE, REGISTRY_KEY_VALUE_NAME, DEFAULT_WMI_NAMESPACE) as string; } return _wmiNamespace; } } private CimInstance _search = null; private CimInstance Search { get { if (_search == null) { _search = new CimInstance(WmiClassName, WmiNamespace); _search.CimInstanceProperties.Add(CimProperty.Create(WmiKeyPropertyName, WmiKeySearchCriteria, CimFlags.Key)); } return _search; } } private CimInstance _results = null; private CimInstance SearchResults { get { if (_results == null) { _results = Session.GetInstance(WmiNamespace, Search); } return _results; } } #endregion #region Needs Override virtual protected string WmiClassName { get; } virtual protected string WmiKeyPropertyName { get; } virtual protected string WmiKeySearchCriteria { get; } virtual public string HostName { get; protected set; } #endregion #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). Session?.Dispose(); Search?.Dispose(); SearchResults?.Dispose(); } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~Win32Share() { // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); // } // This code added to correctly implement the disposable pattern. public void Dispose() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); // TODO: uncomment the following line if the finalizer is overridden above. // GC.SuppressFinalize(this); } #endregion } </code></pre> <p>This now handles a few things:</p> <ul> <li>We grab the appropriate namespace from the registry, and fall back to the normal default value</li> <li>We assume that everything will search using a single key property</li> <li>This implements <code>IDisposable</code>, so now we don't need our deeply nested <code>using</code>s</li> <li>We don't need to know how all of the CIM classes interact under the hood.</li> </ul> <p>Then we make a child class to represent the specific WMI class we need, <code>Win32_Share</code>:</p> <pre><code>public class Win32Share: Win32WmiClass { #region Override override protected string WmiClassName { get; } = "Win32_Share"; override protected string WmiKeyPropertyName { get; } = "Name"; override protected string WmiKeySearchCriteria { get { return ShareName; } } #endregion #region Properties public string ShareName { get; set; } public string Caption { get { return GetCimInstanceProperty&lt;string&gt;("Caption"); } } public string Description { get { return GetCimInstanceProperty&lt;string&gt;("Description"); } } public DateTime InstallDate { get { return GetCimInstanceProperty&lt;DateTime&gt;("InstallDate"); } } public string Status { get { return GetCimInstanceProperty&lt;string&gt;("Status"); } } public uint AccessMask { get { return GetCimInstanceProperty&lt;uint&gt;("AccessMask"); } } public bool AllowMaximum{ get { return GetCimInstanceProperty&lt;bool&gt;("AllowMaximum"); } } public uint MaximumAllowed { get { return GetCimInstanceProperty&lt;uint&gt;("MaximumAllowed"); } } public string Name { get { return GetCimInstanceProperty&lt;string&gt;("Name"); } } public string Path { get { return GetCimInstanceProperty&lt;string&gt;("Path"); } } public uint Type { get { return GetCimInstanceProperty&lt;uint&gt;("Type"); } } #endregion public Win32Share(string hostname, string sharename) { HostName = hostname; ShareName = sharename; } } </code></pre> <p>This exposes the different instance properties through normal, strongly-typed properties and doesn't require a developer to remember how to grab the instance properties. We could add methods/system properties as well, but that isn't necessary for our use-case. Additionally, this becomes very easy to use for any developer who needs it, like so:</p> <pre><code>private static string CheckIfUncPathExistsV3(string fullpath) { ParseUncPath(fullpath, out string hostname, out string sharename, out string path); using (var share = new Win32Share(hostname, sharename)) { return share.Path + path; } } </code></pre> <p>The main things I'd be interested in are:</p> <ul> <li>General C# tips; it isn't my main language, but we do use it a fair bit so if there are cleaner ways to express myself I'd love to hear it</li> <li>Specific <code>System.Management</code> or <code>Microsoft.Management.Infrastructure</code> tips, or if I'm completely misusing/misunderstanding something. It works in all of our tests so far, but if there is something I'm missing please let me know.</li> <li>Encapsulation - am I providing a reasonable base class that would be extendable to any other WMI classes I'm just not using right now? </li> <li>Usability - if you were to get onboarded to this project tomorrow, which of these three approaches would be easiest to understand, use, and modify without having to have MSDN open the entire time?</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T14:45:29.547", "Id": "437324", "Score": "0", "body": "Maybe my understanding of the problem is too simple, but to check if a path exists; can't you use `Directory.Exists(uncPath)`? Or if you want some metadata: `new DirectoryInfo(uncPath).Exists` - both can handle UNC-paths" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T15:02:09.233", "Id": "437328", "Score": "0", "body": "That is one part of what we do (one of the higher steps in this pipeline does that), but we then also want to do some comparisons (e.g. make sure UNC path A is not a subdirectory of UNC path B) after this validation. I'll admit that this is not a well named function :)" } ]
[ { "body": "<h2>API #3</h2>\n\n<p>Several legacy Windows WMI API's (LAN adapters, CIM, installed products, ..) have extended state available in the Registry. It's a good idea to provide a wrapper class for consumers, keeping all the magic inside this class. I'm not convinced though about the name <code>Win32WmiClass</code>, it suggest a WMI-only interface, but you also use the Registry.</p>\n\n<hr>\n\n<h3><a href=\"https://github.com/ktaranov/naming-convention/blob/master/C%23%20Coding%20Standards%20and%20Naming%20Conventions.md\" rel=\"nofollow noreferrer\">Naming Concentions</a> (C#)</h3>\n\n<ul>\n<li>Constants should be PascalCased: <code>DEFAULT_WMI_NAMESPACE</code> -> <code>DefaultWmiNamespace</code> </li>\n</ul>\n\n<hr>\n\n<h3>General Guidelines</h3>\n\n<p>Use arrow notation to write more clean and compact code.</p>\n\n<blockquote>\n<pre><code>public string Caption { get { return GetCimInstanceProperty&lt;string&gt;(\"Caption\"); }}\n</code></pre>\n</blockquote>\n\n<pre><code> public string Caption =&gt; GetCimInstanceProperty&lt;string&gt;(\"Caption\");\n</code></pre>\n\n<p>Use built-in path concatenation functions.</p>\n\n<blockquote>\n<pre><code>return share.Path + path;\n</code></pre>\n</blockquote>\n\n<pre><code>return System.IO.Path.Combine(share.Path, path); // namespace could be using statement\n</code></pre>\n\n<p>Use built-in memoization support. The problem with the code below, is that it \nwill always retrieve the value from the Registry on each <em>get</em>, if the value is an empty string.</p>\n\n<blockquote>\n<pre><code>private string WmiNamespace\n{\n get\n {\n if (string.IsNullOrWhiteSpace(_wmiNamespace))\n {\n _wmiNamespace = Registry.GetValue(REGISTRY_KEY_NAMESPACE, \n REGISTRY_KEY_VALUE_NAME, DEFAULT_WMI_NAMESPACE) as string;\n }\n\n return _wmiNamespace;\n }\n}\n</code></pre>\n</blockquote>\n\n<p>You only want initialise-once support instead.</p>\n\n<pre><code>private Lazy&lt;string&gt; _wmiNamespace = new Lazy&lt;string&gt;(\n () =&gt; Registry.GetValue(REGISTRY_KEY_NAMESPACE, REGISTRY_KEY_VALUE_NAME, \n DEFAULT_WMI_NAMESPACE) as string);\n\npublic string WmiNamespace =&gt; _wmiNamespace.Value; // only once initialized\n</code></pre>\n\n<hr>\n\n<h3>OO-Design</h3>\n\n<ul>\n<li>Your base class is not <em>abstract</em>, but perhaps it should be. Is there a use case to instantiate the base class, I tend to think not? Your virtual properties are glorified constants. It's better, in my opinion, to make a <em>protected</em> constructor with the values of the properties for derived classes to set. This allows for better encapsulation.</li>\n</ul>\n\n<p>I would do something like this:</p>\n\n<pre><code>public abstract class Win32WmiClass: IDisposable\n{\n protected string WmiClassName { get; }\n protected string WmiKeyPropertyName { get; }\n protected string WmiKeySearchCriteria { get; }\n public string HostName { get; }\n\n protected Win32WmiClass(string wmiClassName, string wmiKeyPropertyName, \n string wmiKeySearchCriteria, string hostName) \n {\n WmiClassName = wmiClassName;\n WmiKeyPropertyName = wmiKeyPropertyName;\n WmiKeySearchCriteria = wmiKeySearchCriteria;\n HostName = hostName;\n }\n\n // .. CR: other code omitted for brevity\n}\n</code></pre>\n\n<p>If <code>Win32Share</code> itself could have derived classes, also provide the <em>protected</em> constructor below. If not, take it out and <em>seal</em> the class.</p>\n\n<pre><code>public class Win32Share: Win32WmiClass\n{\n public string ShareName { get; }\n\n protected Win32Share(string wmiClassName, string wmiKeyPropertyName, \n string wmiKeySearchCriteria, string hostName, string shareName) \n : base (wmiClassName, wmiKeyPropertyName, wmiKeySearchCriteria, hostName)\n {\n ShareName = shareName;\n }\n\n public Win32Share(string hostName, string shareName) \n : this(\"Win32_Share\", \"Name\", hostName, shareName)\n { \n }\n\n // .. CR: other code omitted for brevity\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T05:00:41.180", "Id": "225236", "ParentId": "225215", "Score": "4" } } ]
{ "AcceptedAnswerId": "225236", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T20:02:57.557", "Id": "225215", "Score": "2", "Tags": [ "c#", "object-oriented", "comparative-review", "io", "wmi-query" ], "Title": "Searching for matching shares" }
225215
<p>I am solving some programming challenges for learning Javascript. The challenge I chose is:</p> <blockquote> <p>Given the head of a singly linked list, reverse it in-place.</p> </blockquote> <p>Here is my implementation in JS</p> <pre><code>// Given the head of a singly linked list, reverse it in-place. const ReverseLinkedList = { reverseLinkedList: (/** @type{ListNode} */ head) =&gt; { if (head === undefined) { return undefined; } if (head.next === undefined) { return head; } let temp = head; let tail = head.next.next; head = temp.next; head.next = temp; head.next.next = undefined; while (tail !== undefined) { let tempNext = tail.next; temp = head; head = tail; head.next = temp; tail = tempNext; } return head; }, ListNode: function ListNode(/** @type{ListNode} */ next, val) { return { next: next, val: val } } }; module.exports = ReverseLinkedList; </code></pre> <p>and my test class</p> <pre><code>const expect = require('chai').expect; const reverseLinkedList = require('../../src/reverseLinkedList'); let head; let node_01; let node_02; let reversed; node_02 = reverseLinkedList.ListNode(undefined, 2); node_01 = reverseLinkedList.ListNode(node_02, 1); head = reverseLinkedList.ListNode(node_01, 0); reversed = reverseLinkedList.reverseLinkedList(head); expect(reversed.val).to.equal(2); expect(reversed.next.val).to.equal(1); expect(reversed.next.next.val).to.equal(0); expect(reversed.next.next.next).to.equal(undefined); node_01 = reverseLinkedList.ListNode(undefined, 1); head = reverseLinkedList.ListNode(node_01, 0); head.next = node_01; reversed = reverseLinkedList.reverseLinkedList(head); expect(reversed.val).to.equal(1); expect(reversed.next.val).to.equal(0); expect(reversed.next.next).to.equal(undefined); head = reverseLinkedList.ListNode(undefined, 0); reversed = reverseLinkedList.reverseLinkedList(head); expect(reversed.val).to.equal(0); expect(reversed.next).to.equal(undefined); </code></pre> <p>Being a Javascript newbie, any comments on the styling and best practices? Also any comments on the algorithm itself is highly appreciated.</p>
[]
[ { "body": "<p>I'm not a big fan of your type-hinting comments. Let JavaScript be JavaScript. If you want typing, practice TypeScript instead.</p>\n\n<p>I find it counterintuitive that the <code>ListNode</code> constructor takes its <code>next</code> parameter before its <code>val</code> parameter. Putting <code>val</code> first is more natural (see my <code>piDigits</code> example below), and also allows <code>next</code> to be omitted for the last node in a list.</p>\n\n<p>You can use the <code>{val, next}</code> syntactic shorthand.</p>\n\n<p>As for the <code>reverseLinkedList</code> algorithm, there is too much code, with too many special cases. The fact that you mention <code>.next.next</code>, reaching <em>two</em> elements ahead, is a sign that you aren't thinking about the loop invariant the right way. You want the code to consider just the local situation at the <code>head</code>.</p>\n\n<p>It's not really appropriate to explicitly set a variable to <code>undefined</code>; <a href=\"https://stackoverflow.com/q/5076944/1157100\"><code>undefined</code> is supposed to represent the fact that no assignment has taken place</a>. In any case, you should be more lenient than checking for <code>… === undefined</code>.</p>\n\n<p>I find that it's nearly always unhelpful to use <code>temp</code> as a variable name or in a variable name.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const ListNode = (val, next) =&gt; { return {val, next}; };\n\nconst reverseLinkedList = (head) =&gt; {\n let newTail = null;\n while (head) {\n let next = head.next;\n head.next = newTail;\n newTail = head;\n head = next;\n }\n return newTail;\n};\n\n\n\nlet piDigits = ListNode(3, ListNode(1, ListNode(4, ListNode(1, ListNode(5)))));\nconsole.log(reverseLinkedList(piDigits));\n\nlet emptyList = null;\nconsole.log(reverseLinkedList(emptyList));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T23:49:00.540", "Id": "437447", "Score": "1", "body": "Thank you very much, very clean and helpful. (Even makes me feel embarrassed to be honest.)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T04:57:47.753", "Id": "225235", "ParentId": "225216", "Score": "7" } } ]
{ "AcceptedAnswerId": "225235", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T20:05:00.457", "Id": "225216", "Score": "1", "Tags": [ "javascript", "beginner", "linked-list" ], "Title": "Reverse a Linked List in place" }
225216
<p>I have developed the following javascript code for creating "widgets" that a third party site can paste onto their page and load content from our web application. Everything is working, and I am in the process of thoroughly testing before we present it for use to our clients (as we don't want any issues to occur that would negatively affect their sites, or any changes to be required on our end that would cause them to have to re-paste the code).</p> <p>The code which a client includes on their page is:</p> <pre><code>&lt;script src="/widgets/widget-script.js"&gt;&lt;/script&gt; &lt;script&gt;document.addEventListener("DOMContentLoaded", function(){UniqueWidgetName.init(["arg1", "arg2"]);});&lt;/script&gt; &lt;div class="unique-widget-name-container"&gt;&lt;/div&gt; </code></pre> <p>And the code contained within <code>widget-script.js</code> is as followed (this is just a basic template void of any business logic):</p> <pre><code>var UniqueWidgetName = UniqueWidgetName || (function(window, document){ "use strict"; var _args = {}; var jQuery, $; var url = "https://yoursite.com"; function main(){ // load required css loadCSS(url + "/widgets/your.css"); // business logic here including usage of loaded jquery version, // usually involves doing an ajax call to obtain some data // and place it within the 'unique-widget-name-container' div } function loadCSS(url){ var css_link = $('&lt;link&gt;',{ rel: "stylesheet", type: "text/css", href: url }); css_link.appendTo('head'); } function loadScript(url, callback){ var scriptTag = document.createElement('script'); scriptTag.setAttribute("src", url); if(typeof callback !== 'undefined'){ if(scriptTag.readyState){ // for older ie versions scriptTag.onreadystatechange = function(){ if(this.readyState === 'complete' || this.readyState === 'loaded'){ callback(); } }; } else { scriptTag.onload = callback; } } (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(scriptTag); } return { init: function(Args){ _args = Args; loadScript("https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js", function(){ // restore $ and window.jQuery to their previous values and store the // new jQuery in our local jQuery variables $ = jQuery = window.jQuery.noConflict(true); main(); }); } }; /* END OF LIBRARY *******************************************************************************/ })(window, document); </code></pre> <p>My main concern at this point is dealing with jquery conflicts. I believe the way I have implemented <code>jQuery.noConflict()</code> should resolve this potential issue, but I wanted someone else to confirm this before a production deployment.</p> <p>Also, does anything else jump out as being a potential issue? Is there anything you would do differently?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T18:38:15.067", "Id": "437700", "Score": "0", "body": "`business logic here including usage of loaded jquery version, usually involves doing an ajax call to obtain some data and place it within the 'unique-widget-name-container' div` Do you really need jQuery?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T19:02:47.290", "Id": "437702", "Score": "0", "body": "@Mohrn Do I REALLY need jQuery...probably not. Does it increase my productivity...Yes. However, if the advantages of not using it outweigh what is gained from using it, I would consider rewriting." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T21:15:15.957", "Id": "225218", "Score": "1", "Tags": [ "javascript" ], "Title": "Javascript Widget Embed Code" }
225218
<p>This is a follow-up to <a href="https://codereview.stackexchange.com/q/224980/5846">this question</a> with bug fixes, question and code improvements from @dfhwze, @PieterWitvoet, @HenrikHansen, @t3chb0t. I am still hoping for an improved approach or algorithm rather than micro-optimizations to the code.</p> <p>.Net provides <code>String.IndexOfAny(string, char[])</code> but not <code>String.IndexOfAny(string, string[])</code>.</p> <p>The existing built-in <code>String.IndexOfAny</code> takes an array of <code>char</code> and returns the lowest position of any one <code>char</code> from the array in a passed in <code>string</code> or <code>-1</code> if none are found.</p> <p>My extension takes a <code>string</code> to search <code>s</code> and an array of <code>string</code>s to find <code>targets</code> and returns the lowest position found of any member of <code>targets</code> in <code>s</code> or <code>-1</code> if none are found.</p> <p>A naive implementation (using LINQ) isn't particularly efficient:</p> <pre><code>public static int IndexOfAny1(this string s, params string[] targets) =&gt; targets.Select(t =&gt; s.IndexOf(t)).Where(p =&gt; p &gt;= 0).DefaultIfEmpty(-1).Min(); </code></pre> <p>My improved implementation tracks the current candidate position and restricts future searches to be before that candidate position:</p> <pre><code>public static int IndexOfAny2(this string s, params string[] targets) =&gt; s.IndexOfAny3(StringComparison.Ordinal, targets); public static int IndexOfAny2(this string s, StringComparison sc, params string[] targets) { if (targets == null || targets.Length == 0) return -1; int index = s.IndexOf(targets[0], sc); var sLen = s.Length; for (int j1 = 1; j1 &lt; targets.Length; ++j1) { var target = targets[j1]; var targetIndex = s.IndexOf(target, 0, index &gt;= 0 ? Math.Min(sLen, index + target.Length) : sLen, sc); if (targetIndex &gt;= 0 &amp;&amp; (index == -1 || targetIndex &lt; index)) { index = targetIndex; if (index == 0) // once you're at the beginning, can't be any less break; } } return index; } </code></pre> <p>This runs up to two times faster.</p> <p>Sample code to test the two methods:</p> <pre><code>Console.WriteLine($"IndexOfAny1 should be 8: {"foo bar baz".IndexOfAny1("barz", "baz")}"); Console.WriteLine($"IndexOfAny1 should be 0: {"aabbccddeeffgghh".IndexOfAny1("bbb", "hh", "aa")}"); Console.WriteLine($"IndexOfAny1 should be 0: {"abc".IndexOfAny1("c", "abc")}"); Console.WriteLine($"IndexOfAny2 should be 8: {"foo bar baz".IndexOfAny2("barz", "baz")}"); Console.WriteLine($"IndexOfAny2 should be 0: {"aabbccddeeffgghh".IndexOfAny2("bbb", "hh", "aa")}"); Console.WriteLine($"IndexOfAny2 should be 0: {"abc".IndexOfAny2("c", "abc")}"); </code></pre> <p>Is there a better algorithm or another way to make this faster?</p> <p>PS Test harness for testing random possibilities:</p> <pre><code>var r = new Random(); var sb = new StringBuilder(); for (int j1 = 0; j1 &lt; r.Next(80,160); ++j1) sb.Append((char)('0'+r.Next(0, 26+52))); var s = sb.ToString(); var listTargets = new List&lt;string&gt;(); for (int j1 = 0; j1 &lt; r.Next(5, 10); ++j1) if (r.NextDouble() &lt; 0.8) { var tLen = r.Next(4, Math.Min(s.Length - 4, 10)); var beginPos = r.Next(0, s.Length - tLen); listTargets.Add(s.Substring(beginPos, tLen)); } else { sb.Clear(); for (int j2 = 0; j2 &lt; r.Next(5, 10); ++j2) sb.Append((char)('0'+r.Next(0, 26+52))); listTargets.Add(sb.ToString()); } var targets = listTargets.ToArray(); if (s.IndexOfAny1(targets) != s.IndexOfAny2(targets)) Console.WriteLine($"Fail on {s} containing {String.Join(",", targets)}"); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T09:12:22.807", "Id": "437271", "Score": "2", "body": "As mentioned before, there are certainly better algorithms, but it also depends on the intended use-case. Many of the more advanced algorithms require some kind of preprocessing, which makes them slower for small inputs, but faster for larger inputs, more targets, repeated searches, and so on. What exactly are your requirements?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T20:46:28.597", "Id": "437409", "Score": "0", "body": "@PieterWitvoet I would say short text, small list of targets would be typical use case: think processing lines of text from a file. Note my test harness generates 80 - 160 character strings and 5 - 10 targets of upto 10 characters, 80% found." } ]
[ { "body": "<p>It seems that you've managed to fix the algorithm, so it does what it's supposed to do. But the concept is the same and performance isn't improved. </p>\n\n<p>Still you could use some more descriptive names, and <code>i</code> instead of <code>j1</code> (why <code>1</code>?).</p>\n\n<p>You could use <code>foreach (string target in targets) { ... }</code> instead of <code>for (int j1;...)</code> because you don't use the index to anything and the performance for an array is about the same for the two <code>for</code>-concepts.</p>\n\n<hr>\n\n<p>You ask for other algorithm types that improves performance.</p>\n\n<p>One concept for the algorithm - that seems to improve the performance significantly - could be the following:</p>\n\n<pre><code>public static int IndexOfAny(this string text, params string[] targets)\n{\n if (string.IsNullOrEmpty(text)) return -1;\n if (targets == null || targets.Length == 0) return -1;\n\n for (int i = 0; i &lt; text.Length; i++)\n {\n foreach (string target in targets)\n {\n if (i + target.Length &lt;= text.Length &amp;&amp; target == text.Substring(i, target.Length))\n return i;\n }\n }\n\n return -1;\n}\n</code></pre>\n\n<hr>\n\n<p>Another that can improve performance even more is the following written in pseudo code - leaving it as a challenge for you to implement it in C#:</p>\n\n<pre><code>IndexOfAny text targets:\n for i = 0 to len(text)-1:\n skip = len(text)\n foreach target in targets:\n target_can_skip = 0\n for k = 0 to len(target)-1:\n if target[k] &lt;&gt; text[i+k]:\n target_can_skip = count how many chars that can be skipped in text before target can be a candidate again\n break\n if k == len(target):\n return i\n\n\n skip = min(skip, target_can_skip)\n\n if skip &gt; 0: \n i = i + skip - 1\n\n return -1 // No match found\n</code></pre>\n\n<hr>\n\n<p>Besides that you may find inspiration <a href=\"https://en.wikipedia.org/wiki/String-searching_algorithm\" rel=\"nofollow noreferrer\">here</a></p>\n\n<hr>\n\n<p><strong>Update according to VisualMelons comments:</strong></p>\n\n<p>The above implemented with <code>string.IndexOf()</code>:</p>\n\n<pre><code>public static int IndexOfAny1(this string text, params string[] targets)\n{\n if (string.IsNullOrEmpty(text)) return -1;\n if (targets == null || targets.Length == 0) return -1;\n\n for (int i = 0; i &lt; text.Length; i++)\n {\n foreach (string target in targets)\n {\n if (i + target.Length &lt;= text.Length &amp;&amp; text.IndexOf(target, i, target.Length) == i)\n return i;\n }\n }\n\n return -1;\n}\n</code></pre>\n\n<p>Notice that the <code>count</code> parameter must be at minimum the length of <code>target</code> or else it will not be found.</p>\n\n<p>Test case:</p>\n\n<pre><code> Stopwatch watch = Stopwatch.StartNew();\n IndexOfAnyDelegate[] funcs = new IndexOfAnyDelegate[]\n {\n Extensions.IndexOfAny,\n //Extensions.IndexOfAny1,\n };\n\n int sum = 0;\n\n for (int i = 0; i &lt; 10000; i++)\n {\n foreach (var func in funcs)\n {\n sum += func(\"foo bar baz\", \"foo\", \"barz\", \"baz\", \" \");\n sum += func(\"aabbccddeeffgghh\", \"bbb\", \"hh\", \"aaa\", \"fg\");\n sum += func(\"abcabc\", \"c\", \"abc\");\n sum += func(\"abcabc\", \"x\", \"wer\");\n sum += func(\"adfaææwjerqijaæsdklfjaeoirweqærqkljadfaewrwexwer\", \"xxxxx\", \"yyyyy\", \"zzzzz\", \"Aaaaaa\", \"x\", \"wer\");\n\n //Console.WriteLine($\"IndexOfAny should be 8: {func(\"foo bar baz\", \"barz\", \"baz\", \" \", \"foo\")}\");\n //Console.WriteLine($\"IndexOfAny should be 0: {func(\"aabbccddeeffgghh\", \"bbb\", \"hh\", \"aaa\", \"fg\")}\");\n //Console.WriteLine($\"IndexOfAny should be 0: {func(\"abcabc\", \"c\", \"abc\")}\");\n //Console.WriteLine($\"IndexOfAny should be 0: {func(\"abcabc\", \"x\", \"wer\")}\");\n //Console.WriteLine(func(\"adfaææwjerqijaæsdklfjaeoirweqærqkljadfaewrwexwer\", \"xxxxx\", \"yyyyy\", \"zzzzz\", \"Aaaaaa\", \"x\", \"wer\"));\n //Console.WriteLine();\n }\n }\n watch.Stop();\n Console.WriteLine(sum);\n Console.WriteLine(watch.ElapsedMilliseconds);\n</code></pre>\n\n<p>You'll have to comment in/out as needed.</p>\n\n<hr>\n\n<p><strong>Update 2</strong></p>\n\n<p>The performance of the above pseudo code decreases (obviously) when the number of targets increases. So my analysis wasn't quite good enough. To optimize on that problem the below variant maintains an array of the next valid index per target, which minimize the number of targets that should be examined per char in the text string:</p>\n\n<pre><code>public static int IndexOfAny(this string text, params string[] targets)\n{\n if (string.IsNullOrEmpty(text)) return -1;\n if (targets == null || targets.Length == 0) return -1;\n\n // Holds the next valid index in text per parget.\n int[] targetNextIndex = new int[targets.Length];\n\n for (int i = 0; i &lt; text.Length; i++)\n {\n for (int j = 0; j &lt; targets.Length; j++)\n {\n // If the targets next index isn't i then continue to next target\n if (targetNextIndex[j] &gt; i)\n continue;\n\n string target = targets[j];\n int k = 0;\n\n for (; k &lt; target.Length &amp;&amp; i + k &lt; text.Length; k++)\n {\n if (target[k] != text[i + k])\n {\n int nextIndex = i + 1;\n // Tries to find the next index in text where the char equals the first char in target.\n while (nextIndex &lt; text.Length &amp;&amp; target[0] != text[nextIndex])\n {\n nextIndex++;\n }\n // The next valid index for the target is found, so save it\n targetNextIndex[j] = nextIndex;\n break;\n }\n }\n\n if (k == target.Length)\n {\n return i;\n }\n }\n }\n\n return -1;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T10:11:54.477", "Id": "437276", "Score": "0", "body": "That middle algorithm is of course going to perform much better in some cases, but it needn't allocate anything: you can use `text.IndexOf(target,i,1) == i` (or something like that) instead of `target == text.Substring(i, target.Length)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T10:54:10.760", "Id": "437284", "Score": "0", "body": "@VisualMelon: normally you are right, when writing something, but in this case - according to my test cases - using `IndexOf()` as you suggest instead of `Substring()` is about 10x slower." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T10:55:45.197", "Id": "437285", "Score": "1", "body": "Wow; glad you measured it then! Could you provide your test code in a gist or something (so I don't have to write my own), because I'm going to have to investigate why (makes no sense to me)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T11:10:16.720", "Id": "437288", "Score": "0", "body": "@VisualMelon: You are right: using `StringComparison.Ordinal` definitely improves performance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T11:10:51.777", "Id": "437289", "Score": "0", "body": "Yes, but I'm not sure it's correct; I'm ashamed I can't remember what `==` does... (I never use it when globalisation is concerned)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T11:42:01.390", "Id": "437295", "Score": "2", "body": "I can't seem to find documentation for the exact behaviour of `==`, but it does appear to be ordinal (ends up calling `EqualsHelper` [here](https://raw.githubusercontent.com/microsoft/referencesource/master/mscorlib/system/string.cs)), so it probably should be `Ordinal` for comparison. With that change, it runs your sample on my machine in ~60ms rather than ~100ms for the `SubString` version (and indeed 1s for the non-ordinal version!)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T15:36:48.980", "Id": "437338", "Score": "0", "body": "A bit of testing indicates that a for loop would be several times faster than the `Substring` approach (and indeed, `IndexOf` is significantly slower, for whatever reason). OP's solution is very sensitive to the order of `targets` - it works best if the first target(s) are found early on. Your solution works best if any target occurs early on, but it's slower when there are no matches at all." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T15:53:32.980", "Id": "437341", "Score": "0", "body": "@PieterWitvoet: If I understand you right, the for-loop approach is what I suggest in the pseudo code - which - when implemented - in fact is much faster than the others. I'm aware that worst case is different for the different algorithms." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T18:08:15.533", "Id": "437372", "Score": "0", "body": "`for` in general is faster than `foreach` when dealing with arrays (and `List`), and using `for` allowed for testing the first target separately to initialize `target` to something useful, which would be even slower with `foreach`. I don't use `i` as a general rule from an old habit of `i` and `l` being poor variables names since they are too easily mistaken for `1` or each other, but I had intended to change `j1` (my goto loop variable) with a more meaningful name (`targetIndex`?). I will try your suggested algorithms but they need to support `StringComparison`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T19:34:19.550", "Id": "437392", "Score": "0", "body": "@VisualMelon `IndexOf` is only about 3 times slower in my (random) testing, but surprising to me as well. I wonder how .Net Core `Span` would be faster and avoid allocation. Perhaps `Substring` shares storage with the parent string when not a duplicate (interning)? PS I am familiar with the Wikipedia page, but assume (and have seen evidence) `IndexOf` is going to be faster than a C# implementation of any of those." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T20:29:26.077", "Id": "437402", "Score": "0", "body": "@HenrikHansen: ah yes, you're right. The `skip` variable threw me off, making me think it was some kind of Boyer-Moore variant." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T20:35:50.313", "Id": "437403", "Score": "0", "body": "My implementation of your pseudo-code uses `target_can_skip = k+1` which in my initial thinking seems correct (unless it is supposed to be based on all `targets` - I'm thinking the description is wrong otherwise it should affect `k` during the loop). Unfortunately there is a bug in the code when a match runs off the end of `text`: \"abc\".IndexOfAny(\"cd\")`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T20:36:17.580", "Id": "437404", "Score": "0", "body": "@PieterWitvoet I think it is like BM, but since the comparison is not reversed, it is not as efficient at skipping (?)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T20:38:34.013", "Id": "437405", "Score": "0", "body": "@NetMage: whether `IndexOf` is faster than those algorithms depends on the use-case. For example, Aho-Corasick's preprocessing can be quite slow, but once that's done a multi-string search can be orders of magnitude faster. Even a single search can be faster if the search text contains few or no matches or if the search text is huge." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T20:40:37.180", "Id": "437406", "Score": "0", "body": "@NetMage: I think so, yes. Also, skipping normally relies on a pre-calculated skip table to be efficient, so I'm not sure what Henrik has in mind?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T20:44:38.777", "Id": "437408", "Score": "0", "body": "@PieterWitvoet A quick search shows a C# implementation of A-C says IndexOf is faster then you have less than 70 targets to look for, which implies to me it is not worth it for most use cases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T20:47:58.013", "Id": "437411", "Score": "0", "body": "Forgot to mention, my implementation of your pseudo-code is 8 to 20 times faster than my naive method, so it is definitely a good improvement if it can be fixed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T08:41:57.607", "Id": "437487", "Score": "0", "body": "@HenrikHansen: after testing it a bit, it looks like the next-index search is often actually slower, at least with OP's test data. Replacing the `while` loop with a `string.IndexOf(char, int)` makes it faster, but it's still occasionally slower compared to the same implementation, but with the next-index search removed. It's making the algorithm more susceptible to non-occurring targets, so maybe capping the look-ahead distance would be better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T17:13:38.847", "Id": "437584", "Score": "0", "body": "@PieterWitvoet: OK, I think the (or my) conclusion is: the different variations over my pseudo code - with or without look ahead - takes the lead depending on the input. Compared the original and the `Substring()` approach, all my tests show them to be better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-05T20:14:37.260", "Id": "514033", "Score": "0", "body": "I wonder if using `IndexOfAny(string,char[])` with the first characters of all targets would speed up finding the next possible match." } ], "meta_data": { "CommentCount": "20", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T07:59:00.197", "Id": "225245", "ParentId": "225220", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T21:42:29.130", "Id": "225220", "Score": "3", "Tags": [ "c#", "performance", "strings", "search" ], "Title": "String.IndexOfAny(string, string[]) (lowest position for group of needles in haystack)" }
225220
<p>I've started working on a small Flask project for no real reason other than fun, and pulled myself back on form validation. I realize that there are existing libraries like WTForms, but wanted to try and write something myself.</p> <p>I tried to make the high-level interaction similar to that of SQLAlchemy, where you define models with column (in this case field) attributes and they get done 'automatically', but this is the first time I've tried writing something like this so I'm looking for criticisms primarily in the <code>FormDeserializer.__init__</code> (I've never had a practical purpose for <code>dir</code> and <code>__dict__</code> so I'm unsure if my usage is acceptable)</p> <pre class="lang-py prettyprint-override"><code>import typing from werkzeug.security import generate_password_hash, check_password_hash from werkzeug import ImmutableMultiDict class Field(): class FieldLengthExceeded(Exception): pass class MissingFieldData(Exception): pass def __init__(self, name: str, *, strict: bool=False, max_length: int=1024): self.name: str = name self._value: typing.Optional[str] = None self._strict: bool = strict self._max_length: int = max_length @property def value(self) -&gt; typing.Optional[str]: return self._value @value.setter def value(self, value): if value is not None and len(value) &gt; self._max_length: raise self.FieldLengthExceeded else: self._value = value def validate(self): if self._value is None and self._strict: raise self.MissingFieldData elif self._value is not None: self._type_specific_validation() def _type_specific_validation(self): pass class IntegerField(Field): class InvalidInteger(Exception): pass def _type_specific_validation(self): if not all([x in '0123456789' for x in self._value]): raise self.InvalidInteger @Field.value.getter def value(self) -&gt; typing.Optional[int]: return self._value if self._value is None else int(self._value) class PasswordField(Field): class Password(str): def __eq__(self, comparator): return check_password_hash(self, comparator) @Field.value.getter def value(self) -&gt; typing.Optional[Password]: return self._value if self._value is None else self.Password(generate_password_hash(self._value)) class EmailField(Field): class InvalidEmail(Exception): pass def _type_specific_validation(self): if '@' not in self._value: raise self.InvalidEmail class FormDeserializer(): def __init__(self, data: ImmutableMultiDict): for attrib in dir(self): d = getattr(self, attrib) if isinstance(d, Field): # Get the attribute from the form data v: typing.Optional[str] = data.get(d.name, None) d.value = v # Check the value is valid d.validate() # Finally, rebind to the value of the field self.__dict__[attrib] = d.value ### Example ### class TestForm(FormDeserializer): username = Field('username', strict=False, max_length=24) password = PasswordField('password', strict=True) email = EmailField('email') data = {'username': 'jellywx', 'password': 'hello world', 'email': 't@tm.tm'} f = TestForm(data) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-30T22:31:42.263", "Id": "225221", "Score": "4", "Tags": [ "python", "python-3.x", "validation", "form", "flask" ], "Title": "Form deserializer for Python Flask" }
225221
<p>Given an array of non-negative integers, we need to find the sum of concatenation of elements in the array.</p> <p>For example - given [11, 22] the result should be - 6666 <br/> i.e.,<br/> 11 + 11 = 1111<br/> 11 + 22 = 1122<br/> 22 + 11 = 2211<br/> 22 + 22 = 2222<br/></p> <p>Sum of all those numbers would result in 6666</p> <p>My code is as below - </p> <pre><code>function concatenationsSum(a) { var sum = 0; for (var i = 0; i &lt; a.length; i++) for (var j = 0; j &lt; a.length; j++) sum += Number("" + a[i] + a[j]); return sum; } </code></pre> <p>Problems like these require brute force since we need to sum each and every combination. This works sure fine for smaller inputs. But if the array is longer, say, 1 ≤ lengthOfArray ≤ 2<sup>5</sup>, how can I handle such large inputs faster? Any suggestions would be appreciated. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T03:55:54.217", "Id": "437229", "Score": "3", "body": "What would be the expected result for an array with three or more elements? Is it still the sum of all combinations of *two* array elements?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T06:13:45.057", "Id": "437244", "Score": "1", "body": "Btw, an array with 2^5 = 32 elements is not really “large.”" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T14:04:41.037", "Id": "437314", "Score": "0", "body": "@MartinR, sure the max length of the array would be 32, but the combinations I need to calculate the sum for would be 1024" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T19:27:07.310", "Id": "437389", "Score": "5", "body": "Could you provide an example for three or four elements as well? Just to clarify how the concatenation should be done." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T07:32:55.400", "Id": "504444", "Score": "0", "body": "(If this was tagged [tag:algorithm], I was tempted to suggest running totals by number \"length\".)" } ]
[ { "body": "<p>I'm always leery of the claim that problems require brute force algorithms. There is, for example, a formula for directly calculating the Nth <a href=\"https://en.wikipedia.org/wiki/Fibonacci_number\" rel=\"noreferrer\">Fibonacci number</a>.</p>\n\n<p>In the case of this problem, there is a much simpler way to perform the calculation that does not require O(n^2) time. Each element of the array pairs with every other element exactly twice - once as the most significant part, and once as the least significant part. These two parts can be calculated separately in one pass.</p>\n\n<p>The low part is the sum of the elements times the number of elements.</p>\n\n<p>The high part is the sum of (the \"offset\" for each element times the sum of the elements). The offset is the digit base raised to the number of digits (expressed generally, but this problem always uses base 10). So for a two digit number (11 or 22) the offset is 100.</p>\n\n<pre><code>function concatenationsSum2(a) {\n var lowSum = 0;\n for (var i = 0; i &lt; a.length; i++)\n lowSum += a[i];\n\n var sum = lowSum * a.length;\n\n for (var i = 0; i &lt; a.length; i++) {\n var size = a[i].toString().length;\n var offset = iPower(10, size);\n sum = sum + lowSum * offset;\n }\n\n return sum;\n}\n\nfunction iPower(base, power) {\n var result = 1;\n for (var i = 1; i &lt;= power; i++)\n result *= base;\n\n return result;\n}\n</code></pre>\n\n<p>And from there, we can simplify even further by combining the two parts.</p>\n\n<pre><code>function concatenationsSum3(a) {\n var lowSum = 0;\n var offsetSum = 0;\n for (var i = 0; i &lt; a.length; i++) {\n lowSum += a[i];\n\n var size = a[i].toString().length;\n var offset = iPower(10, size);\n offsetSum += offset;\n }\n\n return lowSum * a.length + lowSum * offsetSum;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-14T20:45:28.810", "Id": "502368", "Score": "0", "body": "Yeah, if the user puts in numbers that overflow a 32 bit integer then the implementation has to ensure that the arithmetic is done with either 64 bit integers or some kind of \"Big Int\" library. The original question didn't ask about handling pathological test cases, so I think I can forgive myself for overlooking that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-14T21:02:04.870", "Id": "502371", "Score": "0", "body": "The *32 bit integer* case has been solved by making the refactor to use Longs from the start: `var lowSum = 0L`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T19:11:38.657", "Id": "225289", "ParentId": "225228", "Score": "10" } }, { "body": "<p>Try to convert before concatenating, it may be that directly concatenating 2 integers takes longer than concatenating 2 strings</p>\n<pre><code>sum += parseInt( a[i].toString.concat(a[j].toString() );\n</code></pre>\n<p>If you are looking to improve, you could assign a variable the size of the array, so that it does not do it in each cycle.</p>\n<pre><code>n = a.length;\n\nfor (var i = 0; i &lt; n; i++)\n</code></pre>\n<p>It is better if for the conversion from Integer to String you do it previously, so you will not have to repeat conversions.</p>\n<p>A solution in Php:</p>\n<pre><code>function concatenationsSum ($a) {\n $sum = 0;\n $n = count($a);\n for ($i=0; $i &lt;$n ; $i++) { \n $a[$i] = (string)$a[$i];\n }\n foreach($a as $v1) {\n foreach ($a as $v2) {\n $sum += (int)($v1 . $v2);\n }\n }\n \n return $sum;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T07:30:54.483", "Id": "504442", "Score": "1", "body": "Welcome to CodeReview@SE. In your first code block, the best clue whether this is something to avoid or something to strive for is digesting the code in your second block - it might be easier if you stuck to JavaScript. (The name of that other, um, language is PHP (started as an acronym).)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-05T04:22:03.437", "Id": "255636", "ParentId": "225228", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T03:20:11.310", "Id": "225228", "Score": "8", "Tags": [ "javascript", "performance" ], "Title": "Sum of all possible concatenations of array values" }
225228
<p>I am writing trading software, and have written this utility function. Its purpose is to return a list of timeframes relevant to the just-elapsed time period. "Timeframe" here means bar or candle period.</p> <p>E.g if time has just struck UTC 10:30am, the returned list will contain "1m", "3m", "5m", "m15" and "30m" strings, as those are the candles or bars that have just closed.</p> <p>The first minute of a new day or week will add daily/weekly/monthly timeframe strings. </p> <p>Timeframes in use are 1, 3, 5, 15 and 30 mins, 1, 2, 3, 4, 6, 8 and 12 hours, 1, 2 and 3 days, as well as weekly and monthly.</p> <p><strong>Is there a more elegant, less verbose way to achieve this?</strong></p> <p>Note: the output could also be integers instead of strings, where each timeframe is expressed as its total number of minutes.</p> <pre><code>def get_timeframes(self): timestamp = datetime.datetime.utcnow() timeframes = ["1m"] # 3 minute bars for x in range(0, 20): val = x * 3 if timestamp.minute == val: timeframes.append("3m") # 5 minute bars for x in range(0, 12): val = x * 5 if timestamp.minute == val: timeframes.append("5m") # 15 minute bars for x in range(0, 4): val = x * 15 if timestamp.minute == val: timeframes.append("15m") # 30 minute bars for x in range(0, 2): val = x * 30 if timestamp.minute == val: timeframes.append("30m") # 1 hour bars if timestamp.minute == 0: timeframes.append("1h") # 2 hour bars if timestamp.minute == 0 &amp; timestamp.hour % 2 == 0: timeframes.append("2h") # 3 hour bars if timestamp.minute == 0 &amp; timestamp.hour % 3 == 0: timeframes.append("3h") # 4 hour bars if timestamp.minute == 0 &amp; timestamp.hour % 4 == 0: timeframes.append("4h") # 6 hour bars if timestamp.minute == 0 &amp; timestamp.hour % 6 == 0: timeframes.append("6h") # 8 hour bars if timestamp.minute == 0 &amp; timestamp.hour % 8 == 0: timeframes.append("8h") # 12 hour bars if timestamp.minute == 0 &amp; timestamp.hour % 12 == 0: timeframes.append("12h") # 1 day bars if timestamp.minute == 0 &amp; timestamp.hour == 0: timeframes.append("1d") # 2 day bars if ( timestamp.minute == 0 &amp; timestamp.hour == 0 &amp; timestamp.day % 2 == 0): timeframes.append("2d") # 3 day bars if ( timestamp.minute == 0 &amp; timestamp.hour == 0 &amp; timestamp.day % 3 == 0): timeframes.append("3d") # weekly bars if ( timestamp.minute == 0 &amp; timestamp.hour == 0 &amp; calendar.day_name[date.today().weekday()] == "Monday"): timeframes.append("1w") return timeframes </code></pre>
[]
[ { "body": "<p>I think you should separate the computation in three different functions, one for minutes, one for hours, and one for days. And generalize each of these functions, so they can be used for other time frames if you ever decide to change them.</p>\n\n<h2>Minutes</h2>\n\n<p>You can specify an extra parameter in <code>range()</code>, the <code>step</code>: how much is added every iteration. With this the method to check a minute time frame is quite simple:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def minute_timeframe(minutes, timestamp, timeframes):\n for x in range(0, 60, minutes):\n if timestamp.minute == x:\n timeframes.append(f\"{minutes}m\")\n</code></pre>\n\n<p>Since your tags say you use Python 3, I used <a href=\"https://docs.python.org/3/reference/lexical_analysis.html#f-strings\" rel=\"nofollow noreferrer\">formatted string literals</a>.</p>\n\n<h2>Hours</h2>\n\n<p>Be careful! You are using the <code>&amp;</code> operator, which in Python is the <code>binary and</code> operation. Since what you want is probably the logical and (i.e. this is true and the other is true), use the <code>and</code> keyword (same for <code>or</code> and <code>not</code>).</p>\n\n<p>By looking at your implementation of hour timeframes, it's pretty easy to generalize:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def hour_timeframe(hours, timestamp, timeframes):\n if timestamp.minute == 0 and timestamp.hour % hours == 0:\n timeframes.append(f\"{hours}h\")\n</code></pre>\n\n<h2>Days</h2>\n\n<p>The same happens for generalizing days. I must comment though, that your original does not seem to follow the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8 Style</a> for the indentations on that part of the code. You also do not need the parenthesis surrounding the if condition.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def day_timeframe(days, timestamp, timeframes):\n if timestamp.minute == 0 and timestamp.hour == 0 and timestamp.day % days == 0:\n timeframes.append(f\"{days}d\")\n</code></pre>\n\n<h2>Final result</h2>\n\n<p>Now that our functions are generalized, in my opinion what would be best is to store a list of the different timeframes you want to use, that way adding new ones or changing them is simple. This is the final function:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># Constants go in ALL_CAPS\nMINUTE_TIMEFRAMES = [3, 5, 15, 30]\nHOUR_TIMEFRAMES = [1, 2, 3, 4, 6, 8]\nDAY_TIMEFRAMES = [1, 2, 3]\n\ndef get_timeframes(self):\n timestamp = datetime.datetime.utcnow()\n timeframes = [\"1m\"]\n\n for x in MINUTE_TIMEFRAMES:\n minute_timeframe(x, timestamp, timeframes)\n\n for x in HOUR_TIMEFRAMES:\n hour_timeframe(x, timestamp, timeframes)\n\n for x in DAY_TIMEFRAMES:\n day_timeframe(x, timestamp, timeframes)\n\n # Format it correctly and use 'and'\n if (timestamp.minute == 0 and timestamp.hour == 0 and\n calendar.day_name[date.today().weekday()] == \"Monday\"):\n timeframes.append(\"1w\")\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T22:15:17.600", "Id": "437440", "Score": "0", "body": "Thanks @eric.m, much cleaner." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T08:00:33.840", "Id": "225246", "ParentId": "225232", "Score": "1" } } ]
{ "AcceptedAnswerId": "225246", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T04:14:50.387", "Id": "225232", "Score": "1", "Tags": [ "python", "performance", "python-3.x", "finance" ], "Title": "Return timeframes relevant to just-elapsed time period (financial/trading context)" }
225232
<p>I applied for a job, and the prospective employer sent me the following HackerRank problem, which cannot be found in the public area.</p> <p>There is a lottery with <code>n</code> coupons and <code>n</code> people take a part in it. Each person picks exactly one coupon. Coupons are numbered from <code>a</code> to <code>b</code>. The winner of lottery is any person who owns a coupon with the sum of digits written on it equal to s, and if there are more such people, then the prize is split equally among them. Determine s in such a way the is at least one winner and the prize is split among the most people.</p> <p>How many ways can the required sum be chosen so that the lottery is split among the maximum number of people?</p> <p>For example, there are <code>n = 10</code> participants in the lottery coupons are numbered from <code>a = 1</code> to <code>b = 10</code>. The sums of the digits of each coupon are <code>[1,2,3,4,5,6,7,8,9,1]</code>. Any sum from 2 to 9 has only 1 winner. If the sum of digit is 1, however, there are two winners, tickets 1 and 10. The answer is <code>s = 1</code> with two participants winning the lottery. </p> <p><strong>Function Description</strong></p> <p>Complete the function <code>waysToChooseSum</code>. The function must return an array of <code>Long</code> integers with 2 elements: the total number of ways to choose sum so that maximum possible participants win the lottery and the number of participants who will win the lottery.</p> <p><code>waysToChooseSum</code> has the following parameter(s): <code>a</code> - a <code>Long</code> integer, that starting index of lottery coupons, <code>b</code> - a <code>Long</code> integer, that ending index of lottery coupons</p> <p><strong>Constraints</strong></p> <ul> <li>1 &lt;= a &lt; b &lt;= 10^18</li> </ul> <p><strong>Solution</strong></p> <pre><code>fun Long.sum(): Long { var sum = 0L for(ch in toString()) sum += ch.toString().toLong() return sum } fun waysToChooseSum(a: Long, b: Long): Array&lt;Long&gt; { val sums = HashMap&lt;Long, Long&gt;() var variants = 0L var maxPeople = 1L for(i in a..b) { val sum = i.sum() if(!sums.containsKey(sum)) sums[sum] = 1 else { sums[sum] = sums[sum]!!.plus(1) if(sums[sum]!! &gt; maxPeople) { variants = 0 maxPeople = sums[sum]!! } } if(sums[sum]!! == maxPeople) variants++ } return arrayOf(variants, maxPeople) } </code></pre> <p>I'm trying to improve performance, correctness in unanticipated cases in the solution above to successfully pass programming test. Any advice or potential issues in the code? </p> <p><strong>Sample Case 1</strong></p> <p>Sample Input</p> <p><code>a = 1, b = 5</code></p> <p>Sample Output</p> <pre><code>[5, 1] </code></pre> <p><em>The sum of digits for all participants is different, i.e. <code>[1,2,3,4,5]</code>, hence there are 5 ways to choose the sum with 1 winner each.</em></p> <p><strong>Sample Case 2</strong></p> <p>Sample Input</p> <p><code>a = 3, b = 12</code></p> <p>Sample Output</p> <pre><code>[1, 2] </code></pre> <p><em>The sum of digits of 10 numbers are <code>[3,4,5,6,7,8,9,1,2,3]</code>. The sum 3 is seen twice. So, there is 1 way to choose, with the maximum of 2 winners.</em></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T06:18:17.093", "Id": "437246", "Score": "1", "body": "The description is wrong. The first sentence says \"there are exactly \\$n\\$ coupons\". Therefore, if \\$n=5\\$, the digit sums of \"each coupon\" must contain 5 elements as well, not 10." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T06:24:29.177", "Id": "437247", "Score": "1", "body": "What was the result of running your code with \\$a=10^{17}, b=10^{18}\\$? In other words: you need to solve this problem on an elegant mathematical level, not by trying out all combinations. \\$10^{18}\\$ is a huge number." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T06:27:24.913", "Id": "437248", "Score": "0", "body": "@RolandIllig I just copy text from HackerRank which means they did mistake. Could you advice how to solve this problem on mathematical level, where to look for solution? Give some theory and key how to solve it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T06:39:46.773", "Id": "437249", "Score": "0", "body": "No, I have no idea how to solve this efficiently. I just noticed that your current code takes too long." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T06:40:24.707", "Id": "437250", "Score": "1", "body": "If you took the task from HackerRank, you should add a link to the original task." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T06:47:14.740", "Id": "437251", "Score": "0", "body": "@RolandIllig no original link because this code challenge was sent by employer and link is private and already expired since I already passed the test, so I just try to improve my skills to solve such puzzles like this one more efficiently for my future coding/technical interviews." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T14:57:07.387", "Id": "437326", "Score": "0", "body": "Can you clarify what is meant by *\"the total number of ways to choose sum so that maximum possible participants win the lottery\"* ? Can you give a couple of example inputs and outputs?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T22:13:42.927", "Id": "437437", "Score": "0", "body": "If this task was sent to you privately, you just cannot say \"I just copy text from HackerRank\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T11:47:13.680", "Id": "437510", "Score": "0", "body": "@RolandIllig then what I should say?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T11:51:05.153", "Id": "437511", "Score": "0", "body": "@SimonForsberg Sample input `a = 1, b = 5`, sample output `[5,1]`. Another sample input `a = 3, b = 12`, output `[1,2]`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T16:41:40.840", "Id": "437580", "Score": "0", "body": "@Arsenius describe the situation as precisely as possible, so that someone who has no knowledge about your personal situation can fully understand it. In this particular case, it might be: \"I applied for a job, and the prospective employer sent me the following HackerRank problem, which cannot be found in the public area\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T19:11:21.727", "Id": "437610", "Score": "0", "body": "@Arsenius Edit those inputs/outputs to the question please." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T10:33:34.527", "Id": "437656", "Score": "0", "body": "@SimonForsberg done" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T10:35:57.900", "Id": "437657", "Score": "0", "body": "@RolandIllig I edited question" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T13:25:16.333", "Id": "437675", "Score": "0", "body": "@Arsenius Thanks for editing the question. One open item remains though. The constraints are given as \\$1\\le a\\lt b \\le 10^{18}\\$. What does your program output for this range, and how did you verify this? Until you can answer this question, I could simply say that your program does not satisfy all requirements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T10:52:50.570", "Id": "437776", "Score": "0", "body": "@RolandIllig the problem is when I try to run this code `waysToChooseSum(1,1000000000000000000L)` the execution will take maybe few month to accomplish if not years" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "16", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T06:11:36.603", "Id": "225239", "Score": "0", "Tags": [ "algorithm", "programming-challenge", "kotlin" ], "Title": "Digit Sum find number of ways and max people" }
225239
<p>I wrote the following working code, which I just can't stomach:</p> <pre><code>var data = [ { id: 0, isHeading: true, description: "A heading" }, { id: 1, isHeading: false, description: "Blah 1" }, { id: 2, isHeading: false, description: "Blah 2" }, { id: 3, isHeading: true, description: "A heading" }, { id: 4, isHeading: false, description: "Blah 3" }, { id: 5, isHeading: false, description: "Blah 4" }, { id: 7, isHeading: false, description: "Blah 5" }, { id: 8, isHeading: false, description: "Blah 6" }, { id: 9, isHeading: true, description: "A heading" }, { id: 10, isHeading: false, description: "Blah 7" }, { id: 11, isHeading: false, description: "Blah 8" }, { id: 12, isHeading: false, description: "Blah 9" }, { id: 13, isHeading: true, description: "A heading" }, { id: 14, isHeading: false, description: "Blah 10" }, { id: 15, isHeading: false, description: "Blah 11" }, { id: 16, isHeading: true, description: "A heading" }, { id: 17, isHeading: false, description: "Blah 12" }, { id: 18, isHeading: false, description: "Blah 13" }, { id: 19, isHeading: false, description: "Blah 14" } ] function getLines (headingId) { var r = [] var inThere = false for (let line of data) { if (line.isHeading) { if(line.id === headingId) { inThere = true continue } else if (line.id !== headingId &amp;&amp; inThere) { return r } } if (inThere) r.push(line) } return r } getLines(9) </code></pre> <p>Basically, it's taking a chunk of a list; it's a state automaton where the <code>inThere</code> state is set by a matching heading ID, and the routine is done when either there are no more items, or a new heading comes up.</p> <p>Is there a much better way of writing this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T08:21:38.927", "Id": "437267", "Score": "0", "body": "It would be nice if you could replace the _Blah_ dummy data with some real data from your working environment, so we get an idea how you would use this function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T17:33:52.283", "Id": "437365", "Score": "0", "body": "@200_success you suggest a state machine solution to this problem?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T17:35:46.633", "Id": "437366", "Score": "0", "body": "@dfhwze No, I'm just tagging the question according to the author's own characterization of the code as a state automaton." } ]
[ { "body": "<h3>Review</h3>\n\n<ul>\n<li>Your function skips until the heading is found and than takes element until the next heading. Perhaps we could split these methods up to make them <strong>reusable</strong>. </li>\n<li>Try to avoid <code>var</code> (undesired scope), prefer <code>let</code> or <code>const</code> instead.</li>\n<li>Prefer a Tree data structure over flat list for hierarchical data.</li>\n</ul>\n\n<h3>Refactored for Reusability</h3>\n\n<p>Skip items while a predicate is true.</p>\n\n<pre><code> function skipWhile(items, predicate) {\n let ok = false;\n return items.filter((value, index, array) =&gt; {\n if (!ok &amp;&amp; !predicate(value)){\n ok = true;\n }\n return ok;\n });\n };\n</code></pre>\n\n<p>Take items while a predicate is true.</p>\n\n<pre><code> function takeWhile(items, predicate) {\n let ok = true;\n return items.filter((value, index, array) =&gt; {\n if (ok &amp;&amp; !predicate(value)){\n ok = false;\n }\n return ok;\n });\n };\n</code></pre>\n\n<p>The OP method:</p>\n\n<pre><code> function getLines (headingId) {\n let lines = skipWhile(data, v =&gt; v.id != headingId);\n lines.shift(); // we don't want the heading\n lines = takeWhile(lines, v =&gt; !v.isHeading);\n return lines;\n }\n</code></pre>\n\n<p>And verification:</p>\n\n<pre><code> console.log(getLines(9).map(x =&gt; x.description))\n</code></pre>\n\n<p>Yielding:</p>\n\n<blockquote>\n <p>(3) [ \"Blah 7\" , \"Blah 8\" , \"Blah 9\" ]</p>\n</blockquote>\n\n<p>You could also create these methods as prototype extensions on <code>Array</code> or refactor them to become generator functions (with <em>yield</em> syntax). I am sure these methods could get optimized for performance somehow.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T08:06:43.920", "Id": "225247", "ParentId": "225243", "Score": "2" } }, { "body": "<ul>\n<li>Unless you know of the top of your head every instance that automatic semicolon insertion can fail (there are a few) you should use semicolons.</li>\n<li>Always use <code>{}</code> to delimit a statement block, even if it is one line. It is very easy to overlook the missing <code>{}</code> if you make changes and its not easy to spot the error when you look for the bug.</li>\n<li>The array <code>r</code> can be a constant</li>\n<li>The variable line in he loop can be a constant;</li>\n<li><code>r</code> is a very poor name, maybe <code>result</code> would be better?</li>\n<li><code>inThere</code> is a very poor name, maybe <code>headingFound</code> has more meaning?</li>\n<li><code>getLines</code> has no meaning, maybe <code>sectionByHeadingId</code> ( I don't know what it represents so the section part is a guess)</li>\n<li><p>You are accessing a global scoped object <code>data</code> try to avoid such access by passing the array as a argument</p></li>\n<li><p>Avoid undue complication. </p>\n\n<ul>\n<li>Don't execute statement if not needed. The statement <code>if (inThere)</code> can be <code>} else if (inThere)</code> </li>\n<li>Don't repeat the same return if there is a shorter way. Replace the inner return with <code>break</code>, </li>\n<li>Don't test a state you know. You test <code>if(line.id === headingId) {</code> then in the following <code>else</code> you check its state again <code>else if (line.id !== headingId</code> The first statement has already determined if the line is heading id you can only get to the else if <code>line.id !== headingId</code> is true</li>\n</ul></li>\n</ul>\n\n<h2>Example</h2>\n\n<p>Rewrites your code</p>\n\n<pre><code>function sectionByHeadingId(sections, headingId) {\n const result = [];\n var headingFound = false;\n for (const line of sections) {\n if (line.isHeading) {\n if (line.id === headingId) { \n headingFound = true;\n } else if (headingFound) { \n break;\n }\n } else if (headingFound) { \n result.push(line);\n }\n }\n return result;\n}\nsectionByHeadingId(data, 9);\n</code></pre>\n\n<h2>Example2</h2>\n\n<p>An alternative and simpler solution by using <code>Array.findIndex</code> to find the start of the section you want. Then you need only push lines till the next heading or end of array</p>\n\n<pre><code>function sectionByHeadingId(sections, headingId) {\n const result = [];\n var idx = sections.findIndex(line =&gt; line.id === headingId) + 1;\n while (sections[idx] &amp;&amp; !sections[idx].isHeading) { \n result.push(sections[idx++]);\n }\n return result;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-11T22:12:00.310", "Id": "438885", "Score": "0", "body": "Picked this one mainly for the fantastic rewrite at the bottom. Thanks for this!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T10:37:40.240", "Id": "225254", "ParentId": "225243", "Score": "2" } } ]
{ "AcceptedAnswerId": "225254", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T07:15:35.067", "Id": "225243", "Score": "4", "Tags": [ "javascript", "array", "state-machine" ], "Title": "Extract lines under the specified heading" }
225243
<p>This is <a href="https://projecteuler.net/problem=67" rel="nofollow noreferrer">Project Euler #67: Maximum path sum II</a>:</p> <blockquote> <p>By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.</p> <p>3<br> 7 4<br> 2 4 6<br> 8 5 9 3</p> <p>That is, 3 + 7 + 4 + 9 = 23.</p> <p>Find the maximum total from top to bottom in <a href="https://projecteuler.net/project/resources/p067_triangle.txt" rel="nofollow noreferrer">triangle.txt</a> (right click and 'Save Link/Target As...'), a 15K text file containing a triangle with one-hundred rows.</p> <p>NOTE: This is a much more difficult version of <a href="https://projecteuler.net/problem=18" rel="nofollow noreferrer">Problem 18</a>. It is not possible to try every route to solve this problem, as there are 2<sup>99</sup> altogether! If you could check one trillion (10<sup>12</sup>) routes every second it would take over twenty billion years to check them all. There is an efficient algorithm to solve it. ;o)</p> </blockquote> <p>I previously posted a solution to problem 18 using a greedy algorithm, here's the optimal solution using bottom up recursion.</p> <pre><code>from time import time def get_triangle(triangle_filename): """Return a list of lists containing rows of the triangle.""" triangle = open(triangle_filename).read().split('\n') triangle = [[int(number) for number in row.split()] for row in triangle] return triangle def maximize_triangle(triangle, start_index=-1): """Return the maximum triangle path sum(bottom up).""" if start_index == - len(triangle): return triangle[0][0] for index in range(len(triangle[start_index]) - 1): maximum = max(triangle[start_index][index], triangle[start_index][index + 1]) triangle[start_index - 1][index] += maximum return maximize_triangle(triangle, start_index - 1) if __name__ == '__main__': start_time = time() triangle_file = get_triangle('p067_triangle.txt') print(f'Maximum Path: {maximize_triangle(triangle_file)}') print(f'Time: {time() - start_time} seconds.') </code></pre>
[]
[ { "body": "<p>The algorithm is very efficient, your program computes the result in fractions of a second. </p>\n\n<p>Reading the file into a nested list can be simplified to</p>\n\n<pre><code>def get_triangle(triangle_filename):\n \"\"\"Return a list of lists containing rows of the triangle.\"\"\"\n triangle = [[int(number) for number in row.split()]\n for row in open(triangle_filename)]\n return triangle\n</code></pre>\n\n<p>because <code>open()</code> returns a file object that can be iterated over. As an additional advantage, no empty list is appended. Your reading function actually returns</p>\n\n<pre><code>[[59], [73, 41], [52, 40, 9], ... , []]\n</code></pre>\n\n<p>Here</p>\n\n<pre><code>triangle_file = get_triangle('p067_triangle.txt')\n</code></pre>\n\n<p>I find the naming confusing: The return value is not a file, and the nested list is called <code>triangle</code> everywhere else. Therefore I would change that here as well:</p>\n\n<pre><code>triangle = get_triangle('p067_triangle.txt')\n</code></pre>\n\n<p>In the main routine </p>\n\n<pre><code>def maximize_triangle(triangle, start_index=-1):\n</code></pre>\n\n<p>I would use a nested loop instead of recursion. That makes the <code>start_index</code> parameter with its default value obsolete, and the logic is easier to understand (in my opinion). Instead of <code>start_index</code> and <code>index</code> I would use <code>row</code> and <code>col</code> as variable names. Finally the function does not “maximize a triangle” but computes the “maximal path sum,” so let's name it accordingly:</p>\n\n<pre><code>def maximal_path_sum(triangle):\n \"\"\"Return the maximum triangle path sum(bottom up).\"\"\"\n # Starting with the last row ...\n for row in range(len(triangle) - 1, 0, -1):\n # ... add maximum of adjacent entries to the corresponding entry\n # in the preceding row:\n for col in range(len(triangle[row]) - 1):\n maximum = max(triangle[row][col], triangle[row][col + 1])\n triangle[row - 1][col] += maximum\n return triangle[0][0]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T11:09:09.347", "Id": "225259", "ParentId": "225248", "Score": "3" } }, { "body": "<p>When you <code>open()</code> a resource, such as a file, it is important to <code>close()</code> it. Failure to close the resource can result in other processes not being able to access it until the garbage collector finally determines the resource is not longer in use.</p>\n\n<p>The <code>with</code> statement is useful when opening auto-closable resources, as it will ensure the resource is closed even if execution abruptly exits with an exception.</p>\n\n<pre><code>with open(triangle_filename) as file:\n # ... use file here\n# ... file is automatically closed here\n</code></pre>\n\n<hr>\n\n<p>Your bottom-up solution requires reading in the entire file, so that you can get and start the process with the last row of the triangle. As such, your solution will be <span class=\"math-container\">\\$O(n^2)\\$</span> in memory.</p>\n\n<p>There is a top-down solution, which will allow you to process from the top of the triangle down to the bottom. This means you don't need to read-in and store the entire triangle; you can process it one line at a time. As a result, a solution can be written in <span class=\"math-container\">\\$O(n)\\$</span> memory.</p>\n\n<pre><code>def pe87(filename):\n\n prev = []\n\n with open(filename) as file:\n for line in file:\n prev = [0] + prev + [0]\n curr = map(int, line.split())\n prev = [max(a, b) + c for a, b, c in zip(prev[:-1], prev[1:], curr)]\n\n return max(prev)\n</code></pre>\n\n<p>I'm maintaining the previous maximum partial sum in <code>prev</code>. For each new row, I'm prepending and appending a <code>0</code> value, as a convenience for the next step.</p>\n\n<p>At any given row:</p>\n\n<ul>\n<li><code>prev[:-1]</code> is the list of previous maximum partial sums, with a <code>0</code> at the start</li>\n<li><code>prev[1:]</code> is the list of previous maximum partial sums, with a <code>0</code> at the end</li>\n<li><code>curr</code> is the list of values on the current row.</li>\n<li>All 3 list are the same length</li>\n</ul>\n\n<p>If we take those lists, and <code>zip</code> them together, we get a list of tuples. Each tuple contains a previous maximum partial sum from the row above (or zero if this is the first tuple), a different previous maximum partial sum from the row above (or zero if this is the last tuple), and the value from the current row. Adding the current value to the maximum of the two previous maximum partial sums will produce the new maximum partial sum over all paths leading to this cell of the triangle.</p>\n\n<p>The maximum value from the maximum partial sums of the last row is the answer.</p>\n\n<p>No recursion is necessary.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T23:43:33.407", "Id": "225308", "ParentId": "225248", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T09:14:42.210", "Id": "225248", "Score": "3", "Tags": [ "python", "beginner", "python-3.x", "programming-challenge" ], "Title": "Project Euler # 67 Maximum path sum II (Bottom up) in Python" }
225248
<p>I'm an intermediate Java programmer trying to learn the basics of C++.</p> <p>Thus, I decided to write "Conway's game of life" as my second C++ program (I already wrote a Mandelbrot image generator). It was a fun exercise but I struggled a lot with structuring my program and dealing with pointers and references.</p> <p>It's a bit of a mishmash because I wanted to try to learn how to use both regular pointers and smart pointers, and I also implemented the <code>Grid</code> class to practice how to use templates and lambdas.</p> <p>Never used SFML, never written a game. Never written a game loop so I don't really understand what I have done and all the documentation out there about game loops was difficult for me to understand.</p> <p>All in all, it was a fun experience and please give me tips on structure, improvements, what was good, what was bad, should I give up and take up another hobby?</p> <p>I would really like to become a better C++ developer.</p> <p><a href="https://github.com/Tandolf/Game-Of-Life" rel="nofollow noreferrer">Git repository for source code</a></p> <p><strong>main.cpp</strong></p> <pre><code>int main() { Game game(2048, 1024, "Game Of Life"); game.run(); } </code></pre> <p><strong>Game.cpp</strong></p> <pre><code>#include &lt;SFML/System/Clock.hpp&gt; #include &lt;SFML/Graphics.hpp&gt; #include &lt;time.h&gt; #include &lt;iostream&gt; #include "LifeState.hpp" #include "Game.hpp" const int Game::FPS = 25; const int Game::SKIP_TICKS = 1000 / FPS; Game::Game(const int width, const int height, const std::string title) { this-&gt;data-&gt;window.create(sf::VideoMode(width, height), title); this-&gt;data-&gt;assets.loadTexture("tile", "assets/tile.png"); this-&gt;data-&gt;assets.loadTexture("tile2", "assets/tile2.png"); this-&gt;lifeState.init(this-&gt;data); }; void Game::run(){ int nextGameTick = clock.getElapsedTime().asMilliseconds(); struct timespec tim, tim2; tim.tv_sec = 0; tim.tv_nsec = 0; while (this-&gt;data-&gt;window.isOpen()) { updateGame(); displayGame(); nextGameTick += SKIP_TICKS; tim.tv_nsec = (nextGameTick - clock.getElapsedTime().asMilliseconds()); if(tim.tv_nsec &gt;= 0){ nanosleep(&amp;tim, &amp;tim2); } } } void Game::updateGame(){ this-&gt;lifeState.update(); sf::Event event; while (this-&gt;data-&gt;window.pollEvent(event)) { if (event.type == sf::Event::Closed) { this-&gt;data-&gt;window.close(); } if(event.type == sf::Event::MouseButtonPressed) { auto mouse_pos = sf::Mouse::getPosition(this-&gt;data-&gt;window); sf::Vector2&lt;float&gt; translated_pos = this-&gt;data-&gt;window.mapPixelToCoords(mouse_pos); this-&gt;lifeState.toggle(translated_pos); std::cout &lt;&lt; "mouse clicked at: " &lt;&lt; event.mouseButton.x &lt;&lt; " " &lt;&lt; event.mouseButton.y &lt;&lt; std::endl; } if(event.type == sf::Event::KeyReleased) { if (event.key.code == sf::Keyboard::Space) { if(lifeState.isGenerating) { this-&gt;lifeState.stop(); } else { this-&gt;lifeState.start(); } } } } } void Game::displayGame(){ this-&gt;data-&gt;window.clear(sf::Color::Black); this-&gt;lifeState.draw(); this-&gt;data-&gt;window.display(); } </code></pre> <p><strong>AssetManager.cpp</strong></p> <pre><code>#include "AssetManager.hpp" void AssetManager::loadTexture(std::string name, std::string filename) { sf::Texture texture; if(texture.loadFromFile(filename)) { this-&gt;textures[name] = texture; } } sf::Texture *AssetManager::getTexture(std::string name) { return &amp;this-&gt;textures.at(name); } </code></pre> <p><strong>LifeState.cpp</strong></p> <pre><code>#include &lt;memory&gt; #include &lt;iostream&gt; #include "LifeState.hpp" #include &lt;SFML/System/Clock.hpp&gt; void LifeState::init(GameDataRef &amp;data) { this-&gt;data = data; auto size = this-&gt;data-&gt;assets.getTexture("tile")-&gt;getSize(); int width = this-&gt;data-&gt;window.getSize().x / size.x; int height = this-&gt;data-&gt;window.getSize().y / size.y; auto boolean = [](int x, int y, int height, int width) { return false; }; this-&gt;currentState.fill(height, width, boolean); this-&gt;nextState.fill(height, width, boolean); int posX = 0; int posY = 0; sf::Texture* tile = this-&gt;data-&gt;assets.getTexture("tile"); this-&gt;sprites.fill(height, width, [tile, posX, posY](int x, int y, int height, int width) mutable { sf::Sprite sprite; sprite.setTexture(*tile); sprite.setTextureRect(sf::IntRect(0, 0, tile-&gt;getSize().x, tile-&gt;getSize().y)); sprite.setPosition(posX, posY); posX += tile-&gt;getSize().x; if(y == width-1) { posY += tile-&gt;getSize().y; posX = 0; } return sprite; }); this-&gt;lastTime = 0; }; void LifeState::toggle(sf::Vector2&lt;float&gt; translated_pos) { this-&gt;sprites.forEach([&amp;translated_pos, this](sf::Sprite sprite, int x, int y){ if(sprite.getGlobalBounds().contains(translated_pos)) { if(this-&gt;currentState.get(x, y)) { this-&gt;currentState.set(x, y, false); } else { this-&gt;currentState.set(x, y, true); } } }); } void LifeState::draw() { sf::Texture* tile = this-&gt;data-&gt;assets.getTexture("tile"); sf::Texture* tile2 = this-&gt;data-&gt;assets.getTexture("tile2"); sprites.forEach([this, tile, tile2](sf::Sprite sprite, int x, int y){ if(this-&gt;currentState.get(x, y)) { sprite.setTexture(*tile2); } else { sprite.setTexture(*tile); } this-&gt;data-&gt;window.draw(sprite); }); } void LifeState::start() { std::cout &lt;&lt; "Started simulation" &lt;&lt; std::endl; isGenerating = true; } void LifeState::stop() { std::cout &lt;&lt; "Stopped simulation" &lt;&lt; std::endl; isGenerating = false; } void LifeState::update() { if(isGenerating) { double time_counter = 0; int thisTime = clock.getElapsedTime().asSeconds(); time_counter += (double)(thisTime - this-&gt;lastTime); if(time_counter &gt; 0) { currentState.forEach([this](bool value, int x, int y) { const int neighbours = this-&gt;getNeighbours(x, y); this-&gt;updateCell(x, y, neighbours); }); this-&gt;currentState = nextState; } this-&gt;lastTime = thisTime; } } int LifeState::getNeighbours(const int i, const int j) { int neighbours = 0; if(i == this-&gt;currentState.sizeX()-1 &amp;&amp; j == currentState.sizeY(i)-1) { if(this-&gt;currentState.get(i-1, j)) { neighbours++; } if(currentState.get(i-1, j-1)) { neighbours++; } if(currentState.get(i, j-1)) { neighbours++; } return neighbours; } if(i == this-&gt;currentState.sizeX()-1 &amp;&amp; j &gt; 0) { if(this-&gt;currentState.get(i, j-1)) { neighbours++; } if(this-&gt;currentState.get(i-1, j-1)) { neighbours++; } if(this-&gt;currentState.get(i-1, j)) { neighbours++; } if(this-&gt;currentState.get(i-1, j+1)) { neighbours++; } if(this-&gt;currentState.get(i, j+1)) { neighbours++; } return neighbours; } if(i == this-&gt;currentState.sizeX()-1 &amp;&amp; j == 0) { if(this-&gt;currentState.get(i-1, j)) { neighbours++; } if(this-&gt;currentState.get(i-1, j+1)) { neighbours++; } if(this-&gt;currentState.get(i, j+1)) { neighbours++; } return neighbours; } if(i == 0 &amp;&amp; j == 0) { if(this-&gt;currentState.get(i, j+1)) { neighbours++; } if(this-&gt;currentState.get(i+1, j+1)) { neighbours++; } if(this-&gt;currentState.get(i+1, j)) { neighbours++; } return neighbours; } if(i == 0 &amp;&amp; j == this-&gt;currentState.sizeY(i)-1) { if(this-&gt;currentState.get(i, j-1)) { neighbours++; } if(this-&gt;currentState.get(i+1, j-1)) { neighbours++; } if(this-&gt;currentState.get(i+1, j)) { neighbours++; } return neighbours; } if(i == 0 &amp;&amp; j &gt; 0) { if(this-&gt;currentState.get(i, j+1)) { neighbours++; } if(this-&gt;currentState.get(i+1, j+1)) { neighbours++; } if(this-&gt;currentState.get(i+1, j)) { neighbours++; } if(this-&gt;currentState.get(i+1, j-1)) { neighbours++; } if(this-&gt;currentState.get(i, j-1)) { neighbours++; } return neighbours; } if(i &gt; 0 &amp;&amp; j == 0) { if(this-&gt;currentState.get(i-1, j)) { neighbours++; } if(this-&gt;currentState.get(i-1, j+1)) { neighbours++; } if(this-&gt;currentState.get(i, j+1)) { neighbours++; } if(this-&gt;currentState.get(i+1, j+1)) { neighbours++; } if(this-&gt;currentState.get(i+1, j)) { neighbours++; } return neighbours; } if(i &gt; 0 &amp;&amp; j == this-&gt;currentState.sizeY(i)-1) { if(this-&gt;currentState.get(i-1, j-1)) { neighbours++; } if(this-&gt;currentState.get(i-1, j)) { neighbours++; } if(this-&gt;currentState.get(i, j-1)) { neighbours++; } if(this-&gt;currentState.get(i+1, j-1)) { neighbours++; } if(this-&gt;currentState.get(i+1, j)) { neighbours++; } return neighbours; } if(i &gt; 0 &amp;&amp; j &gt; 0) { if(this-&gt;currentState.get(i-1, j)) { neighbours++; } if(this-&gt;currentState.get(i-1, j+1)) { neighbours++; } if(this-&gt;currentState.get(i, j+1)) { neighbours++; } if(this-&gt;currentState.get(i+1, j+1)) { neighbours++; } if(this-&gt;currentState.get(i+1, j)) { neighbours++; } if(this-&gt;currentState.get(i+1, j-1)) { neighbours++; } if(this-&gt;currentState.get(i, j-1)) { neighbours++; } if(this-&gt;currentState.get(i-1, j-1)) { neighbours++; } return neighbours; } return neighbours; } void LifeState::updateCell(const int height, const int width, const int neighbours) { const bool isActive = this-&gt;currentState.get(height, width); if(neighbours &lt; 2 &amp;&amp; isActive) { this-&gt;nextState.set(height, width, false); return; } else if((neighbours == 2 || neighbours == 3) &amp;&amp; isActive) { this-&gt;nextState.set(height, width, true); return; } else if(neighbours &gt; 3 &amp;&amp; isActive) { this-&gt;nextState.set(height, width, false); return; } else if(isActive == false &amp;&amp; neighbours == 3) { this-&gt;nextState.set(height, width, true); return; } } </code></pre> <p><strong>Grid.hpp</strong></p> <pre><code>#pragma once #include &lt;vector&gt; #include &lt;functional&gt; #include &lt;iostream&gt; template&lt;typename T&gt; class Grid { private: std::vector&lt;std::vector&lt;T&gt;&gt; data; public: void fill(int x, int y, const std::function&lt;T(int, int, int, int)&gt; &amp;func); std::size_t sizeX(); std::size_t sizeY(int x); void forEach(const std::function&lt;void(T, int, int)&gt; &amp;func); T get(int x, int y); void set(int x, int y, T value); }; template&lt;typename T&gt; void Grid&lt;T&gt;::fill(int x, int y, const std::function&lt;T(int, int, int, int)&gt; &amp;func) { data.reserve(x); for (int i = 0; i &lt; x; i++) { std::vector&lt;T&gt; v; v.reserve(y); data.push_back(v); std::cout &lt;&lt; y &lt;&lt; std::endl; for (int j = 0; j &lt; y; j++) { T value = func(i, j, data.size(), y); this-&gt;data.at(i).push_back(value); } } } template&lt;typename T&gt; std::size_t Grid&lt;T&gt;::sizeX() { return data.size(); } template&lt;typename T&gt; std::size_t Grid&lt;T&gt;::sizeY(int x) { return data.at(x).size(); } template&lt;typename T&gt; void Grid&lt;T&gt;::forEach(const std::function&lt;void(T, int, int)&gt; &amp;func) { for (int i = 0; i &lt; data.size(); i++) { for (int j = 0; j &lt; data.at(i).size(); j++) { func(data.at(i).at(j), i, j); } } } template&lt;typename T&gt; T Grid&lt;T&gt;::get(int x, int y) { return data.at(x).at(y); } template&lt;typename T&gt; void Grid&lt;T&gt;::set(int x, int y, T value) { data.at(x).at(y) = value; } </code></pre> <p>I have omitted some of the header files, but you can find them all in the source code repository.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T10:31:43.303", "Id": "437278", "Score": "1", "body": "oh wow didn't even notice that, i have changed it to `include`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T11:35:23.300", "Id": "437292", "Score": "1", "body": "Take a look at [The Definitive C++ Book Guide and List](https://stackoverflow.com/q/388242) on Stack Overflow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T12:28:51.313", "Id": "437300", "Score": "0", "body": "thank you for the book tips! much appreciated" } ]
[ { "body": "<p>Welcome to C++! Java and C++ are quite different languages with different programming idioms and techniques, so hopefully this review will help you get better in C++.</p>\n\n<h1><code>main.cpp</code></h1>\n\n<p>The first thing I noticed is that you omitted the <code>#include</code> when posting your <code>main.cpp</code> code. I checked your GitHub repository and noticed that <code>#include \"Game.hpp\"</code> is present in the <code>main.cpp</code> file. Please post complete code in the future.</p>\n\n<p>When I see the line</p>\n\n<pre><code>Game game(2048, 1024, \"Game Of Life\");\n</code></pre>\n\n<p>I wonder which of the two numbers is the width and which is the height (if they are supposed to be dimensions at all) and what the <code>\"Game Of Life\"</code> string means. You didn't post your <code>Game.hpp</code> file, but I go ahead and check it. There is a constructor:</p>\n\n<pre><code>Game(const int width, const int height, const std::string title);\n</code></pre>\n\n<p>which answers the questions. It would be better if a reader does not need to examine another file to understand the code. In this case, a simple comment is sufficient:</p>\n\n<pre><code>// creates a 2048 x 1024 game with title \"Game Of Life\"\nGame game(2048, 1024, \"Game Of Life\");\n</code></pre>\n\n<p>This approach has drawbacks: the comment is invalidated when the code changes, and comments shouldn't be used to indicate how the code works. For more complicated cases, the <a href=\"https://isocpp.org/wiki/faq/ctors#named-parameter-idiom\" rel=\"nofollow noreferrer\">named argument idiom</a> is commonly used.</p>\n\n<h1><code>Game.cpp</code></h1>\n\n<p>You didn't actually post <code>Game.hpp</code>. I can check your code on GitHub, but this answer can only review <code>Game.cpp</code>.</p>\n\n<p>You included <code>&lt;time.h&gt;</code>. C headers of the form <code>&lt;time.h&gt;</code> are deprecated in favor of <code>&lt;ctime&gt;</code>. In fact, you should be using <code>&lt;chrono&gt;</code> instead of <code>&lt;ctime&gt;</code> in C++.</p>\n\n<pre><code>const int Game::FPS = 25;\nconst int Game::SKIP_TICKS = 1000 / FPS;\n</code></pre>\n\n<p>These two lines are (probably) definitions of static <code>const</code> variables. They can be made <code>constexpr</code> and defined directly in-class. <code>ALL_CAPS</code> identifiers are usually reserved for macros, and constants shouldn't really use them. In C++, types are used to assign values meanings. Make a type alias <code>fps_t</code> for the type of <code>fps</code>:</p>\n\n<pre><code>using fps_t = int;\n</code></pre>\n\n<p>Also, <code>skip_ticks</code> seems to be a time duration instead of a pure integer, so use <code>chrono</code>:</p>\n\n<pre><code>// in the Game class declaration\nstatic constexpr fps_t fps = 25;\nstatic constexpr auto skip_ticks = 1000ms / fps; \n</code></pre>\n\n<p>(Assumes <code>using namespace std::chrono_literals</code>.) <code>1000ms</code> is unambiguously 1000 milliseconds instead of 1000 microseconds or 1000 Minecraft ticks.</p>\n\n<p><code>this-&gt;</code> has limited use and is redundant in your case, so leave them out. This applies to all functions.</p>\n\n<p>Your constructor declares all parameters as <code>const</code>. This is not necessary. Also, <code>title</code> should be passed by <code>std::string_view</code>.</p>\n\n<p>The <code>run</code> function is where the C time facilities become a bit unhandy with <code>timespec</code> and pointers. Here's what the same code looks like when written using C++ chrono facilities: (just an idea, not tested because I am not familiar with SFML clocks)</p>\n\n<pre><code>void Game::run()\n{\n std::chrono::milliseconds nextGameTick{clock.getElapsedTime().asMilliseconds()};\n while (data-&gt;window.isOpen()) {\n updateGame();\n displayGame();\n\n nextGameTick += skip_ticks; // the units are handled properly by the type system\n\n std::chrono::milliseconds current_time{clock.getElapsedTime().asMilliseconds()};\n std::this_thread::sleep_for(nextGameTick - current_time); // more intuitive than timespec and nanosleep\n }\n}\n</code></pre>\n\n<p>This needs <code>#include &lt;chrono&gt;</code> and <code>#include &lt;thread&gt;</code> (for <a href=\"https://en.cppreference.com/w/cpp/thread/sleep_until\" rel=\"nofollow noreferrer\"><code>sleep_until</code></a>).</p>\n\n<p>The <code>updateGame</code> function uses a bunch of <code>if</code>s. At least they should be made <code>else if</code> to avoid redundant checking. And the right tool here is <code>switch</code>:</p>\n\n<pre><code>switch (event.type) {\ncase sf::Event::Closed:\n // ...\n break;\ncase sf::Event::MouseButtonPressed:\n // ...\n break;\ncase sf::Event::KeyReleased:\n // ...\n break;\n}\n</code></pre>\n\n<p>Your use of <code>endl</code> is justified because flushing is required here. This may deserve a comment.</p>\n\n<h1><code>AssetManager.cpp</code></h1>\n\n<p>Both functions should pass the strings by <code>string_view</code> instead of <code>string</code> by value. And it may be more convenient for <code>getTexture</code> to return a reference instead of a pointer.</p>\n\n<h1><code>LifeState.cpp</code></h1>\n\n<p>Several of your lambdas can be simplified with default captures. For example, <code>[=]</code> instead of <code>[tile, posX, posY]</code>, and <code>[&amp;]</code> instead of <code>[&amp;translated_pos, this]</code>. The lambda in <code>draw</code> can also be <code>[&amp;]</code> if you make <code>getTexture</code> return a reference as recommended above, or make <code>tile</code> and <code>tile2</code> references.</p>\n\n<p>The process of assigning the game data should probably be in the constructor of the <code>LifeState</code> class instead of the <code>init</code> function. Don't name the parameter identically to the data member. <code>boolean</code> is not a useful name for the lambda. <code>always_false</code> is better.</p>\n\n<p>The <code>update</code> function can similarly be rewritten using <code>chrono</code>.</p>\n\n<p>In the <code>getNeighbours</code> function, use prefix <code>++</code> instead of postfix <code>++</code>. Replace all <code>neighbours++</code> with <code>++neighbours</code>. And the logic should probably be simplified or organized somehow ...</p>\n\n<h1><code>Grid.hpp</code></h1>\n\n<p>Generic templates are not easy to get right. You definitely shouldn't be implementing <code>Grid</code> yourself in this project. Use an existing library instead.</p>\n\n<p>A <code>vector&lt;vector&lt;T&gt;&gt;</code> doesn't feel good. A library should use contiguous memory internally.</p>\n\n<p>You are using <code>.at</code> all over the place. Use <code>[]</code> when you have control over the index to reduce performance penalty.</p>\n\n<p><code>fill</code> should be a constructor, and should accept any callable object. <code>std::function</code> shouldn't be used here at all. And in this case, the use of <code>std::endl</code> is inherently wrong &mdash; you don't need to flush every single time and <code>'\\n'</code> is the way to go. <code>int</code> also doesn't feel right here. And your implementation is needlessly complex. Here's a basic proofread (not tested):</p>\n\n<pre><code>template &lt;typename T, typename F&gt;\nGrid&lt;T&gt;::Grid(size_type x, size_type y, F f)\n :data(x)\n{\n for (size_type i = 0; i &lt; x; ++i) {\n data[i].reserve(y);\n std::cout &lt;&lt; y &lt;&lt; '\\n';\n for (size_type j = 0; j &lt; y; ++j) {\n data[i].push_back(f(i, j, i + 1, y)); // the arguments are guessed\n }\n }\n}\n</code></pre>\n\n<p>where <code>size_type</code> is declared beforehand with</p>\n\n<pre><code>using size_type = typename decltype(data)::size_type;\n</code></pre>\n\n<p>I don't see how <code>sizeY</code> should be taking an argument. The grid is supposed to be rectangular, right?</p>\n\n<p>The <code>get</code> and <code>set</code> functions also feel a bit anti-C++-ish. <code>get</code> should be made <code>const</code>. I'd expect this in C++:</p>\n\n<pre><code>template &lt;typename T&gt;\nT&amp; Grid&lt;T&gt;::operator()(size_type x, size_type y)\n{\n return data.at(x).at(y);\n}\n\ntemplate &lt;typename T&gt;\nconst T&amp; Grid&lt;T&gt;::operator()(size_type x, size_type y) const\n{\n return data.at(x).at(y);\n}\n</code></pre>\n\n<p>This way, we can do <code>grid(x, y)</code> to get and <code>grid(x, y) = value</code> to set.</p>\n\n<p>Again, there are too many ways in which this feels unidiomatic and <em>please use an existing library instead of rolling out your own.</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T11:04:16.437", "Id": "437286", "Score": "0", "body": "this is excellent, thank you for all your comments!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T12:26:06.743", "Id": "437298", "Score": "1", "body": "I **strongly** disagree that a comment improves the constructor call. In fact, it makes it *worse* because it gives the reader false confidence. In reality, the comment could be completely wrong (e.g. width & height switched) and the reader would be none the wiser. This comment is a typical, extreme anti-pattern: It’s the cause of numerous hard to find bugs. Unfortunately there are no good and simple solutions to this issue. The best is to use strong typing with a named-argument idiom, and write `auto game = Game{width{2048}, height{1024}, title{\"foobar\"}};`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T13:04:35.523", "Id": "437308", "Score": "0", "body": "@KonradRudolph I also prefer the named argument approach. In this case, the constructors are not gonna be reused anyway, and since OP is relatively new to C++, that may be too much for him I guess. I'll update my answer to incorporate this information." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T16:59:02.050", "Id": "437696", "Score": "0", "body": "i looked into the \"named-argument idiom\" and that is what we call the \"builder-pattern\" in Java! nice to see that this pattern is also used in C++" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-05T11:01:14.053", "Id": "438005", "Score": "2", "body": "@ThomasAndolf Just to be clear, there are multiple completely different implementations of that idiom, and the one I was referring to isn’t the builder pattern (I’d call that builder pattern in C++!) and I strongly recommend *against* using it. I’d call that an anti-pattern in C++ because it makes it impossible to have `const` objects. In C++, an object should be be fully initialised once the constructor has finished running. The same is true in Java — builders should always generate a *different type*, such as `StringBuilder`, which is used to build an immutable `String`. This usage is OK." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-05T12:38:59.007", "Id": "438024", "Score": "0", "body": "@KonradRudolph ah yes, thank you for pointing that out, i actually noticed that yesterday when i was coding that in the example `OpenFile` returns a `File` So its more of a sort of factory pattern-isch. I fully agree with you in everything you say. Oh i have sooooooo many questions about C++ i find it very fascinating, it's like a mix of both new and old. I really appreciate you taking the time helping me, really." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T10:47:46.430", "Id": "225255", "ParentId": "225250", "Score": "4" } } ]
{ "AcceptedAnswerId": "225255", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T09:58:03.327", "Id": "225250", "Score": "4", "Tags": [ "c++", "beginner", "c++17", "game-of-life", "sfml" ], "Title": "C++ beginner wrote Conway's game of life using SFML" }
225250
<p>I have a function consisting of one line of code:</p> <pre><code>def trimString(string): """ Remove unnecessary whitespace. """ return re.sub('\s+', ' ', string).strip() </code></pre> <p>But I've been debating with myself whether the following would be better, seeing as explicit > implicit.</p> <pre><code>def trimString(string): """ Remove unnecessary whitespace. """ string = re.sub('\s+', ' ', string).strip() return string </code></pre> <p>So which is preferable, the former or the latter? And why is that the case?</p> <p>The question may be off-topic but I find myself asking it often enough and thought this was the place to ask.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T10:39:18.733", "Id": "437280", "Score": "1", "body": "I think anyone reading this who understands what `re.sub` and `.strip()` do will understand that this will return a string. The doctring and type hints as suggested by @eric.m make it even clearer without adding an extra variable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T10:48:00.200", "Id": "437281", "Score": "0", "body": "@HoboProber I'll keep this in mind going forward as I don't want to bloat the code while still keeping things explicit. Thanks for your input!" } ]
[ { "body": "<p>I think the shorter, the better. Since you are in Python 3, if you really want to make explicit that the function is returning a string, you can use <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">type hints</a>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def trimString(string) -&gt; str:\n</code></pre>\n\n<p>You can also specify it in the parameter:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def trimString(string: str) -&gt; str:\n</code></pre>\n\n<p>(keep in mind that Python will ignore type hints, but some IDEs like PyCharm use it to detect warnings and errors)</p>\n\n<p>On a side note, you should try to follow the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8 styling conventions</a>; the function name should be in camel case, so <code>trim_string</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T10:33:49.510", "Id": "437279", "Score": "0", "body": "I hadn't thought of type hints before but it seems like something I'll be very into. I've seen people deliberately avoiding the naming conventions suggested by PEP 8, namely on [this thread](https://stackoverflow.com/questions/159720/what-is-the-naming-convention-in-python-for-variable-and-function-names/160830#160830) and figured I'd do the same simply because of habit and preference. But I still have my doubts. Anyways, good answer :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T10:48:35.057", "Id": "437283", "Score": "1", "body": "I used to avoid the naming conventions before, because I was used to programming Java. Now when I look at my old Python code it looks ugly since it's not what my brain expects to see in Python. I guess it's a matter of habit." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T10:26:22.533", "Id": "225253", "ParentId": "225252", "Score": "4" } } ]
{ "AcceptedAnswerId": "225253", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T10:19:11.770", "Id": "225252", "Score": "1", "Tags": [ "python", "python-3.x", "strings", "regex" ], "Title": "Short function to remove unnecessary whitespace" }
225252
<p>This is the 'details.ts' which define the user's details that I want to recuperate in a JSON (user's role, logintime, duration).</p> <pre><code>import {AuthenticationService} from '../_services'; import { User } from '../_models'; export class Details { authenticationService : AuthenticationService; currentUser = this.authenticationService.currentUserValue; role = this.currentUser.role; logintime = this.authenticationService.today; duree = this.authenticationService.timeLeft; } </code></pre> <p>and this is the service "details.service.ts" which implement the method create and get:</p> <pre><code>import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Employee } from '../shared/employee'; import { Observable, throwError } from 'rxjs'; import { retry, catchError } from 'rxjs/operators'; import {Details} from './details'; @Injectable({ providedIn: 'root' }) export class DetailsService { apiURL = 'http://localhost:3000'; constructor(private http: HttpClient) { } httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) } createEmployee(details): Observable&lt;Details&gt; { return this.http.post&lt;Details&gt;(this.apiURL + '/details', JSON.stringify(details), this.httpOptions) .pipe( retry(1), catchError(this.handleError) ) } getEmployees(): Observable&lt;Details&gt; { return this.http.get&lt;Details&gt;(this.apiURL + '/details') .pipe( retry(1), catchError(this.handleError) ) } deleteEmployee(id){ return this.http.delete&lt;Details&gt;(this.apiURL + '/details/' + id, this.httpOptions) .pipe( retry(1), catchError(this.handleError) ) } handleError(error) { let errorMessage = ''; if(error.error instanceof ErrorEvent) { // Get client-side error errorMessage = error.error.message; } else { // Get server-side error errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`; } window.alert(errorMessage); return throwError(errorMessage); } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T10:57:29.730", "Id": "225256", "Score": "2", "Tags": [ "json", "typescript", "angular-2+" ], "Title": "Recuperate user's details into fake JSON server" }
225256
<p>I'm trying to improve my Game of life program for school in Python, to be able to run it quicker. So if you have some ideas, I will be glad to hear them.</p> <p>My current code:</p> <pre><code>def neighbourhood(m, i, j): num = 0 n_board = len(m) for k in range(i-1,i+2): for l in range(j-1,j+2): if k &lt; 0 or l &lt; 0 or k &gt;= n_board or l &gt;= n_board: num = num + 0 else: num = num + m[k][l] return num def update(m): s = np.copy(m) n_board = len(m) for i in range(0, n_board): for j in range(0, n_board): if s[i][j] == 1: num = neighbourhood(s, i, j) - 1 if num &lt;= 1 or num &gt; 3: m[i][j] = 0 else: m[i][j] = 1 else: num = neighbourhood(s, i, j) if num == 3: m[i][j] = 1 else: m[i][j] = 0 def square(x, y): turtle.penup() turtle.setposition(x,y) turtle.setheading(0) turtle.pendown() turtle.begin_fill() for i in range(4): turtle.forward(0.9) turtle.left(90) turtle.end_fill() def draw(m): turtle.clear() n_board = len(m) for i in range(n_board): for j in range(n_board): if m[i][j] == 1: square(j, (n_board - i - 1)) turtle.update() def main(n_board): turtle.reset() turtle.setworldcoordinates(0, 0, n_board, n_board) turtle.hideturtle() turtle.speed('fastest') turtle.tracer(0, 0) turtle.color('black') turtle.bgcolor('white') board=np.zeros((n_board, n_board), int) for i in range(n_board): for j in range(n_board): if random() &lt; 0.5: board[i][j] = 1 draw(board) for k in range(100): update(board) draw(board) </code></pre> <p>So as you can see for the moment i'm only doing 100 repetition and the starting board is randomly created.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T12:16:55.363", "Id": "437296", "Score": "0", "body": "Welcome to code review. It might be better if your title was about what the code does rather than about the results you are trying to achieve. For a little more help on asking good questions please see the code review guidelines at https://codereview.stackexchange.com/help/how-to-ask and https://codereview.stackexchange.com/help/dont-ask." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T12:46:48.253", "Id": "437304", "Score": "1", "body": "You mention that you are using turtles to display the board. Nothing in your code shows this. You can only ask about code that you show in your question. Since we are on Code Review, complete code is often preferable to shortened code." } ]
[ { "body": "<p>Since you aren't using any of the things that make numpy fast, this code would be about 2x faster if you just used python lists instead. Alternatively, if you vectorized the update function, you would probably be able to make it much faster. That said, this will not be easy. <a href=\"https://codereview.stackexchange.com/questions/160802/game-of-life-with-numpy\">This question</a> has a very good example of what the result would look like.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T20:12:34.747", "Id": "437400", "Score": "0", "body": "Thank for the answer i'm going to look into it. Any idea to replace turtle which would speed thing up" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T20:22:48.567", "Id": "437401", "Score": "0", "body": "I don't know much about turtle, but matplotlib is a pain but generally pretty good." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T21:23:29.703", "Id": "437423", "Score": "0", "body": "Yes i start by using matplotlib but it was much more harder than using turtle but since turtle is so slow i will go for matplotlib" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T21:24:48.357", "Id": "437424", "Score": "0", "body": "PS:Sorry for my english level, i'm doing my best, i'm french." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T21:38:00.273", "Id": "437430", "Score": "0", "body": "no problem. I hadn't noticed" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T19:44:28.693", "Id": "225290", "ParentId": "225257", "Score": "1" } } ]
{ "AcceptedAnswerId": "225290", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T11:02:37.913", "Id": "225257", "Score": "2", "Tags": [ "python", "performance", "numpy", "homework", "game-of-life" ], "Title": "Game of life using NumPy" }
225257
<p>Users like exploring maps, seeing all that is around. However they tend to go too far. To prevent the map from getting lost to the user it bounces back into the set bounds, as defined by a rectangle.</p> <p>To do this I keep track of two rectangles, the outer rectangle that the user moves around (the map), and an inner rectangle that serves as the viewport. When the outer rectangle gets swiped all the way to the right, the left side of the inner and outer rectangles overlap. The user can still drag it to see the overhang of the map, but once they release their touch the map moves back to inside the bounds.</p> <p>My implementation for this: (unity 2019.1.8f1 with C# 4.x runtime IL2CPP):</p> <p><strong>MapMover.cs</strong></p> <pre><code>using System; using System.Collections; using UnityEngine; using UnityEngine.EventSystems; public class MapMover : MonoBehaviour, IDragHandler, IBeginDragHandler, IEndDragHandler { [Flags] private enum OutOfBoundsDirection { Inbounds = 1, Left = 2, Right = 4, Top = 8, Bottom = 16 }; private OutOfBoundsDirection outOfBounds; [SerializeField] private GameObject mainCanvas; [SerializeField] private BoxCollider2D maskCol; private readonly float snapBackSpeed = 100; private Vector3 startTouchPos; private BoxCollider2D col; private WaitForEndOfFrame waitFrame; private void Start() { waitFrame = new WaitForEndOfFrame(); col = GetComponent&lt;BoxCollider2D&gt;(); } public void OnBeginDrag(PointerEventData eventData) { startTouchPos = Input.mousePosition; } /// &lt;summary&gt; /// Move the map in a 1:1 scale to the movement of the finger. To do this We need to divide the difference between the start position of the touch and the current position /// by the scale of the canvas (and any other parent, whose scale isn't exactly 1. Right now this isn't the case). /// &lt;/summary&gt; /// &lt;param name="eventData"&gt;&lt;/param&gt; public void OnDrag(PointerEventData eventData) { var posDiff = startTouchPos - Input.mousePosition; transform.localPosition -= posDiff / mainCanvas.transform.localScale.x; startTouchPos -= posDiff; } public void OnEndDrag(PointerEventData eventData) { CheckBounds(); } /// &lt;summary&gt; /// Check if the map is still within the set bounds of the inner rect. /// &lt;/summary&gt; private void CheckBounds() { Rect innerRect = new Rect(maskCol.GetCornerVertices()[3].x, maskCol.GetCornerVertices()[3].y, maskCol.size.x, maskCol.size.y); Rect outerRect = new Rect(col.GetCornerVertices()[3].x + transform.localPosition.x, col.GetCornerVertices()[3].y + transform.localPosition.y, col.size.x, col.size.y); if (outerRect.xMin &lt; innerRect.xMin &amp;&amp; outerRect.xMax &gt; innerRect.xMax &amp;&amp; outerRect.yMin &lt; innerRect.yMin &amp;&amp; outerRect.yMax &gt; innerRect.yMax) { outOfBounds = OutOfBoundsDirection.Inbounds; } else { if ((outOfBounds &amp;= OutOfBoundsDirection.Inbounds) == OutOfBoundsDirection.Inbounds) { outOfBounds ^= OutOfBoundsDirection.Inbounds; } if (outerRect.xMin &gt; innerRect.xMin) { outOfBounds |= OutOfBoundsDirection.Left; } if (outerRect.xMax &lt; innerRect.xMax) { outOfBounds |= OutOfBoundsDirection.Right; } if (outerRect.yMin &gt; innerRect.yMin) { outOfBounds |= OutOfBoundsDirection.Bottom; } if (outerRect.yMax &lt; innerRect.yMax) { outOfBounds |= OutOfBoundsDirection.Top; } StartCoroutine(MoveInbounds()); } } /// &lt;summary&gt; /// Translate the map to inside the bounds /// &lt;/summary&gt; /// &lt;returns&gt;&lt;/returns&gt; private IEnumerator MoveInbounds() { if ((outOfBounds &amp; OutOfBoundsDirection.Left) != 0) { transform.Translate(Vector3.left * snapBackSpeed); } if ((outOfBounds &amp; OutOfBoundsDirection.Right) != 0) { transform.Translate(Vector3.right * snapBackSpeed); } if ((outOfBounds &amp; OutOfBoundsDirection.Top) != 0) { transform.Translate(Vector3.up * snapBackSpeed); } if ((outOfBounds &amp; OutOfBoundsDirection.Bottom) != 0) { transform.Translate(Vector3.down * snapBackSpeed); } yield return waitFrame; CheckBounds(); } } </code></pre> <p><strong>BoxColliderExtensions.cs</strong></p> <pre><code>using UnityEngine; public static class BoxColliderExtensions { /// &lt;summary&gt; /// Returns the local position of the four corner vertices of the collider /// &lt;/summary&gt; /// &lt;param name="col"&gt;Array containing the corner points, starting at the top right and going clockwise&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public static Vector2[] GetCornerVertices(this BoxCollider2D col) { Vector2[] verts = new Vector2[4]; verts[0] = col.offset + new Vector2(-col.size.x, col.size.y) * 0.5f; verts[1] = col.offset + new Vector2(col.size.x, col.size.y) * 0.5f; verts[2] = col.offset + new Vector2(col.size.x, -col.size.y) * 0.5f; verts[3] = col.offset + new Vector2(-col.size.x, -col.size.y) * 0.5f; return verts; } } </code></pre> <p>The code works smoothly. I've never used bitmasks before but thought this would be a nice application of it, since the map can be moved out of bounds in multiple directions at the same time (e.g. up &amp; right). But this takes a lot of if checks to do, which I feel can be halved, as i'm pretty much checking the same thing twice in <code>CheckBounds</code> and <code>MoveInBounds</code>. </p> <p>I'm not experiencing any performance issues with it, so don't need to micro optimize it. Mainly looking for readability improvements/getting rid of those double ifs.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T05:49:37.843", "Id": "437469", "Score": "1", "body": "For some reason, wherever you call GetCornerVertices(), you are only using its element with the index [3]; and then both its x and y fields. Without diving deep inside the logic, this asymmetry looks suspicious: it looks like you rely on the minimap being in one specific corner of the screen, or something like this. However, if there's a valid reason to only check a single vertex, there's no need to detect the rest." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T06:25:49.933", "Id": "437474", "Score": "0", "body": "@IMil it is because of the way a rect is constructed. `new Rect(float x, float y, float width, floath height`. the vertex at index `[3]` is the bottom left vertex. Starting from this vertex means I can pass in its full width/height to get the total rectangle. If I used index [0] (top left) i'd have to pass in width/-height. As you say only that single index gets used here and could indeed make a function that returns just that specific vertex, hand't thought of that. Thanks! (If you add that as an answer I can upvote it)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T13:29:23.640", "Id": "437534", "Score": "0", "body": "Not a code review, but I find the re-positioning really bad UX (what if I want to find distance to a known landmark that is just outside of the bounds?). Better to provide a sort of \"home\" button to go back to the initial position." } ]
[ { "body": "<h3>Readability</h3>\n\n<blockquote>\n <p><em>Mainly looking for readability improvements/getting rid of those double ifs.</em></p>\n</blockquote>\n\n<p>Since you are considered about readability, I will focus on that part.</p>\n\n<hr>\n\n<p>Declare a flags enum on multiple lines and prefer to use the bit shift to indicate its location. Use an unsigned type as underlying type. Have a value corresponding to 0, because that is the default of any enum.</p>\n\n<blockquote>\n<pre><code>[Flags]\nprivate enum OutOfBoundsDirection { Inbounds = 1, Left = 2, Right = 4 // ..\n</code></pre>\n</blockquote>\n\n<pre><code>[Flags]\nprivate enum OutOfBoundsDirection : uint\n{ \n None = 0\n Inbounds = 1 &lt;&lt; 0, \n Left = 1 &lt;&lt; 1, \n Right = 1 &lt;&lt; 2, \n Top = 1 &lt;&lt; 3, \n Bottom = 1 &lt;&lt; 4\n}\n</code></pre>\n\n<hr>\n\n<p>Don't inline annotations.</p>\n\n<blockquote>\n<pre><code> [SerializeField] private GameObject mainCanvas;\n</code></pre>\n</blockquote>\n\n<pre><code>[SerializeField] \nprivate GameObject mainCanvas;\n</code></pre>\n\n<hr>\n\n<p>Use early exit when you want to avoid nested if statements.</p>\n\n<blockquote>\n<pre><code>if (outerRect.xMin &lt; innerRect.xMin &amp;&amp; outerRect.xMax &gt; innerRect.xMax &amp;&amp;\n outerRect.yMin &lt; innerRect.yMin &amp;&amp; outerRect.yMax &gt; innerRect.yMax)\n{\n outOfBounds = OutOfBoundsDirection.Inbounds;\n}\nelse\n{\n if ((outOfBounds &amp;= OutOfBoundsDirection.Inbounds) == OutOfBoundsDirection.Inbounds)\n {\n outOfBounds ^= OutOfBoundsDirection.Inbounds;\n }\n // .. CR: code omitted for brevity\n}\n</code></pre>\n</blockquote>\n\n<pre><code>if (outerRect.xMin &lt; innerRect.xMin &amp;&amp; outerRect.xMax &gt; innerRect.xMax &amp;&amp;\n outerRect.yMin &lt; innerRect.yMin &amp;&amp; outerRect.yMax &gt; innerRect.yMax)\n{\n outOfBounds = OutOfBoundsDirection.Inbounds;\n return;\n}\nif ((outOfBounds &amp;= OutOfBoundsDirection.Inbounds) == OutOfBoundsDirection.Inbounds)\n{\n outOfBounds ^= OutOfBoundsDirection.Inbounds;\n}\n// .. CR: code omitted for brevity\n</code></pre>\n\n<hr>\n\n<p>Use <code>HasFlag</code> to perform the bit check for you.</p>\n\n<blockquote>\n<pre><code>if ((outOfBounds &amp; OutOfBoundsDirection.Left) != 0)\n</code></pre>\n</blockquote>\n\n<pre><code>if ((outOfBounds.HasFlag(OutOfBoundsDirection.Left))\n</code></pre>\n\n<hr>\n\n<p>Create constants where you can.</p>\n\n<blockquote>\n<pre><code>verts[0] = col.offset + new Vector2(-col.size.x, col.size.y) * 0.5f;\nverts[1] = col.offset + new Vector2(col.size.x, col.size.y) * 0.5f;\nverts[2] = col.offset + new Vector2(col.size.x, -col.size.y) * 0.5f;\nverts[3] = col.offset + new Vector2(-col.size.x, -col.size.y) * 0.5f;\n</code></pre>\n</blockquote>\n\n<pre><code>const float factor = 0.5f;\n\nverts[0] = col.offset + new Vector2(-col.size.x, col.size.y) * factor;\nverts[1] = col.offset + new Vector2(col.size.x, col.size.y) * factor;\nverts[2] = col.offset + new Vector2(col.size.x, -col.size.y) * factor;\nverts[3] = col.offset + new Vector2(-col.size.x, -col.size.y) * factor;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T11:36:56.540", "Id": "437293", "Score": "0", "body": "Thank you for the suggestions! Is there a technical reason why a bit shift is better when declaring the enum? To me it looks likes that would be less readable on bigger enums." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T11:38:18.583", "Id": "437294", "Score": "4", "body": "No, only for readability :) But you might not agree with this. Many developers show the bit location in the declaration." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T15:21:20.687", "Id": "437330", "Score": "0", "body": "Is it considered bad style to inline annotations? I found it useful especially in Unity projects where `[SerializeField] private` is used frequently" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T17:09:21.600", "Id": "437360", "Score": "1", "body": "@sonny To some point, style preferences are subjective. If you like this style, use it :) Just be consistent in what you pick." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T05:51:29.297", "Id": "437471", "Score": "2", "body": "While using constants is a reasonable suggestion, in this case replacing 0.5 with \"factor\" is hardly an improvement because there's no indication what this \"factor\" means. It would make a lot more sense to introduce two variables: \"double halfWidth = col.size.x * 0.5\" and its counterpart \"halfHeight\". Then there'll be no need to replace 0.5 with a constant, because its meaning will be obvious from the variable name." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T06:00:10.060", "Id": "437473", "Score": "0", "body": "@IMil I agree. This would be improve readability even better." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T11:28:16.763", "Id": "225261", "ParentId": "225260", "Score": "10" } }, { "body": "<p>This </p>\n\n<blockquote>\n<pre><code> if (outerRect.xMin &lt; innerRect.xMin &amp;&amp; outerRect.xMax &gt; innerRect.xMax &amp;&amp;\n outerRect.yMin &lt; innerRect.yMin &amp;&amp; outerRect.yMax &gt; innerRect.yMax)\n</code></pre>\n</blockquote>\n\n<p>and this:</p>\n\n<blockquote>\n<pre><code> if (outerRect.xMin &gt; innerRect.xMin)\n {\n outOfBounds |= OutOfBoundsDirection.Left;\n }\n\n if (outerRect.xMax &lt; innerRect.xMax)\n {\n outOfBounds |= OutOfBoundsDirection.Right;\n }\n\n if (outerRect.yMin &gt; innerRect.yMin)\n {\n outOfBounds |= OutOfBoundsDirection.Bottom;\n }\n\n if (outerRect.yMax &lt; innerRect.yMax)\n {\n outOfBounds |= OutOfBoundsDirection.Top;\n }\n</code></pre>\n</blockquote>\n\n<p>are candidates as extension methods:</p>\n\n<pre><code>static class Extensions\n{\n public static bool Contains(this Rect outerRect, Rect innerRect)\n {\n return outerRect.xMin &lt; innerRect.xMin &amp;&amp; outerRect.xMax &gt; innerRect.xMax &amp;&amp;\n outerRect.yMin &lt; innerRect.yMin &amp;&amp; outerRect.yMax &gt; innerRect.yMax;\n }\n\n public static OutOfBoundsDirection Overlaps(this Rect outerRect, Rect innerRect)\n {\n OutOfBoundsDirection outOfBounds = OutOfBoundsDirection.None;\n\n if (outerRect.xMin &gt; innerRect.xMin)\n {\n outOfBounds |= OutOfBoundsDirection.Left;\n }\n\n if (outerRect.xMax &lt; innerRect.xMax)\n {\n outOfBounds |= OutOfBoundsDirection.Right;\n }\n\n if (outerRect.yMin &gt; innerRect.yMin)\n {\n outOfBounds |= OutOfBoundsDirection.Bottom;\n }\n\n if (outerRect.yMax &lt; innerRect.yMax)\n {\n outOfBounds |= OutOfBoundsDirection.Top;\n }\n\n return outOfBounds;\n }\n}\n</code></pre>\n\n<hr>\n\n<p>I'm not a fan of the <code>OutOfBoundsDirection.Inbounds</code> flag, because it can lead to invalid states as:</p>\n\n<pre><code>OutOfBoundsDirection bounds = OutOfBoundsDirection.Inbounds | OutOfBoundsDirection.Left;\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> if (outerRect.xMin &gt; innerRect.xMin)\n {\n outOfBounds |= OutOfBoundsDirection.Left;\n }\n</code></pre>\n</blockquote>\n\n<p>What if <code>outOfBounds</code> has the flag <code>Left</code> set before this check, then it's still set even if <code>outerRect.xMin &lt;= innerRect.xMin</code>? Or maybe you reset <code>outOfBounds</code> elsewhere?</p>\n\n<p>Maybe the first check:</p>\n\n<blockquote>\n<pre><code> if ((outOfBounds &amp;= OutOfBoundsDirection.Inbounds) == OutOfBoundsDirection.Inbounds)\n {\n outOfBounds ^= OutOfBoundsDirection.Inbounds;\n }\n</code></pre>\n</blockquote>\n\n<p>should just be:</p>\n\n<pre><code>outOfBounds = OutOfBoundsDirection.None;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T12:53:24.767", "Id": "437305", "Score": "1", "body": "I was just thinking exactly the same about `Inbounds`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T12:56:38.360", "Id": "437307", "Score": "2", "body": "I had not thought of putting them into extension methods. It would look a lot cleaner indeed. Initially I didn't have a `.None` flag and after adding it didn't realise I can just use that now to set `outOfBounds = OutOfBoundsDirection.None` instead of the if check. Appreciate your feedback!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T12:49:50.937", "Id": "225265", "ParentId": "225260", "Score": "9" } } ]
{ "AcceptedAnswerId": "225261", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T11:09:52.180", "Id": "225260", "Score": "10", "Tags": [ "c#", "bitwise", "enum", "unity3d" ], "Title": "Bouncing map back into its bounds, after user dragged it out" }
225260
<p>I have a website that, based on a user's comments, filters comments by "most liked first, most disliked first" etc...</p> <p>I have a custom table for comments scoring system and system working with +1 and -1's.</p> <p>A few days ago I wanted to filter comments by most liked and most disliked as I said and wrote this code:</p> <p>In my functions.php</p> <pre><code>function bestanswers($a){ global $wpdb; $results = $wpdb-&gt;get_results( 'SELECT * FROM wp_comments LEFT JOIN wp_custom_scoring ON wp_custom_scoring.entryID = wp_comments.comment_ID WHERE class="point" and comment_post_ID='.intval($a).' AND type="plus" GROUP BY entryID ORDER BY COUNT(entryID) DESC'); if(empty($results)){ echo 'Its Empty!'; return false; }else{ return $results; } } </code></pre> <p>And in my functions.php again:</p> <pre><code>function score($a,$b){ if($b == "minus"){ global $wpdb; $results = $wpdb-&gt;get_results( 'SELECT count(id) as total,type,class,entryID FROM wp_custom_scoring WHERE type="minus" and class="point" and entryID='.intval($a)); if($results[0]-&gt;total!= 0){ return "-".$results[0]-&gt;total; }else{ return 0; } }elseif($b == "plus"){ global $wpdb; $results = $wpdb-&gt;get_results( 'SELECT count(id) as total,type,class,entryID FROM wp_custom_scoring WHERE type="plus" and class="point" and entryID ='.intval($a)); if($results[0]-&gt;total != 0){ return "+".$results[0]-&gt;total; }else{ return 0; } }else{ global $wpdb; $results = $wpdb-&gt;get_results( 'SELECT count(id) as total,class,entryID FROM wp_custom_scoring WHERE class="fav" and entryID='.intval($a)); return $results[0]-&gt;total; } } </code></pre> <p>And in comments.php:</p> <pre><code>if(isset($_GET['filter']) and sanitize_text_field(esc_attr($_GET['filter'])) == 'bestanswers'){ foreach (bestanswers($postID) as $bests) { if ( score($bests-&gt;comment_ID,"plus") + score($bests-&gt;comment_ID,"minus") &gt; 0 ){ echo $bests-&gt;comment_ID; comment_text($bests-&gt;comment_ID); ///...etc with my custom theme template } </code></pre> <p>It's working and I'm able to get everything as I wanted but it's looking ugly to me. Is there are any better way to do this? Or any improvement on my code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T12:32:28.137", "Id": "437301", "Score": "0", "body": "Welcome to code review. Your question may attract more attention if the title was just what the code does rather than what you want from the review. An example for this question might be `Filtering web comments by votes`. Please see the code review guidelines at https://codereview.stackexchange.com/help/how-to-ask." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T13:06:31.270", "Id": "437309", "Score": "1", "body": "Thanks for your response! You are right :)" } ]
[ { "body": "<p>Here is my list of recommendations:</p>\n\n<ul>\n<li><p>To make the database object available in the custom functions' scope, pass it as a parameter. I know your <code>global</code> declaration is commonly used by WPers, but I consider it to be <em>sloppy</em> development. If you are going to persist with using <code>global</code>, then you should only do it once per custom function.</p></li>\n<li><p>In <code>bestanswers()</code> to make your SQL easier to read, use newlines, indentation, spaces around operators, ALLCAPS mysql keywords, double-quoting the full string, and single-quoting the values in the string. *That said, for the most secure and consistent project, you should use prepared statements anytime you are supplying variables to your query.</p>\n\n<pre><code>$results = $wpdb-&gt;get_results(\n \"SELECT *\n FROM wp_comments\n LEFT JOIN wp_custom_scoring \n ON wp_custom_scoring.entryID = wp_comments.comment_ID\n WHERE class = 'point'\n AND comment_post_ID = \" . (int)$a . \"\n AND type = 'plus'\n GROUP BY entryID\n ORDER BY COUNT(entryID) DESC\");\n</code></pre></li>\n<li><p><code>empty()</code> does 2 things. It checks if a variable <code>!isset()</code> OR loosely evaluates as \"falsey\". You know that <code>$result</code> will be <code>set</code> because you have unconditionally declared it on the previous line of code. (untested...)</p>\n\n<pre><code>if (!$results)) {\n echo 'Its Empty!';\n return false;\n}else{\n return $results;\n}\n</code></pre>\n\n<p>Or if you don't need the <code>echo</code>:</p>\n\n<pre><code>return $results ? $results : false;\n</code></pre></li>\n<li><p>In <code>scores()</code>, your <code>$b</code> parameter only determines the WHERE clause, so you can DRY out your code like this:</p>\n\n<pre><code>function score($wpdb, $a, $b) {\n if (in_array($b, ['plus','minus']) {\n $where = \"class = 'point' AND type = '{$b}'\";\n } else {\n $where = \"class = 'fav'\";\n } \n\n $results = $wpdb-&gt;get_results(\n \"SELECT COUNT(id) as total\n FROM wp_custom_scoring\n WHERE entryID = \" . (int)$a . \"\n AND {$where}\";\n\n if (!$results || !$results[0]-&gt;total) {\n return 0;\n } elseif ($a === 'plus') {\n return \"+{$results[0]-&gt;total}\";\n } elseif ($a === 'minus') {\n return \"-{$results[0]-&gt;total}\";\n } else {\n return $results[0]-&gt;total;\n }\n}\n</code></pre>\n\n<p>but again, I urge you to consider using prepared statements as a consistent/stable/secure technique across your whole application.</p></li>\n</ul>\n\n<hr>\n\n<p>Ultimately, I don't know what is down in the <code>...etc.</code> portion of your script, but if you are making two function calls to calculate: <code>score($bests-&gt;comment_ID,\"plus\") + score($bests-&gt;comment_ID,\"minus\") &gt; 0</code>, then it may make better sense to create a single custom function that performs this calculation and returns the sum instead.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T01:49:04.593", "Id": "437450", "Score": "0", "body": "Very very good advices! Thank you so much! And yes, I guess I have to use $wpdb->prepare instead of $wpdb->get_results. But in this example intval() command must be securing my query against inj. am I wrong? ( I mean yes, $wpdb->prepare most secure way to protect a query, I'm talking for this code. Ofc I can't use intval() everywhere in my queries. It's only works with numbers...) And, etc means -> everything needed for my comment template. Like $bests->user_id, $bests->comment_ID, $bests->author_name... And you are totally right, I guess I'm calling so many queries for it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T01:51:45.913", "Id": "437451", "Score": "0", "body": "Your posted queries are _technically_ not vulnerable to injection attacks." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T23:15:41.027", "Id": "225307", "ParentId": "225262", "Score": "1" } } ]
{ "AcceptedAnswerId": "225307", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T11:45:02.747", "Id": "225262", "Score": "3", "Tags": [ "php", "wordpress" ], "Title": "Filtering wordpress comments by votes" }
225262
<p>The following code is one of a few similar snippets that generate a graph using CanvasJS, with the datapoints for the graph pushed to an array in PHP during a while loop. The code pulls the the date and the escalation event toals for every weekday for the last 30days, does some math on them, and then pushes the calcualted outcome Y value into an array with the dayID/date as the X value/label. The array is then JSON encoded to be used by CanvasJS.</p> <p>Currently, this particular page (and hence this graph) takes around 9 seconds to run. </p> <p><strong>Disclaimer:</strong> I am not a PHP developer, and I know very little about what is the <em>correct</em> way to do this. This code is my way of doing it, however I know how. I am fully expecting this to be torn apart, haha.</p> <p><strong><em>UPDATE: A little info on what the graph shows, and why there are 2 DB's. The graph shows a percentage figure for each day that is derived from the total number of KPI breachable events in a ticket system, and the number of KPI Breach events that day for tickets in the ticket system. It's fairly high volume, and each day could contain 100-400 events. There are 2 databases because the KPI breaching system was made by me, I track events and the status they are in, and log how long they are in that status for, if that time goes above a defined limit, it is classed as breached (or escalated in this context). I store all of that KPI breach tracking information in a different database, as I cannot add tables or otherwise manipulate the database that contains the ticket information/data (it's an ISMS controlled system, and is a managed/supported solution form a 3rd party, I cant change their DB structure.).</em></strong></p> <p><strong><em>So to summarise that, $db is the ticket system, whcih pulls the total number of escalatable events for a day (and the date), and $db2 is my own DB containing escalated events, timestamps and whether or not they've recovered from escalation status/KPI breach.</em></strong></p> <pre class="lang-php prettyprint-override"><code>&lt;div id="chartContainer" style="height: 370px; width: 800px;"&gt;&lt;/div&gt; &lt;script src="https://canvasjs.com/assets/script/canvasjs.min.js"&gt;&lt;/script&gt; &lt;?php //Debug Mode // $debug=0; if($debug == 1) { ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); } //Get the creds and conn strings for the 2 DBs // include("conf/db.php"); include("conf/db2.php"); //Build Graph Data Points // $daysmax=31; $daycounter=0; $datapoints = array(); while($daysmax &gt; $daycounter) { if ($debug == 1) { echo "Day: ".$daycounter." -- "; } $sql_get_day_total_events="SELECT COUNT(*),date_sub(curdate(),INTERVAL $daycounter day) as date1 FROM tblticketlog WHERE DATE(date) = date_sub(curdate(),INTERVAL $daycounter day) AND dayofweek(date) NOT IN (1,7) AND ((action = 'New Support Ticket Opened') OR (action LIKE 'Status changed to Pending%') OR (action LIKE 'Status changed to In Progress%') OR (action LIKE 'New Ticket Response made by%'))"; $get_day_total_events_result=mysqli_query($db,$sql_get_day_total_events); if(mysqli_num_rows($get_day_total_events_result) &gt; 0) { while($row = $get_day_total_events_result-&gt;fetch_assoc()) { $day_result_date=strtotime($row['date1']); $day_result_value=$row['COUNT(*)']; } } $sql_get_day_escs="SELECT COUNT(*),date_sub(curdate(), INTERVAL $daycounter day) as date FROM escalations WHERE DATE(esc_at) = date_sub(curdate(), INTERVAL $daycounter day) AND dayofweek(esc_at) NOT IN (1,7) AND escalated = 1"; $get_day_escs_result=mysqli_query($db2,$sql_get_day_escs); if(mysqli_num_rows($get_day_escs_result) &gt; 0) { while($row = $get_day_escs_result-&gt;fetch_assoc()) { $day_escs_value=$row['COUNT(*)']; } } $day_slas_met=$day_result_value - $day_escs_value; $day_kpi_pcnt = round((($day_slas_met / $day_result_value) * 100),0); if ($debug == 1) { echo date("d-m-Y",$day_result_date)." - ".$day_slas_met."/".$day_result_value." - ".$day_kpi_pcnt."%&lt;br /&gt;"; } if ($day_result_value &gt; 0) { $datapoints[] = [ 'x' =&gt; 30 - $daycounter, 'label' =&gt; date("d-m-Y",$day_result_date), 'y' =&gt; $day_kpi_pcnt, ]; } $daycounter=$daycounter + 1; } $datapoints_rev = array_reverse($datapoints); if ($debug == 1) { print_r($datapoints_rev); } ?&gt; &lt;script&gt; window.onload = function () { var chart = new CanvasJS.Chart("chartContainer", { animationEnabled: true, exportEnabled: true, theme: "light1", title:{ text: "SLA Met Last 30 Days (Weekdays, %)" }, data: [{ type: "line", //indexLabel: "{y}", indexLabelFontColor: "#5A5757", indexLabelPlacement: "outside", dataPoints: &lt;?php echo json_encode($datapoints_rev, JSON_NUMERIC_CHECK); ?&gt; }] }); chart.render(); } &lt;/script&gt; </code></pre> <p>If it matters, this is the graph it generates: </p> <p><a href="https://i.stack.imgur.com/1qR8t.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1qR8t.jpg" alt="canvasjs graph 1"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T12:39:12.773", "Id": "437302", "Score": "1", "body": "A way to speed this up is to get the data for all the days with one query, instead of a separate query for each day. Then `GROUP BY` date. PS: it would be nice to know what the graph is about and why you need two databases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T12:55:33.680", "Id": "437306", "Score": "0", "body": "@KIKOSoftware Thankyou for the reply, I've added another section to my post that briefly explains its purpose, and why there are 2 different databases in use. I will investigate pulling all the data in 1 query. I think I did try that originally and it dodnt work how i expected it to. Not that thats a concern for codereview of course.." } ]
[ { "body": "<p>I first had to <em>look up</em> what <strong>KPI</strong> stands for. It is a \"<strong>K</strong>ey <strong>P</strong>erformance <strong>I</strong>ndicator\". Then a \"KPI breachable event\" must be when some indicator gets over a certain threshold? That's my best guess... Better not use an abbreviation, or jargon, that is unrelated to programming, when explaining what your code is doing. There's a big change we don't know what you're talking about.</p>\n\n<p>There will also be a lot of things I cannot review in this answer, since your question doesn't contain all the code/data/schema. Lack thereof also means I cannot test the code here. <strong>Warning:</strong> There may be bugs.</p>\n\n<p>Given these restrictions I've tried to rewrite your code so it only does one query on each database for all the days in the graph, thereby possibly speeding up your code by a factor of 30, meaning that it should complete in less than half a second. Which is still quite a long time. </p>\n\n<p>One of the other reasons the queries can be slow is the way you've implemented the <code>action</code> column in the <code>tblticketlog</code> table query. It is a string and uses several <code>LIKE</code> comparisons. The query could be made faster if the status of a ticket can be checked more efficiently. Imagine you had a column called <code>status</code> of type <a href=\"https://dev.mysql.com/doc/refman/8.0/en/set.html\" rel=\"nofollow noreferrer\">SET</a> with the values <code>('new', 'rejected', 'pending', 'progress', 'responded', 'delete')</code>, or something similar. The test could then be:</p>\n\n<pre><code>.... AND status IN ('new', 'pending', 'progress', 'responded')\n</code></pre>\n\n<p>Which is a lot faster, and also shorter. You could still have a column similar to <code>action</code> with more details about the status of the ticket.</p>\n\n<p>Also check whether you have set <a href=\"http://www.mysqltutorial.org/mysql-index\" rel=\"nofollow noreferrer\">the proper indexes</a> for these queries.</p>\n\n<p>Here's the rewritten code, without the debugging stuff. </p>\n\n<p>I am going to use this function:</p>\n\n<pre><code>function selectDailyEvents($db, $query)\n{\n $data = [];\n if ($result = mysqli_query($db, $query)) {\n while ($row = $result-&gt;fetch_assoc()) {\n $data[$row[\"dayNo\"]] = [\"date\" =&gt; $row[\"eventDate\"],\n \"count\" =&gt; $row[\"eventCount\"]];\n }\n $result-&gt;free();\n }\n return $data;\n}\n</code></pre>\n\n<p>Because both queries below return, more or less, the same result, I can use the single function above to retrieve the data from the databases. This is how the function is used:</p>\n\n<pre><code>$totalDays = 31;\n\n$query = \"SELECT COUNT(*) AS eventCount,\n DATE(date) AS eventDate,\n $totalDays - DATEDIFF(date, curdate()) AS dayNo\n FROM tblticketlog\n WHERE DATE(date) &gt; date_sub(curdate(),INTERVAL $totalDays day) AND \n dayofweek(date) NOT IN (1,7) AND \n ((action = 'New Support Ticket Opened') OR \n (action LIKE 'Status changed to Pending%') OR \n (action LIKE 'Status changed to In Progress%') OR \n (action LIKE 'New Ticket Response made by%'))\n GROUP BY ticketDate \n ORDER BY ticketDate\";\n\n$dailyTickets = selectDailyEvents($db, $query);\n\n$query = \"SELECT COUNT(*) AS eventCount,\n DATE(esc_at) AS eventDate, \n $totalDays - DATEDIFF(date, curdate()) AS dayNo\n FROM escalations\n WHERE DATE(esc_at) &gt; date_sub(curdate(), INTERVAL $totalDays day) AND \n dayofweek(esc_at) NOT IN (1,7) AND \n escalated = 1 \n GROUP BY escalationDate \n ORDER BY escalationDate\";\n\n$dailyEscalations = selectDailyEvents($db2, $query);\n</code></pre>\n\n<p>These two queries are exactly the same ones as you have, except that I added the <code>GROUP BY</code> and <code>ORDER BY</code>. I also added a <code>dayNo</code> in the output, because that indicates which day it is in the sequence.</p>\n\n<p>Now we have two arrays, <code>$dailyTickets</code> and <code>$dailyEscalations</code>, which needs to be rearranged for the graph. We use a loop to go over each day:</p>\n\n<pre><code>$graphData = [];\n\nfor ($dayNo = 0; $dayNo &lt; $totalDays; $dayNo++) {\n $ticketCount = 0;\n if (isset($dailyTickets[$dayNo])) {\n $eventDate = $dailyTickets[$dayNo][\"eventDate\"];\n $ticketCount = $dailyTickets[$dayNo][\"eventCount\"];\n }\n $escalationCount = 0;\n if (isset($dailyEscalations[$dayNo])) {\n $eventDate = $dailyEscalations[$dayNo][\"eventDate\"];\n $escalationCount = $dailyEscalations[$dayNo][\"eventCount\"];\n }\n if (isset($eventDate)) {\n $serviceLevel = round(100 * ($ticketCount - $escalationCount) / $ticketCount, 0);\n $readableDate = date(\"d-m-Y\", strtotime($eventDate));\n $graphData[] = ['x' =&gt; $dayNo,\n 'label' =&gt; $readableDate,\n 'y' =&gt; $serviceLevel];\n }\n}\n</code></pre>\n\n<p>I'm not sure the result of this last bit of code is exactly what you need, but with a bit of debugging you should be able to get there. As I said before: I cannot test this. The database queries are probably correct.</p>\n\n<p>I've also notice that your coding style is not optimal. Spacing is inconsistent. Also the naming of database columns and PHP variables could be improved. That means <code>escalated_at</code> instead of <code>esc_at</code> and <code>$ticketCount</code> or <code>$escalationCount</code> instead of <code>$day_result_value</code>. Always try to make your code as easy to read as possible.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T15:12:30.130", "Id": "437561", "Score": "0", "body": "Thankyou for all of that, I appreciate the time spent to try and decipher my quite obviously \"hacky\" code. I didnt realise you'd replied, and actually spent this mornign rewriting most of what I was doign to only query the DB's once each and then loop on the returned rows to push values into the array. I got the PHP processing time down form 9+ seconds to 488ms, whcih I'm happy with considering what I started with. That said, my code is still very different to your suggestions, so I'll make some adjustments and adopt more elements of your suggestions there. Thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T21:26:56.867", "Id": "225301", "ParentId": "225264", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T12:32:35.617", "Id": "225264", "Score": "3", "Tags": [ "performance", "php", "mysql" ], "Title": "Building CanvasJS Graph Datapoints in PHP Loop (MySQL Backend)" }
225264
<blockquote> <p>SUMMER OF '69: Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 9 (every 6 will be followed by at least one 9). Return 0 for no numbers.</p> </blockquote> <p>My solution:</p> <pre><code>def summer_sum(a_list): """ Use a stack to solve the problem. 1. If current num is '6', push '0' on the stack. 2. If current num is not '6' and the stack is empty, add it. 3. If current num is '9' and the stack is not empty, pop the stack. """ exclude_stack = [] total = 0 for num in a_list: if num == 6: exclude_stack.append(0) elif not len(exclude_stack): total += num elif num == 9 and len(exclude_stack): exclude_stack.pop() return total </code></pre> <p>Questions:</p> <ol> <li>Is this implementation correct?</li> <li>Is the time complexity of the this implementation O(n)?</li> <li>Is there a better/faster way to solve the problem?</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T14:14:48.660", "Id": "437315", "Score": "8", "body": "If you're not sure the implementation is correct, why not write some tests?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T14:18:49.487", "Id": "437316", "Score": "2", "body": "What does `[6,9,9]` return? What does `[9]` return?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T15:59:39.903", "Id": "437344", "Score": "0", "body": "@benrudgers I did write my tests and the program seems to work correctly. However, It's possible that I may have missed something and that others could have noticed easily. That's why I said it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T16:00:49.157", "Id": "437345", "Score": "0", "body": "@benrudgers `[6, 9, 9]` returns 9. `[9]` returns 9." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T16:40:29.583", "Id": "437351", "Score": "0", "body": "This might give you an idea of the time complexity https://www.reddit.com/r/Python/comments/8g8vh6/understanding_why_this_is_faster/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T18:50:16.790", "Id": "437377", "Score": "1", "body": "@pacmaninbw Yeah, I saw that. And that's something I don't understand. The guy in the comment section used the index method which is O(n) and then says it's O((k+j)logn). What? Also, I don't think that implementation considers nested cases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T20:00:28.093", "Id": "437398", "Score": "0", "body": "What should the answer be for an input of [6, 6, 9, 5]? Your code assumes every 6 has a corresponding 9, whereas the question only states that there is no 6 without a 9 to its right." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T23:04:56.733", "Id": "437445", "Score": "1", "body": "@spyr03 `[6, 6, 9, 5]` returns 0. The question says, \"every 6 will be followed by at least one 9.\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T15:52:16.937", "Id": "437570", "Score": "0", "body": "@sg7610 I don't understand the question at all if you get an answer of 0. I would have expected to group/remove elements \"flatten\" like this `[6, 6, 9] + [5] == [] + [5] -> 5` or \"nested\" like`[6, [6, 9], 5] == [6, 5] -> invalid input`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T22:19:48.697", "Id": "437625", "Score": "2", "body": "I don't understand why this question is downvoted. Looks like a valid code review request. I've seen much worse posts with lots of upvotes." } ]
[ { "body": "<p>Your code looks good. It's always nice to see people following PEP 8. There is a small issue though with how you check if a list is empty or not. Currently you write \n<code>elif not len(exclude_stack):</code> or <code>elif num == 9 and len(exclude_stack):</code> but PEP 8 actually has the following <a href=\"https://www.python.org/dev/peps/pep-0008/#programming-recommendations\" rel=\"nofollow noreferrer\">recommendation</a> for this kind of tests:</p>\n\n<blockquote>\n <p>For sequences, (strings, lists, tuples), use the fact that empty\n sequences are false.</p>\n\n<pre><code>Yes: if not seq: \n if seq:\n\nNo: if len(seq): \n if not len(seq):\n</code></pre>\n</blockquote>\n\n<p>So, in your case, it should be <code>elif not exclude_stack:</code> and <code>elif num == 9 and exclude_stack:</code>.</p>\n\n<p>Additionally, the details on implementation in the docstring look redundant, I would remove them and leave only the task description.</p>\n\n<p>The main question I have regarding your implementation is: Do you really need to have the stack to keep track if you are inside the 6-9 section? If I print <code>exclude_stack</code> for this input <code>summer_sum([6] * 10 + [9] * 10)</code>, it will look like this:</p>\n\n<pre><code>[0]\n[0, 0]\n[0, 0, 0]\n[0, 0, 0, 0]\n[0, 0, 0, 0, 0]\n[0, 0, 0, 0, 0, 0]\n[0, 0, 0, 0, 0, 0, 0]\n[0, 0, 0, 0, 0, 0, 0, 0]\n[0, 0, 0, 0, 0, 0, 0, 0, 0]\n[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n[0, 0, 0, 0, 0, 0, 0, 0, 0]\n[0, 0, 0, 0, 0, 0, 0, 0]\n[0, 0, 0, 0, 0, 0, 0]\n[0, 0, 0, 0, 0, 0]\n[0, 0, 0, 0, 0]\n[0, 0, 0, 0]\n[0, 0, 0]\n[0, 0]\n[0]\n[]\n</code></pre>\n\n<p>This doesn't really look like the most optimal solution memory-wise. How about keeping a track of the 6-9 sections by simply incrementing/decrementing some integer variable instead? Something like this:</p>\n\n<pre><code>def summer_sum(a_list):\n \"\"\"Solution for Summer 69 challenge\"\"\"\n section_depth = 0\n total = 0\n for num in a_list:\n if num == 6:\n section_depth += 1\n elif section_depth == 0:\n total += num\n elif num == 9 and section_depth &gt; 0:\n section_depth -= 1\n return total\n</code></pre>\n\n<p>I assume this will be also a bit faster as you won't have to pop or append to a list.</p>\n\n<p>My hands are also itching to remove the <code>total</code> variable and make a generator function, but this may be a bit overboard:</p>\n\n<pre><code>def summer_sum(a_list):\n \"\"\"Solution for Summer 69 challenge\"\"\"\n\n def free_numbers(numbers):\n section_depth = 0\n for num in numbers:\n if num == 6:\n section_depth += 1\n elif section_depth == 0:\n yield num\n elif num == 9 and section_depth &gt; 0:\n section_depth -= 1\n\n return sum(free_numbers(a_list))\n\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T22:18:37.537", "Id": "225385", "ParentId": "225266", "Score": "4" } } ]
{ "AcceptedAnswerId": "225385", "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T12:51:06.017", "Id": "225266", "Score": "0", "Tags": [ "python", "performance", "programming-challenge", "complexity" ], "Title": "Python Implementation: Summer of 69" }
225266
<p>The description of the problem is:</p> <blockquote> <p>The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ?</p> </blockquote> <p>Here is my solution:</p> <pre><code>import heapq from math import sqrt def find_max_prime_factor(n: int) -&gt; int: ''' returns the largest prime factor of the non negative integer n :param n: the number we want to find the max prime factor of :return: the largest prime factor of n ''' max_heap = [] # Checking for 2 as prime factor if n % 2 == 0: heapq.heappush(max_heap, -2) # dividing by 2 until n becomes odd while n % 2 == 0: n = n/2 # dealing with odd numbers for i in range(3,int(sqrt(n)),2): if n % i == 0: heapq.heappush(max_heap,-1*i) while n % i == 0: n = n/i # dealing with case where n is a prime by itself if n &gt; 2: return n return heapq.heappop(max_heap) * (-1) </code></pre> <p>Here's some examples and test-cases:</p> <pre><code>from ProjectEuler.problem3 import find_max_prime_factor if __name__ == "__main__": # 13195 prime factors are 5,7,13,29 -&gt; returns 29 print(find_max_prime_factor(13195)) # 600851475143 prime factors are 6857,1471,839,71 -&gt; returns 6857 print(find_max_prime_factor(600851475143)) # 7 is prime therefor -&gt; returns 7 print(find_max_prime_factor(7)) # 3452656 prime factors are 2,31,6961 -&gt; returns 6961 print(find_max_prime_factor(3452656)) # 896776435 prime factors are 5,17,2549,4139 -&gt; returns 4139 print(find_max_prime_factor(896776435)) </code></pre> <p>Would love for feedback on my code.Thanks!</p>
[]
[ { "body": "<blockquote>\n<pre><code> max_heap = []\n</code></pre>\n</blockquote>\n\n<p>I think the essentially Hungarian naming here is actually fairly helpful, but it would be very useful to have a comment explaining that the library support is only for min heaps, so everything must be negated when pushed or popped.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> # Checking for 2 as prime factor\n if n % 2 == 0:\n heapq.heappush(max_heap, -2)\n # dividing by 2 until n becomes odd\n while n % 2 == 0:\n n = n/2\n # dealing with odd numbers\n for i in range(3,int(sqrt(n)),2):\n if n % i == 0:\n heapq.heappush(max_heap,-1*i)\n while n % i == 0:\n n = n/i\n</code></pre>\n</blockquote>\n\n<p>Reasonable use of a special case: I see you've given some thought to optimisation.</p>\n\n<p>It's better to use <code>-i</code> than <code>-1*i</code>, and <code>n // i</code> (since you want integer division) than <code>n / i</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> # dealing with case where n is a prime by itself\n</code></pre>\n</blockquote>\n\n<p>That's open to misinterpretation. Is it talking about the original value of <code>n</code> or the current value? I think I would phrase it</p>\n\n<pre><code> # if n &gt; 1 here then it's a prime\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> return heapq.heappop(max_heap) * (-1)\n</code></pre>\n</blockquote>\n\n<p>See previous point about unary minus.</p>\n\n<hr>\n\n<p>I wanted to address minor improvements before addressing the big one. Why use a heap at all? The largest prime is the last prime encountered, and there's no need to store the smaller ones. Removing the heap would make the code simpler and faster.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T14:21:10.357", "Id": "437317", "Score": "1", "body": "At first I thought about returning the whole prime factorization array, maybe for further utilization if needed, and thought that the max_heap would solve me both problems. in the context of this specific question you are totally right. thanks! :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T14:25:15.840", "Id": "437318", "Score": "0", "body": "By the way, why is -i better than using -1*i? I couldn't find it by googling." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T14:29:41.897", "Id": "437319", "Score": "1", "body": "It's easier to read, and (depending on compiler and architecture) may be faster." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T14:05:16.150", "Id": "225272", "ParentId": "225269", "Score": "3" } }, { "body": "<p>As you will quickly realize, a lot of Project Euler problems involve prime numbers. It is therefore a good idea to write a good prime generating function early on. I usually use a simple <a href=\"https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow noreferrer\">Sieve of Eratosthenes</a>. With that function it is easy to write a function that gets the prime factorization of a number (something you will also need again). After you got that, just use the built-in <code>max</code>.</p>\n\n<pre><code>from math import sqrt\nfrom itertools import takewhile\n\ndef prime_sieve(limit):\n prime = [True] * limit\n prime[0] = prime[1] = False\n\n for i, is_prime in enumerate(prime):\n if is_prime:\n yield i\n for n in range(i * i, limit, i):\n prime[n] = False\n\ndef prime_factors(n, primes=None):\n limit = int(sqrt(n)) + 1\n if primes is None:\n primes = prime_sieve(limit)\n else:\n primes = takewhile(lambda p: p &lt; limit, primes)\n for p in primes:\n while n % p == 0:\n yield p\n n //= p\n if n &gt; 1: # n is prime\n yield n\n\nif __name__ == \"__main__\":\n print(13195, max(prime_factors(13195)))\n print(600851475143, max(prime_factors(600851475143)))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T16:22:53.987", "Id": "225363", "ParentId": "225269", "Score": "2" } } ]
{ "AcceptedAnswerId": "225272", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T13:30:16.660", "Id": "225269", "Score": "4", "Tags": [ "python", "python-3.x", "programming-challenge", "primes" ], "Title": "Project Euler - Problem 3" }
225269
<h2>Problem</h2> <p>The following statistical functions were created to calculate statistics of experiments:</p> <ul> <li>Mean</li> <li>Peak to Peak</li> <li>Standard Deviation</li> <li>Variance</li> <li>Mean Absolute Error (MAE)</li> <li>Mean Square Error (MSE)</li> <li>Root Mean Square Error (RMSE)</li> </ul> <p>So there are some statistics that needs an ideal point and some that doesn't.</p> <p>The following image contains the data:</p> <p><a href="https://i.stack.imgur.com/AySds.png" rel="noreferrer"><img src="https://i.stack.imgur.com/AySds.png" alt="Data" /></a></p> <p>Where there are two columns, the first contains the measured value and the second the quantity that the data repeats.</p> <h2>Statistical UDFs</h2> <p>Each function will have as input only the first data column and the quantities must be on the right.</p> <h3>Mean</h3> <p>The function on G3 is <code>=MeanArr(C2:C20)</code></p> <p>And the code is:</p> <pre><code>Public Function MeanArr(rng As Range) As Double Dim Arr() Dim ws As Worksheet Dim i As Long, j As Long Set ws = Application.Caller.Parent Dim cell As Range With ws For Each cell In rng If cell.Offset(0, 1) &gt; 1 Then ReDim Preserve Arr(cell.Offset(0, 1) + j - 1) For i = 0 To cell.Offset(0, 1) - 1 Arr(j + i) = cell Next i j = j + i ElseIf cell.Offset(0, 1) = 1 Then ReDim Preserve Arr(cell.Offset(0, 1) + j - 1) i = 0 Arr(j + i) = cell j = j + 1 End If Next cell 'Mean MeanArr= Application.WorksheetFunction.Average(Arr) End With Exit Function ErrHandler: MeanArr = &quot;Error&quot; End Function </code></pre> <p>It is <a href="http://mathworld.wolfram.com/ArithmeticMean.html" rel="noreferrer">the Arithmetic Mean</a>:</p> <p><a href="https://i.stack.imgur.com/Rmybd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Rmybd.png" alt="Mean" /></a></p> <h3>Peak to Peak</h3> <p>The function on G4 is <code>=PeaktoPeak(C2:C20)</code></p> <p>And the code is:</p> <pre><code>Public Function PeaktoPeak(rng As Range) As Double Dim Arr() Dim ws As Worksheet Dim i As Long, j As Long Set ws = Application.Caller.Parent Dim cell As Range With ws For Each cell In rng If cell.Offset(0, 1) &gt; 1 Then ReDim Preserve Arr(cell.Offset(0, 1) + j - 1) For i = 0 To cell.Offset(0, 1) - 1 Arr(j + i) = cell Next i j = j + i ElseIf cell.Offset(0, 1) = 1 Then ReDim Preserve Arr(cell.Offset(0, 1) + j - 1) i = 0 Arr(j + i) = cell j = j + 1 End If Next cell 'Peak to Peak PeaktoPeak = WorksheetFunction.Max(Arr) - WorksheetFunction.Min(Arr) End With Exit Function ErrHandler: PeaktoPeak = &quot;Error&quot; End Function </code></pre> <p>Peak to Peak is the amplitude of the data, it is the max minus the min.</p> <h3>Standard Deviation</h3> <p>The function on G5 is <code>StdDeviation(C2:C20)</code>.</p> <pre><code>Public Function StdDeviation(rng As Range) As Double Dim Arr() Dim ws As Worksheet Dim i As Long, j As Long Set ws = Application.Caller.Parent Dim cell As Range With ws For Each cell In rng If cell.Offset(0, 1) &gt; 1 Then ReDim Preserve Arr(cell.Offset(0, 1) + j - 1) For i = 0 To cell.Offset(0, 1) - 1 Arr(j + i) = cell Next i j = j + i ElseIf cell.Offset(0, 1) = 1 Then ReDim Preserve Arr(cell.Offset(0, 1) + j - 1) i = 0 Arr(j + i) = cell j = j + 1 End If Next cell 'Standard Deviation StdDeviation = WorksheetFunction.StDev(Arr) End With Exit Function ErrHandler: StdDeviation = &quot;Error&quot; End Function </code></pre> <p>The <a href="http://mathworld.wolfram.com/StandardDeviation.html" rel="noreferrer">standard deviation</a> is a measure that is used to quantify the amount of variation or dispersion of a set of data values.</p> <p><a href="https://en.wikipedia.org/wiki/Standard_deviation" rel="noreferrer">Wikipedia</a></p> <h3>Variance</h3> <p>The function on G7 is <code>=Variance(C2:C20)</code></p> <pre><code>Public Function Variance(rng As Range) As Double Dim Arr() Dim ws As Worksheet Dim i As Long, j As Long Set ws = Application.Caller.Parent Dim cell As Range With ws For Each cell In rng If cell.Offset(0, 1) &gt; 1 Then ReDim Preserve Arr(cell.Offset(0, 1) + j - 1) For i = 0 To cell.Offset(0, 1) - 1 Arr(j + i) = cell Next i j = j + i ElseIf cell.Offset(0, 1) = 1 Then ReDim Preserve Arr(cell.Offset(0, 1) + j - 1) i = 0 Arr(j + i) = cell j = j + 1 End If Next cell 'Var Variance = WorksheetFunction.Var(Arr) End With Exit Function ErrHandler: Variance = &quot;Error&quot; End Function </code></pre> <p>The <a href="http://mathworld.wolfram.com/Variance.html" rel="noreferrer">Variance</a> is the expectation of the squared deviation of a random variable from its mean. Informally, it measures how far a set of (random) numbers are spread out from their average value.</p> <p><a href="https://en.wikipedia.org/wiki/Variance" rel="noreferrer">Wikipedia</a></p> <h3>Mean Absolute Error (MAE)</h3> <p>The function on G6 is <code>=MAE(C2:C20;B1)</code></p> <pre><code>Public Function MAE(rng As Range, ideal As Double) As Double Dim Arr() Dim ws As Worksheet Dim i As Long, j As Long Dim Sum As Double Set ws = Application.Caller.Parent Dim cell As Range With ws For Each cell In rng If cell.Offset(0, 1) &gt; 1 Then ReDim Preserve Arr(cell.Offset(0, 1) + j - 1) For i = 0 To cell.Offset(0, 1) - 1 Arr(j + i) = cell Next i j = j + i ElseIf cell.Offset(0, 1) = 1 Then ReDim Preserve Arr(cell.Offset(0, 1) + j - 1) i = 0 Arr(j + i) = cell j = j + 1 End If Next cell 'y=y1-t_ideal; %t_ideal is the square wave of ideal communication and y1 the test vector For i = LBound(Arr) To UBound(Arr) Arr(i) = Arr(i) - ideal Next i '%Absolute Value For i = LBound(Arr) To UBound(Arr) Arr(i) = Abs(Arr(i)) Next i 's=sum(se); Sum = 0 For i = LBound(Arr) To UBound(Arr) Sum = Sum + Arr(i) Next i 'Mean Absolute Error MAE = Sum / (UBound(Arr) + 1) End With Exit Function ErrHandler: MAE = &quot;Error&quot; End Function </code></pre> <p>The <a href="https://medium.com/@ewuramaminka/mean-absolute-error-mae-sample-calculation-6eed6743838a" rel="noreferrer">Mean Absolute Error</a> is a measure of difference between two continuous variables. Consider a scatter plot of n points, where point i has coordinates (xi, yi)... Mean Absolute Error (MAE) is the average vertical distance between each point and the identity line. MAE is also the average horizontal distance between each point and the identity line.</p> <p><a href="https://en.wikipedia.org/wiki/Mean_absolute_error" rel="noreferrer">Wikipedia</a></p> <p>Calculated by the following formula:</p> <p><a href="https://i.stack.imgur.com/pqLYY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pqLYY.png" alt="MAE" /></a></p> <h3>Mean Squared Error (MSE)</h3> <p>The function on G2 is <code>MSE(C2:C20;B1)</code></p> <pre><code>Public Function MSE(rng As Range, ideal As Double) As Double Dim Arr() Dim ws As Worksheet Dim i As Long, j As Long Dim Sum As Double Set ws = Application.Caller.Parent Dim cell As Range With ws For Each cell In rng If cell.Offset(0, 1) &gt; 1 Then ReDim Preserve Arr(cell.Offset(0, 1) + j - 1) For i = 0 To cell.Offset(0, 1) - 1 Arr(j + i) = cell Next i j = j + i ElseIf cell.Offset(0, 1) = 1 Then ReDim Preserve Arr(cell.Offset(0, 1) + j - 1) i = 0 Arr(j + i) = cell j = j + 1 End If Next cell 'y=y1-t_ideal; %t_ideal is the square wave of ideal communication and y1 the test vector For i = LBound(Arr) To UBound(Arr) Arr(i) = Arr(i) - ideal Next i '%Square Error, where .^ is used to square vector For i = LBound(Arr) To UBound(Arr) Arr(i) = Arr(i) ^ 2 Next i 's=sum(se); Sum = 0 For i = LBound(Arr) To UBound(Arr) Sum = Sum + Arr(i) Next i 'mse=s/n; %Mean Square Error MSE = Sum / (UBound(Arr) + 1) End With Exit Function ErrHandler: MSE = &quot;Error&quot; End Function </code></pre> <p>The <a href="https://www.freecodecamp.org/news/machine-learning-mean-squared-error-regression-line-c7dde9a26b93/" rel="noreferrer">Mean Squared Error</a> of an estimator (of a procedure for estimating an unobserved quantity) measures the average of the squares of the errors—that is, the average squared difference between the estimated values and what is estimated.</p> <p><a href="https://en.wikipedia.org/wiki/Mean_squared_error" rel="noreferrer">Wikipedia</a></p> <p>Formula:</p> <p><a href="https://i.stack.imgur.com/9ru6h.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/9ru6h.gif" alt="MSE" /></a></p> <h3>Root Mean Square Deviation (RMSE)</h3> <p>The formula on G1 is <code>=RMSE(C2:C20;B1)</code></p> <pre><code>Public Function RMSE(rng As Range, ideal As Double) As Double Dim Arr() Dim ws As Worksheet Dim i As Long, j As Long Dim Soma As Double, MSE As Double Set ws = Application.Caller.Parent Dim cell As Range With ws For Each cell In rng If cell.Offset(0, 1) &gt; 1 Then ReDim Preserve Arr(cell.Offset(0, 1) + j - 1) For i = 0 To cell.Offset(0, 1) - 1 Arr(j + i) = cell Next i j = j + i ElseIf cell.Offset(0, 1) = 1 Then ReDim Preserve Arr(cell.Offset(0, 1) + j - 1) i = 0 Arr(j + i) = cell j = j + 1 End If Next cell 'y=y1-t_ideal; %t_ideal is the square wave of ideal communication and y1 the test vector For i = LBound(Arr) To UBound(Arr) Arr(i) = Arr(i) - ideal Next i '%Square Error, where .^ is used to square vector For i = LBound(Arr) To UBound(Arr) Arr(i) = Arr(i) ^ 2 Next i 's=sum(se); Sum = 0 For i = LBound(Arr) To UBound(Arr) Sum = Sum + Arr(i) Next i 'mse=s/n; %Mean Square Error MSE = Sum / (UBound(Arr) + 1) 'rmse=sqrt(mse) %Root Mean Square Error RMSE = Sqr(MSE) End With Exit Function ErrHandler: RMSE = &quot;Error&quot; End Function </code></pre> <p><a href="http://statweb.stanford.edu/%7Esusan/courses/s60/split/node60.html" rel="noreferrer">Root Mean Square Deviation (RMSE)</a> is a frequently used measure of the differences between values (sample or population values) predicted by a model or an estimator and the values observed.</p> <p><a href="https://en.wikipedia.org/wiki/Root-mean-square_deviation" rel="noreferrer">Wikipedia</a></p> <p>Formula:</p> <p><a href="https://i.stack.imgur.com/5hUds.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5hUds.png" alt="RMSE" /></a></p> <h2>Questions</h2> <ul> <li>How is the performance? Can it improve?</li> <li>Are the results ok? Are the functions working properly?</li> <li>How to make a proper <code>ErrHandler</code>?</li> <li>Should i use <code>WorksheetFunction</code> or created my own UDFs? If the quantity of data gets really large.</li> <li>I was thinking... Should I use a Global Array for each Sheet? So it doesn't have to calculate an array of data for each function again?</li> <li>Further tips/help are welcome. Or another improvements.</li> </ul> <p>Just for reference:</p> <ul> <li><a href="https://medium.com/human-in-a-machine-world/mae-and-rmse-which-metric-is-better-e60ac3bde13d" rel="noreferrer">MAE and RMSE — Which Metric is Better?</a></li> <li><a href="http://people.duke.edu/%7Ernau/compare.htm" rel="noreferrer">How to compare models</a></li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T20:42:46.997", "Id": "437407", "Score": "1", "body": "Be aware there are 2 different formulas for stddev, one for a population and one for a sample space. This also have an effect on related formulas, like variance and stderr." } ]
[ { "body": "<p>Here are some ideas on improvements you can make in the overall code, presented in an example for one of the math functions. The ideas can be applied to all the other functions as well.</p>\n\n<p>My lead-in to the rest of my comments and examples primarily deal with highly repeated logic in all of your functions. A big clue is when you end up copying a section of code into another function, you should STOP and consider creating a single common function. This \"functional isolation\" of logic makes your code more consistent and greatly helps when changes need to be made to the logic. You only have to make the change in once place.</p>\n\n<p>So my first comments deals with your input range to all your functions. Each function seems to require a two-column range with both values and quantities. This is perfectly fine, but if that's the case then your input range should also be a two-column range. Your example accepts a one-column range and uses <code>Offset</code> to check the quantity value. This is a mis-match between what you <strong>think</strong> is the input range: single-column, but really using two. So bottom line is to make your input range match what the UDF is actually using.</p>\n\n<p>Along those lines, each UDF should perform checks against the input values to ensure they match the expectations of your function. In my example below, I've created an <code>InputCheck</code> function that can be called from each of your UDFs, providing central (and functionally isolated) checks on your input data. My example only shows two quick checks, but you can add any other checks/tests as needed. I highly recommend reading <a href=\"http://www.cpearson.com/excel/ReturningErrors.aspx\" rel=\"nofollow noreferrer\">Chip Pearson's Returning Errors From User Defined Functions In VBA</a> for guidance. Returning errors from UDFs in this manner means that \"error handling\" won't stop execution or use a pop-up <code>MsgBox</code> -- any error will be indicated in the cell.</p>\n\n<pre><code>Private Function InputCheck(ByRef dataRange As Variant) As Long\n '--- returns 0 if all checks pass!!\n\n '--- input must be a range\n If Not TypeName(dataRange) = \"Range\" Then\n InputCheck = xlErrRef\n Exit Function\n End If\n\n '--- input range must be one or two columns ONLY\n If (dataRange.Columns.Count &lt; 1) Or (dataRange.Columns.Count &gt; 2) Then\n InputCheck = xlErrRef\n Exit Function\n End If\n\n '--- all cells MUST contain numeric values\n Dim cell As Variant\n For Each cell In dataRange\n If Not IsNumeric(cell) Then\n InputCheck = xlErrNum\n Exit Function\n End If\n Next cell\n\n '--- create any other checks for valid input data...\n\n '--- everything looks good!\n InputCheck = 0\nEnd Function\n</code></pre>\n\n<p><em>(You'll notice that I'm sneaking in an extra check I'll show later. But basically it's if the UDF is called with a single column of data everything will still work.)</em></p>\n\n<p>Now you can create a common block at the beginning of each of your UDFs that will return a valid error code to the worksheet cell:</p>\n\n<pre><code> Dim checkResult As Long\n checkResult = InputCheck(dataRange)\n If checkResult &lt;&gt; 0 Then\n QtyMean = CVErr(checkResult)\n Exit Function\n End If\n</code></pre>\n\n<p>Your next section of common logic builds an array of values from the input data, including repeating values based on the quantity indicator. I've also moved this logic into its own isolated function.</p>\n\n<p>One step in speed improvement is to perform most of your logic in memory-based arrays instead of directly interacting with the worksheet or range object. So the first thing to do is move the input range to an array. You can then make a quick check and if it's a single-column, then you're all done. If there are two columns, the logic proceeds almost identically to your original code. Note that you can pre-determine the size of your return array by summing the quantities in the second column. This avoids the expense of <code>ReDim Preserve</code> during code execution.</p>\n\n<pre><code>Private Function GetDataArray(ByRef srcRange As Variant) As Variant\n Dim theSourceData As Variant\n theSourceData = srcRange.Value\n If srcRange.Columns.Count = 1 Then\n '--- only one column, so we're done!\n GetDataArray = theSourceData\n Exit Function\n End If\n\n '--- we're building a single array and (possibly) repeating values\n ' based on the quantity indicator in the second column, so...\n\n '--- size the results array first...\n Dim resultsSize As Long\n Dim n As Long\n For n = LBound(theSourceData, 1) To UBound(theSourceData, 1)\n resultsSize = resultsSize + theSourceData(n, 2)\n Next n\n\n Dim resultArray() As Variant\n ReDim resultArray(0 To resultsSize)\n\n '--- ... now build the array and repeat values as necessary\n Dim i As Long\n Dim j As Long\n For n = LBound(theSourceData, 1) To UBound(theSourceData, 1)\n If theSourceData(n, 2) &gt; 1 Then\n '--- repeat values in the array\n For i = 0 To theSourceData(n, 2) - 1\n resultArray(j + i) = theSourceData(n, 1)\n Next i\n j = j + i\n ElseIf theSourceData(n, 2) = 1 Then\n '--- only a single value\n i = 0\n resultArray(j + i) = theSourceData(n, 1)\n j = j + 1\n End If\n Next n\n GetDataArray = resultArray\nEnd Function\n</code></pre>\n\n<p>Since this function returns a well-crafted array of values, the only thing left is the math logic. So my example UDF for calculating the Mean is</p>\n\n<pre><code>Public Function QtyMean(ByRef dataRange As Variant) As Double\n '--- accepts a one- or two-column range where column 1 holds the\n ' values and (the optional) column 2 holds the quantities\n Dim checkResult As Long\n checkResult = InputCheck(dataRange)\n If checkResult &lt;&gt; 0 Then\n QtyMean = CVErr(checkResult)\n Exit Function\n End If\n\n Dim dataWithQty As Variant\n dataWithQty = GetDataArray(dataRange)\n\n If IsArray(dataWithQty) Then\n QtyMean = Application.WorksheetFunction.Average(dataWithQty)\n Else\n QtyMean = CVErr(xlErrValue)\n End If\nEnd Function\n</code></pre>\n\n<p>Some end notes on the example code:</p>\n\n<ul>\n<li>Most parameters are passed as <code>Variant</code> because it forces (reminds) me to perform all input error checking in my UDF and supporting functions. Excel will convert some inputs for you, but can't always know exactly what you're expecting and which appropriate error should be raised.</li>\n<li>Use more descriptive names for your variables. It makes the code more readable and self-documenting. As an example, your <code>Arr</code> array variable is not hard to figure out but when I use <code>resultArray</code> it makes more sense when \"reading\" the code.</li>\n<li>Each of your functions consistently sets up a worksheet variable <code>ws</code> but never uses it. I can recommend a tool such as <a href=\"http://rubberduckvba.com/\" rel=\"nofollow noreferrer\">Rubberduck</a> that can help with code quality checks like this. (Disclaimer: I have nothing to do with Rubberduck, just a satisfied user)</li>\n</ul>\n\n<p>Here's the whole example module:</p>\n\n<pre><code>Option Explicit\n\nPublic Function QtyMean(ByRef dataRange As Variant) As Double\n '--- accepts a one- or two-column range where column 1 holds the\n ' values and (the optional) column 2 holds the quantities\n Dim checkResult As Long\n checkResult = InputCheck(dataRange)\n If checkResult &lt;&gt; 0 Then\n QtyMean = CVErr(checkResult)\n Exit Function\n End If\n\n Dim dataWithQty As Variant\n dataWithQty = GetDataArray(dataRange)\n\n If IsArray(dataWithQty) Then\n QtyMean = Application.WorksheetFunction.Average(dataWithQty)\n Else\n QtyMean = CVErr(xlErrValue)\n End If\nEnd Function\n\nPrivate Function GetDataArray(ByRef srcRange As Variant) As Variant\n Dim theSourceData As Variant\n theSourceData = srcRange.Value\n If srcRange.Columns.Count = 1 Then\n '--- only one column, so we're done!\n GetDataArray = theSourceData\n Exit Function\n End If\n\n '--- we're building a single array and (possibly) repeating values\n ' based on the quantity indicator in the second column, so...\n\n '--- size the results array first...\n Dim resultsSize As Long\n Dim n As Long\n For n = LBound(theSourceData, 1) To UBound(theSourceData, 1)\n resultsSize = resultsSize + theSourceData(n, 2)\n Next n\n\n Dim resultArray() As Variant\n ReDim resultArray(0 To resultsSize)\n\n '--- ... now build the array and repeat values as necessary\n Dim i As Long\n Dim j As Long\n For n = LBound(theSourceData, 1) To UBound(theSourceData, 1)\n If theSourceData(n, 2) &gt; 1 Then\n '--- repeat values in the array\n For i = 0 To theSourceData(n, 2) - 1\n resultArray(j + i) = theSourceData(n, 1)\n Next i\n j = j + i\n ElseIf theSourceData(n, 2) = 1 Then\n '--- only a single value\n i = 0\n resultArray(j + i) = theSourceData(n, 1)\n j = j + 1\n End If\n Next n\n GetDataArray = resultArray\nEnd Function\n\nPrivate Function InputCheck(ByRef dataRange As Variant) As Long\n '--- returns 0 if all checks pass!!\n\n '--- input must be a range\n If Not TypeName(dataRange) = \"Range\" Then\n InputCheck = xlErrRef\n Exit Function\n End If\n\n '--- input range must be one or two columns ONLY\n If (dataRange.Columns.Count &lt; 1) Or (dataRange.Columns.Count &gt; 2) Then\n InputCheck = xlErrRef\n Exit Function\n End If\n\n '--- all cells MUST contain numeric values\n Dim cell As Variant\n For Each cell In dataRange\n If Not IsNumeric(cell) Then\n InputCheck = xlErrNum\n Exit Function\n End If\n Next cell\n\n '--- create any other checks for valid input data...\n\n '--- everything looks good!\n InputCheck = 0\nEnd Function\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T21:07:23.503", "Id": "225296", "ParentId": "225271", "Score": "3" } }, { "body": "<p>Standard public announcement: always include <code>Option Explicit</code> at the top of modules.</p>\n\n<h2>How to improve performance</h2>\n\n<p>Two tips here:</p>\n\n<ul>\n<li>Put your range into an array and work with the array, not Excel\nobjects. The switching between Excel and VBA models is computationally expensive.</li>\n<li>Avoid wherever possible <code>ReDim</code>ming and <code>Preserve</code>-ing arrays. They are computationally expensive.</li>\n</ul>\n\n<p>To use your first function as an example</p>\n\n<pre><code>Public Function MeanArr(rng As Range) As Double '&lt;-- I will make a comment about this later\n'Error checks required for if the user selected a single cell, or if they selected more than one column.\n\n Dim initialValues as Variant '&lt;-- create an array here\n Dim initialQuantities as Variant '&lt;-- be explicit with all values you want to use\n initialValues = rng.Value \n initialQuantities = rng.Offset(0,1).Value\n 'Dim Arr() ' &lt;-- This would have been an array of variants, which is subtly different \n Dim i As Long, j As Long\n Dim totalSum as Double, totalCount as Double \n For j = LBound(initialValues,1) to UBound(initialValues,1)\n 'Error checking required for valid input - is it really a Number?\n totalCount = totalCount + CDbl(initialQuantities(j,1))\n totalSum = totalSum + CDBL(initialValues(j,1)) * CDbl(initialQuantities(j,1))\n\n Next j\n MeanArr = totalSum / totalCount\n\n Exit Function '&lt;--- left this here for now but will address errors later.\nErrHandler:\n MeanArr = \"Error\" '&lt;-- I will make a comment about this later\n\nEnd Function\n</code></pre>\n\n<p>You don't use <code>ws</code> (yes, you have a <code>With</code> statement, but how the code is written, that <code>With</code> is not used. Nor is it needed!</p>\n\n<p>I was going to use a Collection instead of an expanding array - but turns out not necessary in this case. However, for the more complex formulae, consider using a Collection instead of an array, or try to resize the array only once at the beginning. See <a href=\"https://stackoverflow.com/a/56842847/9101981\">https://stackoverflow.com/a/56842847/9101981</a></p>\n\n<h2>Are the functions working correctly?</h2>\n\n<p>I don't know - I hope they are otherwise this post is off-topic and I am wasting my time on this response! However, you can derive tests to ensure your own correctness.</p>\n\n<h2>Proper error handling</h2>\n\n<p>You are creating a UDF - Let Excel do some of the work for you.</p>\n\n<pre><code>Public Function MeanArr(rng As Range) As Variant '&lt;-- significant\n'Error checks required for if the user selected a single cell, or if they selected more than one column.\n\n If rng.Columns.Count &gt; 1 then\n MeanArr = CVErr(xlErrName)\n Exit Function\n End If\n\n Dim initialValues as Variant '&lt;-- create an array here\n Dim initialQuantities as Variant '&lt;-- be explicit with all values you want to use\n initialValues = rng.Value \n initialQuantities = rng.Offset(0,1).Value\n\n Dim j As Long\n Dim totalSum as Double, totalCount as Double \n For j = LBound(initialValues,1) to UBound(initialValues,1)\n 'Error checking required for valid input - is it really a Number?\n If Not IsNumeric() or Not IsNumeric() Then\n MeanArr = CVErr(xlErrNum)\n Exit Function\n End If\n totalCount = totalCount + CDbl(initialQuantities(j,1))\n totalSum = totalSum + CDBL(initialValues(j,1)) * CDbl(initialQuantities(j,1))\n\n Next j\n MeanArr = CDbl(totalSum / totalCount)\n' Error handling is now done in the code logic. \nEnd Function\n</code></pre>\n\n<p>Leaving the function return type as Variant is deliberate, it means that you can control what is returned and use the in-built error types to indicate to your user any issues. It also means that if you link the results cell to any other cell, Excel knows how to handle chained errors. Excel might misinterpret a random string (\"error\") potentially hiding issues from the user if you didn't use the built in types.</p>\n\n<h2>Use Worksheet functions?</h2>\n\n<p>This is an 'it depends' answer. For speed, writing your own routines will generally be faster. However, some of the more complex functions, using the built in worksheet function may be easier. Trade off against your own requirements, just remember that every switch to the Excel model costs.</p>\n\n<h2>Use Global Array?</h2>\n\n<p>Definitely not. You are writing portable, reusable UDFs which take a range as a parameter. Using a global variable just ties you down with no flexibility.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T21:13:34.767", "Id": "225298", "ParentId": "225271", "Score": "2" } } ]
{ "AcceptedAnswerId": "225296", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T14:02:52.213", "Id": "225271", "Score": "6", "Tags": [ "vba", "excel", "statistics" ], "Title": "Statistical User-Defined Functions (UDF)" }
225271
<p>There's this simple coding challenge that feels like a twist on FizzBuzz. Your task is to convert a number to a string, the contents of which depends on the number's factors.</p> <blockquote> <ul> <li>If the number has 3 as a factor, output 'Pling'. </li> <li>If the number has 5 as a factor, output 'Plang'.</li> <li>If the number has 7 as a factor, output 'Plong'. </li> <li>If the number does not have 3, 5, or 7 as a factor, just pass the number's digits straight through.</li> </ul> </blockquote> <p>For example, the sample output would look like this:</p> <blockquote> <p>28's factors are 1, 2, 4, <strong>7</strong>, 14, 28. In raindrop-speak, this would be a simple "Plong".</p> <p>30's factors are 1, 2, <strong>3</strong>, <strong>5</strong>, 6, 10, 15, 30. In raindrop-speak, this would be a "PlingPlang".</p> </blockquote> <p>I've come up with a working solution (based on the test suite results). However, I'm not really happy with it, as I feel this could be simplified. Thus, I'd appreciate some feedback.</p> <p><strong>My solution:</strong></p> <pre><code>SOUNDS = {3: "Pling", 5: "Plang", 7: "Plong"} FACTORS = (3, 5, 7) def is_divisible_by(number, divisior): return number % divisior == 0 def raidndrops(number): return [SOUNDS[factor] for factor in FACTORS if is_divisible_by(number, factor)] def convert(number): speak = raidndrops(number) return "".join(speak) if speak else str(number) </code></pre> <p><strong>The test suite is here:</strong></p> <pre><code>import unittest from raindrops import convert class RaindropsTest(unittest.TestCase): def test_the_sound_for_1_is_1(self): self.assertEqual(convert(1), "1") def test_the_sound_for_3_is_pling(self): self.assertEqual(convert(3), "Pling") def test_the_sound_for_5_is_plang(self): self.assertEqual(convert(5), "Plang") def test_the_sound_for_7_is_plong(self): self.assertEqual(convert(7), "Plong") def test_the_sound_for_6_is_pling(self): self.assertEqual(convert(6), "Pling") def test_2_to_the_power_3_does_not_make_sound(self): self.assertEqual(convert(8), "8") def test_the_sound_for_9_is_pling(self): self.assertEqual(convert(9), "Pling") def test_the_sound_for_10_is_plang(self): self.assertEqual(convert(10), "Plang") def test_the_sound_for_14_is_plong(self): self.assertEqual(convert(14), "Plong") def test_the_sound_for_15_is_plingplang(self): self.assertEqual(convert(15), "PlingPlang") def test_the_sound_for_21_is_plingplong(self): self.assertEqual(convert(21), "PlingPlong") def test_the_sound_for_25_is_plang(self): self.assertEqual(convert(25), "Plang") def test_the_sound_for_27_is_pling(self): self.assertEqual(convert(27), "Pling") def test_the_sound_for_35_is_plangplong(self): self.assertEqual(convert(35), "PlangPlong") def test_the_sound_for_49_is_plong(self): self.assertEqual(convert(49), "Plong") def test_the_sound_for_52_is_52(self): self.assertEqual(convert(52), "52") def test_the_sound_for_105_is_plingplangplong(self): self.assertEqual(convert(105), "PlingPlangPlong") def test_the_sound_for_12121_is_12121(self): self.assertEqual(convert(12121), "12121") if __name__ == '__main__': unittest.main() </code></pre>
[]
[ { "body": "<p>Modular division is a well-known concept to almost everyone who has done any programming. In my opinion delegating it to a <code>is_divisible_by</code> function is not needed and only introduces unnecessary overhead by generating an additional function call. It's not like you are ever going to use any other implementation than using modular division. Instead I would simply inline it.</p>\n\n<p>While I am a fan of clear variable names, and <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> recommends against single letter variables, using <code>n</code> for a generic number (and <code>i</code> for a generic counting integer) is IMO acceptable and helps keeping lines short.</p>\n\n<p>Your <code>FACTORS</code> variable is only needed for the order, since it is just the keys of the dictionary. <a href=\"https://docs.python.org/3/whatsnew/3.7.html\" rel=\"nofollow noreferrer\">Since Python 3.7</a> the order of dictionaries is guaranteed to be insertion order (implemented since CPython 3.6), so you also don't need it for the order if you are using a modern version of Python.</p>\n\n<p>You have a spelling error in <code>raindrops</code> (but at least it is also present when calling it).</p>\n\n<p>The <code>convert</code> function can be a bit simplified by using <code>or</code>.</p>\n\n<pre><code>SOUNDS = {3: \"Pling\", 5: \"Plang\", 7: \"Plong\"}\n\ndef raindrops(n):\n return [sound for d, sound in SOUNDS.items() if n % d == 0]\n\ndef convert(n):\n return \"\".join(raindrops(n)) or str(n)\n</code></pre>\n\n<p>You could also get rid of the dictionary altogether and just use a list of tuples:</p>\n\n<pre><code>SOUNDS = [(3, \"Pling\"), (5, \"Plang\"), (7, \"Plong\")]\n\ndef convert(n):\n return \"\".join(sound for d, sound in SOUNDS if n % d == 0) or str(n)\n</code></pre>\n\n<p>Instead of having a lot of testcases, which takes a lot of manual typing to setup, group similar testcases together and use <a href=\"https://docs.python.org/3/library/unittest.html#distinguishing-test-iterations-using-subtests\" rel=\"nofollow noreferrer\"><code>unittest.TestCase.subTest</code></a>:</p>\n\n<pre><code>class RaindropsTest(unittest.TestCase):\n def test_known_results(self):\n test_cases = [(1, \"1\"), (3, \"Pling\"), ...]\n for n, expected in test_cases:\n with self.subTest(n=n, expected=expected)):\n self.assertEqual(convert(n), expected)\n</code></pre>\n\n<p>For successful test cases this reports as one test case, but if it fails the additional information passed as keyword arguments is shown (here purposefully broken by supplying the wrong expected output):</p>\n\n<pre><code>======================================================================\nFAIL: test_known_results (__main__.RaindropsTest) (expected='5', n=5)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"/tmp/test.py\", line 15, in test_known_results\n self.assertEqual(convert(n), expected)\nAssertionError: 'Plang' != '5'\n- Plang\n+ 5\n\n\n----------------------------------------------------------------------\nRan 1 test in 0.000s\n\nFAILED (failures=1)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T14:05:24.670", "Id": "437536", "Score": "0", "body": "I disagree with your suggestion to rely on a CPython-specific implementation detail. If you want an ordered dictionary, you should use an OrderedDict (https://docs.python.org/3/library/collections.html#collections.OrderedDict)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T14:10:32.347", "Id": "437537", "Score": "1", "body": "@WillDaSilva It is in the Python language specification since Python 3.7. Not just CPython. I just wanted to mention that you already have the feature (without the guarantee) if you have CPython 3.6. But I agree, if you want to communicate that the dictionary needs to be ordered, I would use an `OrderedDict` in production code. At least until Python 2.7 is completely obsolete and people have gotten used to dicts being ordered." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T14:13:27.247", "Id": "437541", "Score": "0", "body": "@WillDaSilva And here it would actually be even easier to use a list of tuples instead of any dictionary." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T15:45:10.763", "Id": "225276", "ParentId": "225275", "Score": "16" } } ]
{ "AcceptedAnswerId": "225276", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T15:20:09.537", "Id": "225275", "Score": "11", "Tags": [ "python", "python-3.x", "programming-challenge" ], "Title": "Raindrops in Python" }
225275
<p><strong>Brief:</strong></p> <p>This is a question geared towards optimization and general better coding practices. I'm self-taught in VBA so I'm cautious of bad practices, but they do come up. </p> <p><strong>My Reasoning:</strong></p> <p>I break the links (<code>break_links</code>) because these new files would be sent out and I don't want the external references to cause errors within the spreadsheet formulas. It also makes for better historical files IMO so as the main file is updated we have the historical numbers saved rather than referencing the new numbers. </p> <p>I did take this component from somewhere online, so I'm still unsure how things work when you put something like <code>(ByRef wb As Workbook)</code> into the sub name ie: when to do it, how to do it, etc.</p> <p>The <code>Name</code> reference is a cell that has a fiscal year and period labeled for historical files.</p> <p><strong>My Complaint:</strong></p> <p>Despite turning off screen updating and all that it still works like a clunky recorded macro where I sit for about 20-30 seconds while it does it's thing, and I'm just exploring to see if there's anything I can do to improve this.</p> <pre><code>Sub NewWorkbooks() 'This will make seperate workbooks for each of the tabs listed Dim wb As Workbook Dim NewBook As Workbook Dim ws As Worksheet Dim Name As String Name = ActiveWorkbook.Worksheets("Reference Tables").Range("_Name") Call TurnOffFunctions Set wb = ActiveWorkbook For Each ws In Workbooks("P&amp;L Master Sheet"). _ Worksheets(Array("Accessories", "Leather", "Residential", "Rugs")) ws.Copy Set NewBook = ActiveWorkbook With NewBook Call break_links(NewBook) .SaveAs Filename:="C:\Users\Monthly P&amp;L's\Historical Files\" &amp; "P&amp;L " &amp; Name &amp; " - " &amp; ws.Name .Close 'SaveChanges:=True End With Next Call TurnOnFunctions End Sub Sub break_links(ByRef wb As Workbook) Dim Links As Variant On Error Resume Next Links = wb.LinkSources(Type:=xlLinkTypeExcelLinks) On Error GoTo 0 If Not IsEmpty(Links) Then For i = 1 To UBound(Links) wb.BreakLink _ Name:=Links(i), _ Type:=xlLinkTypeExcelLinks Next i End If End Sub Private Sub TurnOffFunctions() Application.ScreenUpdating = False Application.DisplayStatusBar = False Application.DisplayAlerts = False Application.Calculation = xlCalculationManual Application.EnableEvents = False End Sub Private Sub TurnOnFunctions() Application.ScreenUpdating = True Application.DisplayStatusBar = True Application.DisplayAlerts = True Application.Calculation = xlCalculationAutomatic Application.EnableEvents = True End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T16:19:30.633", "Id": "437354", "Score": "0", "body": "Thanks I'm new enough that I didn't even realize that was it's own thing. How would I go about asking a moderator migrate it? Worst case I can copy and paste this there, but I don't want to have comments lost too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T16:22:30.023", "Id": "437355", "Score": "0", "body": "I flagged it for moderator intervention. If they deem that I'm correct, then they can migrate it over. Thanks for being open to learning how the site works! Again, I could even be wrong and that's the great thing about the way this site is set up. =)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T17:29:50.810", "Id": "437364", "Score": "1", "body": "Hi @RobertTodar looks like you were right and we got this where it belongs. I have a bunch of different subroutines I wrote where I would love to get some professional inputs, and I just want to make sure everything is where it belongs. Thanks for being helpful and understanding while I learn the ropes!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T17:46:37.980", "Id": "437373", "Score": "0", "body": "If the size of each sheet is significant (think 1MB+), you can try using .xlsb format. That does speed up loading and saving, in certain conditions significantly.\nThat's all I have though, so best of luck with your learning and development." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T17:49:50.007", "Id": "437374", "Score": "0", "body": "It was my understanding that an .xlsb file format doesn't support macros which is what I'm with here. The full file itself saved as an .xlsm is only 395KB so it's not really a concern." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T17:51:54.500", "Id": "437375", "Score": "0", "body": "That's not correct, the only difference to .xlsm is how the compression works IIRC (I'm 98% certain). But yes, with such small size, you'd likely see no improvements there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T18:57:07.727", "Id": "437378", "Score": "0", "body": "I looked into it more and I misunderstood, with an XLSB you can't distinguish at face value if there is a macro (like you would between xlsx vs. xlsm). That's where my confusion was. But like you said, the file is so small, but I do really like this idea for bigger files I have!!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T21:43:13.293", "Id": "437623", "Score": "0", "body": "The only part of code that can significantly be speed up is `break_links`. If you only want the values in the new workbooks then `Cells.Value = Cells.Value` would be faster then breaking a large number of links individually." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T12:59:00.840", "Id": "437671", "Score": "0", "body": "@TinMan So this sheet has 4 sheets that are having the links broken, I'm unsure if that's considered a large number or not. There are some formulas, but I suppose it's not a big deal to turn them to values since the work is done. I'll replaced the line `Call break_links(NewBook)` w/ `Cells.Value = Cells.Value` and it caused a run-time error." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T13:11:19.257", "Id": "437673", "Score": "0", "body": "@TinMan I also tried `ws.UsedRange.Value = ws.UsedRange.Value` and it didn't do the trick. I'll mention that the cells aren't all adjacent, but set up like a P&L statement breaking down costs and revenue etc." } ]
[ { "body": "<p>I do have a few suggestions:</p>\n\n<ul>\n<li>First of all, you don't need to reactivate your main\nworkbook every loop, since you hold it's reference in a variable\nanyway.</li>\n<li>Second, instead of creating new workbook and copying the sheet over, just make a copy to new workbook (i.e. wks.Copy creates copy in new workbook, you can then assign it to a variable since, as you said yourself, it is now the active workbook)</li>\n<li>Lastly, unless you want to remove the references (for example if the links contain sensitive information), then I wouldn't worry about it. Excel stores the last value from links in cache within the file.</li>\n</ul>\n\n<p>Depending on your setup, suggestion 2 might actually speed it up a little by reducing the number of actions.</p>\n\n<p>To copy sheet to new workbook, simply <code>ws.Copy</code>, then you can <code>set newWs = Activesheet</code> (or using your naming <code>set NewBook = Activeworkbook</code>) to save it's reference, or just skip that also and put <code>Activeworkbook</code> into your <code>With</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T15:51:02.070", "Id": "437356", "Score": "0", "body": "Hi Filcuk, thanks for your answer. Can you elaborate on how'd I'd go about doing your second suggestion? I would remove the `Set NewBook = Workbooks.Add` and instead just have the `ws.copy` and that's it?\n\nThe references I want to break for security and so if I open the files down the road (or anyone else with access) they don't accidentally update over the historical information (These are P&L statements rather than raw data).\n\nLastly, I'll test this, but I can safely delete the activate line in this instance? Cool!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T15:54:06.330", "Id": "437357", "Score": "0", "body": "@MarkS. the only instances I use .Activate is for freezing cells and on the end of a script, otherwise it should be avoided. As to the sheets, see my edit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T16:11:03.550", "Id": "437358", "Score": "0", "body": "I made the change to that section if you care to review. I appreciate your help and effort with this. I'm still new so I'm not sure if this is the type of question you'd mark as answered since I feel like this is one of those 'always improving' type things." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T16:23:59.767", "Id": "437359", "Score": "0", "body": "Oh yes, looking at it there's more. You save the new workbook, remove links and then save it again. Instead remove the links first then save and close. I'm also thinking that workbooks may recalculate on save (this happens even with calculations on manual). I'm on the road now, but if you have large ammount of formulas, it may be worth looking into. Again might not, depends on the contents." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T17:38:35.237", "Id": "437367", "Score": "0", "body": "I adjusted the code accordingly. Thanks again, I shifted the `Call break_lines` line so it's above the `Saveas` line, and effectively removed the `savechanges` line, since you're correct to say it's redundant. After the links are broken there's just a handful of formulas/sheet so it's not likely to make a big difference, but if it can run even a bit faster why not." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T15:46:09.243", "Id": "225281", "ParentId": "225280", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T15:33:26.193", "Id": "225280", "Score": "4", "Tags": [ "performance", "vba", "excel" ], "Title": "Exporting array of tabs to new workbooks, save them based on tab name" }
225280
<p>The task is to create two random teams from a list of players.</p> <p>Given an example of players = <code>["John", "Mike", "Alice", "Bob"]</code></p> <p>One example random team would be:</p> <pre><code>team1 = ["Mike", "Alice"]; team2 = ["John", "Bob"]; </code></pre> <p>This is my solution but I'm not sure how efficient it is because random can create same number for a number of times.</p> <p>The question to separate equally and randomly without repeating the same player.</p> <pre><code>using System; using System.Collections.Generic; public class Program { public static void Main(string[] args) { Random rnd = new Random(); var numbers = new List&lt;int&gt;(); var ilkListe = new List&lt;int&gt;(); var ikinciListe = new List&lt;int&gt;(); numbers.Add(1); numbers.Add(2); numbers.Add(3); numbers.Add(4); numbers.Add(5); numbers.Add(6); numbers.Add(7); numbers.Add(8); numbers.Add(9); numbers.Add(10); Console.WriteLine("LIST 1: " + numbers.Count); do { int sayi = numbers[rnd.Next(numbers.Count)]; if (!(ilkListe.Contains(sayi))) { Console.WriteLine(sayi); ilkListe.Add(sayi); } } while (ilkListe.Count &lt; numbers.Count / 2); Console.WriteLine("Ikinci liste"); do { int sayi = numbers[rnd.Next(numbers.Count)]; if (!(ilkListe.Contains(sayi)) &amp;&amp; !(ikinciListe.Contains(sayi))) { Console.WriteLine(sayi); ikinciListe.Add(sayi); } } while (ikinciListe.Count &lt; numbers.Count / 2); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T19:31:27.623", "Id": "437391", "Score": "4", "body": "Thanks for updating. I've looked through your code and it does seem like it does what it is supposed to do but in an inefficient way, so you've come to the right place." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T19:43:22.780", "Id": "437395", "Score": "0", "body": "@dfhwze it does not matter actually. The idea is same. I was just trying to simulate the task in an online editor." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T21:46:22.613", "Id": "437434", "Score": "7", "body": "I don't have time today to write an answer, but you should consider shuffling the array, then dividing into the two teams. That completes in deterministic time, whereas there's no guarantee that the presented algorithm will terminate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T22:26:57.297", "Id": "437441", "Score": "0", "body": "@Toby Speight thank you. \"shuffling the array\" do too much." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T03:06:19.003", "Id": "437452", "Score": "0", "body": "Actually: better than shuffling is simply to iterate through the elements, and assign each to a team (with 50% probability) until one of the teams is fully populated (effectively, a partial shuffle)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T14:12:38.550", "Id": "437540", "Score": "0", "body": "@TobySpeight: Your suggestion might work for the OP and it might not. Consider this... There are 100 players listed alphabetically. Using your suggestion, Xavier and Zak will almost always be on the same team, a violation of the OP's \"random teams\" condition." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T17:08:36.803", "Id": "437583", "Score": "0", "body": "A [Fisher-Yates](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) shuffle of an N-element array is bounded linear time, N-1 random calls. Once you have done that, a lot of problems including this one are trivial." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T20:38:54.490", "Id": "437618", "Score": "0", "body": "@Patricia, if implementing a Fisher-Yates shuffle (rather than using a library one), it's possible to stop after reaching element N/2, since the remaining steps serve only to re-order team 2." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T21:04:36.790", "Id": "437621", "Score": "0", "body": "@TobySpeight True. This is a special case of a problem for which I've used a truncated F-Y in the past, pick a random k element subset from an N element array." } ]
[ { "body": "<h3>Review</h3>\n\n<ul>\n<li>Don't use the main entry point to implement an algorithm. Create a method instead.</li>\n<li>Think about how to allow this method to be usable for all kinds of types, not just integers. You have implemented the algorithm for integers, yet you show an example with strings.</li>\n<li>When creating an algorithm, surely you have made some unit tests, at least for the happy paths. Feel free to include them in the question.</li>\n<li>Use clear variable names, and stick to one written language.</li>\n<li>Don't mix algorithm logic with Console output.</li>\n</ul>\n\n<p>A possible method signature could be:</p>\n\n<pre><code>public static IEnumerable&lt;IEnumerable&lt;T&gt;&gt; SplitRandom&lt;T&gt;(\n this IEnumerable&lt;T&gt; source, int targetCount)\n{\n // .. algorithm implementation\n}\n</code></pre>\n\n<p>Called as..</p>\n\n<pre><code>var names = new [] { \"John\", \"Mike\", \"Alice\", \"Bob\" };\nvar teams = names.SplitRandom(2);\n</code></pre>\n\n<p>Or as..</p>\n\n<pre><code>var numbers = Enumrable.Range(1, 10);\nvar numberGroups = numbers.SplitRandom(2);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T22:21:12.157", "Id": "437626", "Score": "0", "body": "I don't think IEnumerable is the correct signature. You need the length of the data and also to shuffle the data, too. So what you need is actually IReadOnlyCollection<T>. And the result is IReadOnlyList<IReadOnlyList<T>> (I'm not sure about the output type)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T20:17:20.510", "Id": "225292", "ParentId": "225287", "Score": "18" } }, { "body": "<pre><code>using System;\nusing System.Collections.Generic;\n\npublic class Program\n{\n\n public static void Main(string[] args)\n {\n List&lt;string&gt; players = new List&lt;string&gt;(new string[]{ \"John\", \"Mike\", \"Kate\", \"Michael\" });\n\n List&lt;string&gt; randomPlayers = ShuffleList&lt;string&gt;(players);\n\n List&lt;string&gt; team1 = randomPlayers.GetRange(0, (randomPlayers.Count - 1) / 2);\n List&lt;string&gt; team2 = randomPlayers.GetRange((randomPlayers.Count - 1) / 2, (randomPlayers.Count - 1));\n }\n\n public static List&lt;E&gt; ShuffleList&lt;E&gt;(List&lt;E&gt; inputList)\n {\n List&lt;E&gt; randomList = new List&lt;E&gt;();\n\n Random r = new Random();\n int randomIndex = 0;\n while (inputList.Count &gt; 0)\n {\n randomIndex = r.Next(0, inputList.Count); //Choose a random object in the list\n randomList.Add(inputList[randomIndex]); //add it to the new, random list\n inputList.RemoveAt(randomIndex); //remove to avoid duplicates\n }\n\n return randomList; //return the new random list\n }\n}\n</code></pre>\n\n<p>After a little search of \"array shuffle keyword\", rewrite the code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T03:10:34.600", "Id": "437453", "Score": "2", "body": "Welcome to Code Review! Just a friendly reminder that self-answers should still be in the form of a _review_ - you're expected to explain what's wrong with the original code, rather than simply posting a replacement. You'll find more guidance in the [help] (sorry, I don't have time to look it up for you right now - I'm in the middle of a very busy spell)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T05:43:29.580", "Id": "437468", "Score": "0", "body": "A quick and easy way I sometimes use to shuffle a list, is to simply order it by NewGuid. So you could do `randomPlayers = players.OrderBy(x => Guid.NewGuid());`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T14:47:31.463", "Id": "437548", "Score": "0", "body": "@dbso; I won't argue that order-by-guid isn't _quick and easy to write_, but it's too hacky to inline without comment, and if you're going to have a designated method for the task then you should do it correctly. The comments on [this answer](https://stackoverflow.com/a/4262134/10135377) discuss your suggestion, and the other answers there show better ways of shuffling in place." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T08:35:11.197", "Id": "437753", "Score": "0", "body": "That's an unnecessarily O(n^2) implementation of a linear problem. The splitting up afterwards is also incorrect." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T22:48:57.100", "Id": "225306", "ParentId": "225287", "Score": "0" } }, { "body": "<p>While your new solution does look somewhat better than the original, I would suggest that constantly removing elements from the list can be quite expensive. I would suggest shuffling or randomly sorting the list then simply divvying up the players to the teams.</p>\n\n<p>Also you're still putting the implementation in Main, instead of calling a method.</p>\n\n<p>Instead of hardcoding everything for 2 teams I would be in favor of allowing any number of teams as long as it's an exact divisor of the number of players.</p>\n\n<p>Instead of multidimensional lists, I would use a Dictionary where the Key is the name of the team and the players names are in a list.</p>\n\n<p>It could look something like this:</p>\n\n<pre><code>public static Dictionary&lt;int,List&lt;T&gt;&gt; MakeTeams&lt;T&gt;(this List&lt;T&gt; playerList, int numTeams)\n{\n\n int count = playerList.Count();\n if(count % numTeams != 0)\n {\n throw new ArgumentException(\"The number of players must be a multiple of numTeams to get even distribution of players\");\n }\n var randomList = playerList.OrderBy(x =&gt; Guid.NewGuid()).ToList();\n var teams = (from int i in Enumerable.Range(0, count)\n let item = randomList[i]\n group item by (i % numTeams) into team\n select team).ToDictionary(team =&gt; team.Key, team =&gt; team.ToList());\n\n return teams;\n}\n</code></pre>\n\n<p>This simply uses a number for the team name. If you wanted to get fancier with it you could add a string array of team names to use instead:</p>\n\n<pre><code>public static Dictionary&lt;string, List&lt;T&gt;&gt; MakeTeams&lt;T&gt;(this List&lt;T&gt; playerList, int numTeams, string[] teamNames)\n{\n if(teamNames.Length &lt; numTeams)\n {\n throw new ArgumentException(\"The number of team names must be equal to or greater than numTeams\");\n }\n int count = playerList.Count();\n if (count % numTeams != 0)\n {\n throw new ArgumentException(\"The number of players must be a multiple of numTeams to get even distribution of players\");\n }\n var randomList = playerList.OrderBy(x =&gt; Guid.NewGuid()).ToList();\n var teams = (from int i in Enumerable.Range(0, count)\n let item = randomList[i]\n group item by (i % numTeams) into team\n select team).ToDictionary(team =&gt; teamNames[team.Key], team =&gt; team.ToList());\n\n return teams;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T00:44:19.557", "Id": "437449", "Score": "6", "body": "Couple of things: Make the dictionary keys a generic type as well. Don't ask how many teams there are, just count how many keys you were given. Don't use random-guid-sort to shuffle ([lengthy discussion in comments](https://stackoverflow.com/a/4262134/10135377))." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T14:22:41.917", "Id": "437680", "Score": "0", "body": "I've seen `OrderBy(x => Guid.NewGuid())` repeatedly and it's an awful solution to shuffle a list. Not only is it non-intuitive, it's also slow, not guaranteed to work at all (there's no guarantee what type of GUID is created, the GUID only has to be unique) and worst of all it's subtly broken. A fisher yates shuffle is trivial to implement so don't skimp to save a few lines of code. (Using a proper PRNG for your random shuffle property is also wrong, so no just stick with fisher yates)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T23:45:33.817", "Id": "225309", "ParentId": "225287", "Score": "5" } }, { "body": "<p>All of <a href=\"https://codereview.stackexchange.com/a/225292/200133\">dfhwze</a>'s points are spot-on, and the only thing I can think of to add to his type-signature is that if you're unfamiliar with all of the syntax he's using <em>that's ok</em>.<br>\n<sub>(If you want to learn the stuff in question, search for \"inheritance\" (or \"interface\"), \"generics\", \"extension methods\", and possibly \"generators\" or \"yield\".)</sub></p>\n\n<h2>Regarding your actual algorithm:</h2>\n\n<p>The <strong>big red flag</strong> that your current algorithm isn't good is that you have two nearly-identical loops. That they happen to be <code>while</code> loops is a <strong>small red flag</strong>, which you noticed indirectly when you noted that <code>rnd.Next()</code> can yield duplicates. </p>\n\n<p>The algorithm you probably want is to first <strong>shuffle</strong> your source list, and then take sequential runs from it as needed.\nStack Exchange gives us usable implementations of both those steps. Only copy-paste them if you understand how they work and you want those exact methods lying around your code-base; most of the time it's better to re-write these things so that you're making the \"details\" decisions for yourself.</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/a/22668974/10135377\">This answer</a> gives us a nice implementation of <a href=\"http://en.wikipedia.org/wiki/Fisher-Yates_shuffle\" rel=\"noreferrer\">The Fisher–Yates shuffle</a>, which is efficient and appropriate. </li>\n<li><a href=\"https://stackoverflow.com/a/1396143/10135377\">This answer</a> gives us tidy slicing. (What <em>exactly</em> happens if <code>source.Count / (Double)size</code> isn't an integer?)</li>\n</ul>\n\n<p>There are some details that <em>probably</em> matter, like whether or not the original order of the elements needs to be preserved, or what should happen if the source list isn't evenly divisible into the number of buckets in question.</p>\n\n<p>And once you've resolved all of that, since you asked about efficiency, we can return to <a href=\"https://codereview.stackexchange.com/a/225292/200133\">dfhwze</a>'s function signature. Specifically, <code>this IEnumerable&lt;T&gt; source</code> is taken as an enumer<strong>able</strong> collection; the Fisher–Yates shuffle shuffles a list <strong>in place</strong>. It's <em>very tempting</em> to change the argument to <code>this IList&lt;T&gt; source</code>, so that if the calling context already has a list, we're can just use that one instead of calling <code>source.ToList()</code>. If you do it that way you'll have written a function that returns a computed value <em>and</em> modifies the contents of its argument; <strong>strongly consider not doing that</strong>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T12:54:19.757", "Id": "437527", "Score": "0", "body": "If you are looking for an efficient implementation I would probably just loop through the list once and randomly assign each player to one team, until one team is full, then all remaining players go to the other team. No shuffling and no reallocations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T14:11:20.873", "Id": "437539", "Score": "3", "body": "@Falco: Your suggestion might work for the OP and it might not. Consider this... There are 100 players listed alphabetically. Using your suggestion, Xavier and Zak will almost always be on the same team, a violation of the OP's \"random teams\" condition." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T16:03:26.350", "Id": "437577", "Score": "0", "body": "You are right, most simpler solutions have unwanted correlations between some players landing in the same team depending on position in the list. An inplace-shuffle and then taking two sub-lists is probably the best way." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T00:34:06.793", "Id": "225311", "ParentId": "225287", "Score": "5" } } ]
{ "AcceptedAnswerId": "225309", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T18:39:39.653", "Id": "225287", "Score": "6", "Tags": [ "c#", "array", "random" ], "Title": "Create two random teams from a list of players" }
225287
<ul> <li>I am doing a join in the axios call.</li> <li>since doing two different api calls.</li> <li>for performance is this the good way.</li> <li>or do I need to use async await and then do join.</li> <li>providing code snippet below</li> </ul> <pre class="lang-or-tag-here prettyprint-override"><code>export function getSearch(value) { console.log('-- getSearch value', value); return dispatch =&gt; { if (value.length) { if (typeof this._source !== 'undefined') { this._source.cancel('Operation canceled due to new request'); } this._source = axios.CancelToken.source(); return axios .get( `http://localhost:787878/hold/search?mode=Smart&amp;value=${value}`, { cancelToken: this._source.token, } ) .then(response =&gt; { console.log('search response.data--&gt;', response.data); let values = response.data.map(filterSearch =&gt; { if (filterSearch.playerIDs) { console.log( 'search response.data playerIDs', filterSearch.playerIDs[0] ); return filterSearch.playerIDs[0].number + ','; } }); console.log( 'search response.data join---&gt;', values.join('') ); axios .get( `http://localhost:787878/hold/animalworldCardList/?playerID=${values.join( '' )}&amp;isHistory=false`, //localhost:787878/hold/ce-affiliation/?animalPimsId=${animalPimsId}&amp;isHistory=${isHistory}`, { cancelToken: this._source.token, } ) .then(responseplayerIDs =&gt; { console.log( 'search response.data --&gt;', responseplayerIDs ); dispatch({ type: ANIMAL_SEARCH_DATA, payload: { animalSearch: response.data, playerIDs: responseplayerIDs.data.animalsInfo, }, }); // callBack(response); }) .catch(error =&gt; { if (axios.isCancel(error)) { console.log( '-- Request canceled', error.message ); } else { console.log('-- Error', error.message); } }); }) .catch(error =&gt; { if (axios.isCancel(error)) { console.log('-- Request canceled', error.message); } else { console.log('-- Error', error.message); } }); } else { dispatch({ type: ANIMAL_SEARCH_DATA, payload: [], }); } }; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T20:46:38.803", "Id": "437410", "Score": "0", "body": "1. Your bullet points don't quite make sense :)\n2. What do you mean by \"doing a join\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T20:52:31.833", "Id": "437412", "Score": "0", "body": "like I am joining the values and passing it in another api `{values.join(`" } ]
[ { "body": "<p>Using <code>Array.join</code> is unrelated to usage of <code>async</code> and <code>await</code>. Also note that the time it takes to call <code>Array.join</code> is insignificant in comparison to the time it takes to make the two API calls.</p>\n\n<p>You can consider <code>call1().then(data =&gt; call2(data))</code> roughly equivalent to <code>const data = await call1(); call2(data)</code>. There's no (obvious) performance gain to be made here by using <code>async</code>/<code>await</code> over <code>then</code>. You would have a slight readability gain though. Note that your second call is dependent on your first call. When this is <em>not</em> the case you can get a performance improvement by making both calls simultaneously like so <code>Promise.All([call1(), call2()])</code>. That is not applicable here, but maybe this was what you had in mind?</p>\n\n<p>The vast majority of the time here is spent waiting for the API calls. If you have ownership of the back end and want to improve performance, then I would suggest you consider creating a new endpoint that better fits your need so you only need to make one API call.</p>\n\n<p>Also I prefer <code>this._source !== undefined</code> over <code>typeof this._source !== 'undefined'</code>, but that's only if you're sure that <code>this._source</code> is declared.</p>\n\n<p>In general I think this code looks fine.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T21:09:06.747", "Id": "225297", "ParentId": "225291", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T20:07:00.417", "Id": "225291", "Score": "1", "Tags": [ "javascript", "react.js", "redux" ], "Title": "join method inside axios call" }
225291
<p>I find that very very often with matrix questions, the traversal and comparison part of the solution is very verbose and repetitive.</p> <p>For example, this code (written for a coding challenge) to find the number of pawns available for a rook to capture in one move on a chess board (<code>R</code> is a white rook, <code>B</code> is a white bishop, and <code>p</code> is a black pawn):</p> <pre><code>class Solution: def numRookCaptures(self, board: List[List[str]]) -&gt; int: for r in range(len(board)): for c in range(len(board[r])): if board[r][c] == 'R': return self.find_p(board, r, c) def find_p(self, board, r, c): count = 0 for i in range(r + 1, 8): if board[i][c] in ('B', 'p'): count += int(board[i][c] == 'p') break for i in range(r - 1, -1, -1): if board[i][c] in ('B', 'p'): count += int(board[i][c] == 'p') break for i in range(c + 1, 8): if board[r][i] in ('B', 'p'): count += int(board[r][i] == 'p') break for i in range(c - 1, -1, -1): if board[r][i] in ('B', 'p'): count += int(board[r][i] == 'p') break return count </code></pre> <p>This is the most concise way of writing it that I've found, without compromising clarity. The <code>in</code> for comparison and <code>int</code> for incrementing the count each save us a few lines of code.</p> <p>But, it's still really verbose and repetitive. Each of the <code>for</code> loops are essentially doing the same exact thing, just in a different direction.</p> <p>This comes up in every matrix question, whether it's just linear checks like above, BFS, DFS, they pretty much all have a four-directional comparison and traversal that produces 4 copies of code that are all identical in function.</p> <p>Is there a less verbose way of writing these, without being overly fancy and hard-to-read?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T20:55:44.600", "Id": "437413", "Score": "1", "body": "_This is the most concise way of writing it that I've found_ Do you mean that you have found somewhere online or have written yourself?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T21:03:18.287", "Id": "437414", "Score": "0", "body": "Both, but if you're asking if I wrote the code above, yes I did. Other code I've seen for similar questions has all been very verbose and messy, matrix questions always seem to produce messy/verbose code..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T21:47:57.660", "Id": "437435", "Score": "0", "body": "What does `B` in `('B', 'p')` signify?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T22:06:48.030", "Id": "437436", "Score": "0", "body": "`R` is a white rook, `B` is a white bishop, and `p` is a black pawn. `B` will block `R`'s movement." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T22:48:01.373", "Id": "437442", "Score": "2", "body": "The forced (because otherwise useless) `Solution` class seems to hint toward a programming challenge. If that really is the case, it might help to mention that in your question before a reviewer unnecessarily focuses on it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T05:11:55.137", "Id": "437462", "Score": "0", "body": "I don't think that this is a problem appropriate for code review. Actually the OP doesn't want us to review the posted code but want's some general advice on how to implement components of a chess program." } ]
[ { "body": "<h2>Dimensions</h2>\n\n<p>How big is your chess board, and is it square, or at least rectangular?</p>\n\n<p>First, you use <code>range(len(board))</code> to determine the rows of the chess board, but then you use <code>range(len(board[r]))</code> for the columns, which means you can handle each row having a different number of columns!</p>\n\n<p>(Supporting a non-rectangular chess board would be a challenging challenge, but totally possible, as demonstrated above.)</p>\n\n<p>But then, you use <code>range(r+1, 8)</code> and <code>range(c+1, 8)</code>, indicating that you only support square 8x8 chess boards.</p>\n\n<p>Unfortunately, you haven’t posted the challenge problem text, so we can only guess at the actual challenge. Additional context would go a long way.</p>\n\n<h2>Verbosity &amp; Fancyness</h2>\n\n<p>In order to be less verbose, we need to do something at least a little bit “fancy”. With only rook movements, it may seem overly fancy, but if you later support bishops and queens, the additional capability we build in will be leveraged, and very little code need be added.</p>\n\n<p>Additionally, you only need the white bishop blocking the white rook, and only black pawns being captured. What about white pawns with a black rook and bishop? This shouldn’t be a special case; it should be generalized. But again, generalization one one hand will be more verbose, and “fancy”, and the other hand will be leveraged to make the code agnostic to the current player.</p>\n\n<p>First of all, you should have an <code>on_board</code> function, which will return <code>True</code> if a given position is actually on the chess board. I’ll hard-code the board size, and assume the board is stored in <code>self</code>; the dimensions could be stored in <code>self</code> or derived from <code>self.board</code> on the fly.</p>\n\n<pre><code>def on_board(self, r, c):\n return r in range(8) and c in range(8)\n</code></pre>\n\n<p>Next, pieces get “blocked” by other pieces. So let’s formalize that. Again, I’ll assume the <code>piece</code> is the <code>'R'</code>, so any white (uppercase) piece will block it. (You should return the appropriate expression based on the colour of <code>piece</code> ... left to student)</p>\n\n<pre><code>def blocked(self, piece, r, c):\n return self.board[r][c].isupper()\n</code></pre>\n\n<p>A black pawn doesn’t “block” a white rook’s move, but it does terminate it in a “capture” event. Again, we’ll assume a white <code>piece</code> is moving, so it will “capture” any black (lowercase) piece. (Again, base actual return value on <code>piece</code> ... left to student)</p>\n\n<pre><code>def capture(self, piece, r, c):\n return self.board[r][c].islower()\n</code></pre>\n\n<p>Rooks, bishops, and queens can move in a straight line any number of spaces until blocked, or it captures another piece. Note that a blocked move is not a valid move, but a capture move is a valid move.</p>\n\n<pre><code>def direction_moves(self, piece, r, c, dr, dc):\n r += dr\n c += dc\n while self.on_board(r, c) and not self.blocked(piece, r, c):\n yield r, c\n if self.capture(piece, r, c):\n break\n r += dr\n c += dc\n</code></pre>\n\n<p>Rooks, bishops and queens can move in more than one direction, so let’s allow multiple directions to be given at once:</p>\n\n<pre><code>def linear_moves(self, piece, r, c, *dirs):\n for dr, dc in dirs:\n yield from self.direction_moves(piece, r, c, dr, dc)\n</code></pre>\n\n<p>Now that we have the building blocks, getting a rook’s moves from a given position is easy:</p>\n\n<pre><code>def rook_moves(self, piece, r, c):\n yield from self.linear_moves(piece, r, c, (1, 0), (0, 1), (-1, 0), (0, -1))\n</code></pre>\n\n<p>Moves for the piece at a given position might be:</p>\n\n<pre><code>def moves(self, r, c):\n piece = self.board[r][c]\n if piece in {'R', 'r'}: # Black or white rook\n yield from self.rook_moves(piece, r, c)\n # ... other types of pieces ...\n</code></pre>\n\n<p>With this, your <code>find_p</code> becomes trivial:</p>\n\n<pre><code>def find_p(self, r, c):\n return sum(1 for i, j in self.moves(r, c) if self.board[i][j] == 'p')\n</code></pre>\n\n<hr>\n\n<p>The above has increased the amount of code, but at the same time it is more generalized. It has work to be done to generalize it for white -vs- black. It would be trivial to add movements for bishops and queens to this structure, and that would not be repetitive code, unlike the original structure.</p>\n\n<p>Unfortunately, you may conclude that it has become overly “fancy”.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T05:26:06.947", "Id": "225320", "ParentId": "225293", "Score": "6" } } ]
{ "AcceptedAnswerId": "225320", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T20:54:24.703", "Id": "225293", "Score": "4", "Tags": [ "python", "python-3.x", "matrix", "chess" ], "Title": "Find the number of pawns available for a rook to capture" }
225293
<p>The following code has been tested on the latest chromium, on Opera Mini, on Safari for IOS 7 and finally, on the default web browser on android 2.3.3.</p> <p>As you may already know, the CSS <code>overflow</code> rule isnt supported on android 2.3.3 which makes sidenavs un-scrollable.</p> <p>Well, guess what? I found a workaround. See the following code:</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>//Import element cont=document.getElementById("content"); nav=document.getElementsByClassName("navbar"); opt=document.getElementsByClassName("option"); side=document.getElementById("sidenav"); side.style.display="none"; navtog(); function showhide(x){ if("transform" in document.body.style) { x.classList.toggle("change"); } //If sidenav open if(cont.style.left=="150px"){ //Sidenav stuff //Store sidenav pos sidepos=window.scrollY; //Move sidenav to pos (to remove wierd chunky animations) side.style.position="fixed"; side.style.top="-"+sidepos+"px"; cont.style.left=""; cont.style.position=""; cont.style.top="0px"; nav[0].style.left="0px"; //Scroll back to user pos window.scrollTo(0,pos); setTimeout(function() { side.style.display="none"; }, 200); }else{//sidenav closed //Store user POS pos=this.scrollY; cont.style.position="fixed"; cont.style.left="150px"; cont.style.top="-"+pos+"px"; nav[0].style.left="150px"; side.style.display="block"; //Make sidenav scrollable again side.style.top=""; side.style.position=""; if(typeof sidepos === 'undefined'){ sidepos=0; } window.scrollTo(0,0); } } window.onscroll = function() {navtog()}; function navtog(){ if(cont.style.left==""){ if(this.scrollY&lt;1){ nav[0].className="navbar"; }else{ nav[0].className="navbar shad"; } } } function bhov(el) { var els = Array.prototype.slice.call( document.getElementsByClassName('option'), 0 ); opt[els.indexOf(event.currentTarget)].className="option o-a"; } function bbay(el) { var els = Array.prototype.slice.call( document.getElementsByClassName('option'), 0 ); opt[els.indexOf(event.currentTarget)].className="option o-o"; }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body{ font-family:Helvetica, sans-serif; margin:0; color:white; background:#23272a; overflow-x:hidden; } /*Layout*/ #sidenav{ /*Important*/ width:150px; float:left; background:#23272a; } #content{ float:left; width:100%; position:absolute; left:0; padding-top:40px; background:#2c2f33; -webkit-transition:left 0.2s ease-out; -moz-transition:left 0.2s ease-out; -ms-transition:left 0.2s ease-out; transition:left 0.2s ease-out; -moz-box-shadow:0 0 20px rgba(0,0,0,0.5); -webkit-box-shadow:0 0 20px rgba(0,0,0,0.5); box-shadow:0 0 20px rgba(0,0,0,0.5); } /*Buttons*/ .option{ text-decoration:none; display:block; color:#99aab5; line-height:14px; font-size:12px; padding:10px; } .o-a{/*ACTIVE*/ color:white; } .o-o{/*OFF*/ color:#99aab5; -webkit-transition:color 0.2s ease-out; -moz-transition:color 0.2s ease-out; -ms-transition:color 0.2s ease-out; transition:color 0.2s ease-out; } /*Navbar*/ .navbar{ position:fixed; top:0; left:0; width:100%; height:40px; /*style*/ -webkit-transition:left 0.2s ease-out,background 0.2s; -moz-transition:left 0.2s ease-out,background 0.2s; -ms-transition:left 0.2s ease-out,background 0.2s; transition:left 0.2s ease-out,background 0.2s; } .shad{background:#99aab5;} /*Logo*/ .navbar img{ display:block; margin:0 auto; padding:5px; height:30px; } /*Ham menu*/ .ham{ width:40px; height:28px; position:absolute; top:5px; left:5px; /*style*/ border:1px solid white; border-radius:3px; cursor:pointer; } .bar1, .bar2, .bar3 { width: 30px; height: 4px; background: white; margin: 4px 5px; transition: 0.4s; border-radius:3px; } .change .bar1 {/*Gauche Haut*/ transform: rotate(45deg) translate(8px, -3px); width:16px; } .change .bar2 {opacity: 0;} .change .bar3 { transform: rotate(-45deg) translate(8px, 3px); width:16px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" charset="utf-8"&gt; &lt;link rel="stylesheet" type="text/css" href="style.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="page"&gt; &lt;div id="sidenav"&gt; &lt;a href="javascript:void(0);" class="option" onmouseover="bhov(this)" onmouseout="bbay(this)"&gt;Option #1&lt;/a&gt; &lt;a href="javascript:void(0);" class="option" onmouseover="bhov(this)" onmouseout="bbay(this)"&gt;Option #2&lt;/a&gt; &lt;a href="javascript:void(0);" class="option" onmouseover="bhov(this)" onmouseout="bbay(this)"&gt;Option #3&lt;/a&gt; &lt;a href="javascript:void(0);" class="option" onmouseover="bhov(this)" onmouseout="bbay(this)"&gt;Option #4&lt;/a&gt; &lt;a href="javascript:void(0);" class="option" onmouseover="bhov(this)" onmouseout="bbay(this)"&gt;Option #5&lt;/a&gt; &lt;a href="javascript:void(0);" class="option" onmouseover="bhov(this)" onmouseout="bbay(this)"&gt;Option #6&lt;/a&gt; &lt;a href="javascript:void(0);" class="option" onmouseover="bhov(this)" onmouseout="bbay(this)"&gt;Option #7&lt;/a&gt; &lt;a href="javascript:void(0);" class="option" onmouseover="bhov(this)" onmouseout="bbay(this)"&gt;Option #8&lt;/a&gt; &lt;a href="javascript:void(0);" class="option" onmouseover="bhov(this)" onmouseout="bbay(this)"&gt;Option #9&lt;/a&gt; &lt;a href="javascript:void(0);" class="option" onmouseover="bhov(this)" onmouseout="bbay(this)"&gt;Option #10&lt;/a&gt; &lt;a href="javascript:void(0);" class="option" onmouseover="bhov(this)" onmouseout="bbay(this)"&gt;Option #11&lt;/a&gt; &lt;a href="javascript:void(0);" class="option" onmouseover="bhov(this)" onmouseout="bbay(this)"&gt;Option #12&lt;/a&gt; &lt;a href="javascript:void(0);" class="option" onmouseover="bhov(this)" onmouseout="bbay(this)"&gt;Option #13&lt;/a&gt; &lt;a href="javascript:void(0);" class="option" onmouseover="bhov(this)" onmouseout="bbay(this)"&gt;Option #14&lt;/a&gt; &lt;a href="javascript:void(0);" class="option" onmouseover="bhov(this)" onmouseout="bbay(this)"&gt;Option #15&lt;/a&gt; &lt;a href="javascript:void(0);" class="option" onmouseover="bhov(this)" onmouseout="bbay(this)"&gt;Option #16&lt;/a&gt; &lt;a href="javascript:void(0);" class="option" onmouseover="bhov(this)" onmouseout="bbay(this)"&gt;Option #17&lt;/a&gt; &lt;a href="javascript:void(0);" class="option" onmouseover="bhov(this)" onmouseout="bbay(this)"&gt;Option #18&lt;/a&gt; &lt;a href="javascript:void(0);" class="option" onmouseover="bhov(this)" onmouseout="bbay(this)"&gt;Option #19&lt;/a&gt; &lt;a href="javascript:void(0);" class="option" onmouseover="bhov(this)" onmouseout="bbay(this)"&gt;Option #20&lt;/a&gt; &lt;a href="javascript:void(0);" class="option" onmouseover="bhov(this)" onmouseout="bbay(this)"&gt;Option #21&lt;/a&gt; &lt;a href="javascript:void(0);" class="option" onmouseover="bhov(this)" onmouseout="bbay(this)"&gt;Option #22&lt;/a&gt; &lt;a href="javascript:void(0);" class="option" onmouseover="bhov(this)" onmouseout="bbay(this)"&gt;Option #23&lt;/a&gt; &lt;a href="javascript:void(0);" class="option" onmouseover="bhov(this)" onmouseout="bbay(this)"&gt;Option #24&lt;/a&gt; &lt;/div&gt; &lt;div id="content"&gt; &lt;div class="navbar"&gt; &lt;div class="ham" onclick="showhide(this);"&gt; &lt;div class="bar1"&gt;&lt;/div&gt; &lt;div class="bar2"&gt;&lt;/div&gt; &lt;div class="bar3"&gt;&lt;/div&gt; &lt;/div&gt; &lt;img src="https://proxy.duckduckgo.com/ip3/codereview.stackexchange.com.ico"&gt; &lt;/div&gt; this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;&lt;a href="javascript:showhide();"&gt;showhide();&lt;/a&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt;this is some content&lt;br&gt; &lt;/div&gt; &lt;/div&gt; &lt;script src="script.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p><strong>How it works:</strong></p> <p>The page content (were the dummy content is+navbar) is set at <code>width="100%"</code></p> <p>when clicking on the hamburger menu, heres what happens</p> <p>1) We store the user scroll position before changing anything</p> <p>2) We set the page content to <code>position="fixed"</code></p> <p>3) We add the following property to the content: top="(page scroll position)";</p> <p>4) We make the sidenav go <code>display="block"</code> (if its not set as none when closed, sometimes, old browsers will click on the sidenav buttons even if closed)</p> <p>5) The page content goes <code>left:150px</code> (Lets not forget that CSS makes it transition between the two stages which makes it look real good)</p> <p>6) We also make the navbar go <code>left:150px</code> cause on old browsers, it doesnt moves (or glitches/stretches if youre on iOS 7 safari)</p> <p>7) The sidenav is now scrollable and the page content isnt. Yay!</p> <p>8) (optional) cool ass hover effect for items in the sidenav.</p> <p><strong>When closing the sidenav</strong></p> <p>Pretty much the reverse thing but we add those steps:</p> <p>1) The animation between open and closed lasts 0.2 seconds. Keep that in mind.</p> <p>2) We store the user's scroll position</p> <p>We add the following properties to the sidenav:</p> <p>3) <code>Position="fixed"</code></p> <p>4) <code>top="(scroll pos)"</code></p> <p><em>Wait 0.2 seconds</em></p> <p>5) <code>display="none"</code></p> <hr> <p>SO thats pretty much how it works... I may have brushed over some details tho, bare with me please, haha.</p> <p>Any suggestions? Ideas? Toughts? Do you think this could be used as production code?</p>
[]
[ { "body": "<p>This code appears to function correctly but I wouldn't use it in production unless it is cleaned up. See the suggestions below.</p>\n\n<p>The first five variables are declared as globals:</p>\n\n<blockquote>\n<pre><code>cont=document.getElementById(\"content\");\nnav=document.getElementsByClassName(\"navbar\");\nopt=document.getElementsByClassName(\"option\");\nside=document.getElementById(\"sidenav\");\nside.style.display=\"none\";\n</code></pre>\n</blockquote>\n\n<p>It would be wise to declare them with the <code>var</code> keyword, and wrap everything in an IIFE to avoid polluting the global namespace. For a small page this likely wouldn't be an issue but as a page grows into a single-page application or larger it could cause issues - for example if a variable name is used in different sections of code. </p>\n\n<p>Also <code>pos</code> should be declared at the top using <code>var</code> to avoid it being used as a global variable.</p>\n\n<hr>\n\n<p>The <code>onmouseover</code> and <code>onmousout</code> could be removed from all the anchors with class <code>option</code> by changing the CSS rulesets to use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/:hover\" rel=\"nofollow noreferrer\"><code>:hover</code> pseudo-class selector</a> though maybe some of those <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/:hover#Browser_compatibility\" rel=\"nofollow noreferrer\">mobile browsers would have compatitibilty issues</a>, depending on the version.</p>\n\n<p>Instead of using CSS selectors <code>.o-o</code> and <code>.o-a</code>, use <code>.option</code> and <code>.option:hover</code>, respectively. The styles under the <code>.o-o</code> ruleset can be moved up into the styles for <code>.option</code> (except for the color, since it is duplicate).</p>\n\n<hr>\n\n<p>The <code>onscroll</code> function can be simplified from </p>\n\n<blockquote>\n<pre><code>window.onscroll = function() {navtog()};\n</code></pre>\n</blockquote>\n\n<p>To simply a reference to the function name:</p>\n\n<pre><code>window.onscroll = navtog;\n</code></pre>\n\n<hr>\n\n<p>For the element with class <em>navbar</em> why not use an <code>id</code> attribute instead of class name? There only appears to be one of those elements and the JS code appears to be selecting the first element with that class so it could be selected by <code>id</code> instead. </p>\n\n<blockquote>\n<pre><code>&lt;div class=\"navbar\"&gt;\n</code></pre>\n</blockquote>\n\n<p>can be changed to </p>\n\n<pre><code>&lt;div id=\"navbar\"&gt;\n</code></pre>\n\n<p>Then </p>\n\n<blockquote>\n<pre><code>nav=document.getElementsByClassName(\"navbar\");\n</code></pre>\n</blockquote>\n\n<p>Can be changed to </p>\n\n<pre><code> nav=document.getElementById(\"navbar\");\n</code></pre>\n\n<p>And CSS selectors must be changed as well. </p>\n\n<p>Those functions <code>bhov</code> and <code>bbay</code> are quite inefficient - mostly because they get all elements with class name <code>option</code> each time either function is called and then look for the element in <code>opt</code>. Why not just use <code>event.currentTarget</code> and modify the <code>className</code> directly? If that doesn't work, then why re-query the DOM instead of using <code>opt</code> to copy elements into <code>els</code>?</p>\n\n<hr>\n\n<p>Indentation is not always consistent - many lines in the JavaScript are indented with a tab, while some of the lines in the <code>bhov</code> and <code>bbay</code> functions are indented with two spaces. And many of the CSS lines inside rulesets are not indented, whereas others are indented with two spaces.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T21:59:28.093", "Id": "225302", "ParentId": "225294", "Score": "2" } } ]
{ "AcceptedAnswerId": "225302", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T21:02:49.000", "Id": "225294", "Score": "5", "Tags": [ "javascript", "html", "css", "event-handling" ], "Title": "Responsive, scrollable sidenav for old browsers" }
225294
<p>The following classes are a simplification of an auto-generated code of an ORM (targeting Microsoft's Dynamics CRM):</p> <pre><code>public class Entity { public Dictionary&lt;string, object&gt; Fields { get; set;} public virtual T GetFieldValue&lt;T&gt;(string fieldName) { return (T)Fields[fieldName]; } protected virtual void SetFieldValue(string fieldName, object value) { Fields[fieldName] = value; } } partial class Account : Entity { public string Name get { return GetFieldValue&lt;string&gt;("Name"); } set { SetFieldValue("Name", value); } public string Email get { return GetFieldValue&lt;string&gt;("Email"); } set { SetFieldValue("Email", value); } } </code></pre> <p>When an <code>Entity</code>'s derived class is retrieved from the database, the base class <code>Fields</code> property is automatically assigned (again, this is not something in my control) with the selected fields.</p> <p>I'd like a review of the following class, intended to validate "partially" filled objects:</p> <pre><code>public class EntitySubset&lt;T&gt; : Entity where T : Entity { public EntitySubset(T subset) { foreach (var field in subset.Fields) { SetFieldValue(field.Key, field.Value); } } public override U GetFieldValue&lt;U&gt;(string fieldName) { if (!Fields.ContainsKey(fieldName)) { throw new Exception($"{typeof(T).Name} must contain {fieldName} as a key!"); } return base.GetFieldValue&lt;U&gt;(fieldName); } } </code></pre> <p>an example usage:</p> <pre><code>private List&lt;Account&gt; GetSimiliarAccounts(EntitySubset&lt;Account&gt; targetAccount) { var similarityFields = new[] { "Name", "Email" }; var similiarAccounts = db.Where(account =&gt; similarityFields.All(f =&gt; account.GetFieldValue&lt;object&gt;(f) == targetAccount.GetFieldValue&lt;object&gt;(f)) ).ToList(); return similiarAccounts; } </code></pre> <p>so that if <code>GetSimiliarAccounts</code> is called as follows:</p> <pre><code>GetSimiliarAccounts(new EntitySubset&lt;Account&gt;(new Account { Email = "b" })); </code></pre> <p>then the output is:</p> <pre><code>System.Exception: 'Account must contain Name as a key!' </code></pre> <p>Note that <code>EntitySubset&lt;T&gt;</code> and its error messaging is intended for developers to "fail fast", namely: to quickly spot and fix bugs stemming from a partially filled object.</p> <p>What do you think of <code>EntitySubset&lt;T&gt;</code> as a validation implementation?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T21:05:54.767", "Id": "437415", "Score": "1", "body": "Good to see your question back up, and with sufficient context." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T21:15:37.867", "Id": "437422", "Score": "1", "body": "Nothing ever is irrelevant around here :)" } ]
[ { "body": "<h3>Review</h3>\n\n<p>You should avoid hardcoded strings. Take advantage of <code>nameof</code>. Also, <em>expression-bodied members</em> (arrow notation) makes code cleaner to read.</p>\n\n<pre><code>public string Name\n{\n get =&gt; GetFieldValue&lt;string&gt;(nameof(Name));\n set =&gt; SetFieldValue(nameof(Name), value);\n}\n</code></pre>\n\n<p><code>EntitySubset&lt;T&gt;</code>'s method <code>GetFieldValue</code> makes sure a clean (but technical) error message is thrown whenever an asked field is not available. </p>\n\n<blockquote>\n<pre><code>public override U GetFieldValue&lt;U&gt;(string fieldName)\n{\n if (!Fields.ContainsKey(fieldName))\n {\n throw new Exception($\"{typeof(T).Name} must contain {fieldName} as a key!\");\n }\n return base.GetFieldValue&lt;U&gt;(fieldName);\n}\n</code></pre>\n</blockquote>\n\n<p>However, don't fallback to this method to perform business rules checks. The business layer should check that mandatory fields are filled in, before mapping the entities to the data layer.</p>\n\n<p>You should also optimize <code>ContainsKey</code> and <code>base.GetFieldValue</code>. You don't want to perform 2 lookups here. Implement something like a <code>TryGetFieldValue</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T21:27:16.510", "Id": "437425", "Score": "0", "body": "*\"The business layer should check that mandatory fields are filled in\"*: well, that's the purpose of `EntitySubset<T>`. Don't you consider it part of the business layer?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T21:28:51.063", "Id": "437426", "Score": "0", "body": "Perhaps so, but it's very generic (unspecific). I would argue you need a layer on top with specific rules and error messages tailored to the end-user. _EntitySubset_ is a last resort fallback (in my opinion)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T21:33:13.740", "Id": "437427", "Score": "0", "body": "I should've clarified (and I'm going to edit it into the question) that `EntitySubset<T>` and its error messaging is intended for developers to \"fail fast\", not for users. Note that an alternative input parameter for `GetSimiliarAccounts` is `Account`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T21:34:27.197", "Id": "437428", "Score": "0", "body": "You may edit the question to stipulate it's a technical error. That re-enforces the need for additional business rule validation a layer higher up the stack." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T21:36:30.113", "Id": "437429", "Score": "0", "body": "Can you give a concrete example for such additional business rule validation? I'm not sure what else is needed that is not already handled by `EntitySubset<T>`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T21:43:12.263", "Id": "437431", "Score": "0", "body": "Well business rules could check, not only on existence of the field, but also content. For instance, _if (string.IsNullOrEmpty(Account.Name)) throw .._" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T21:44:53.383", "Id": "437433", "Score": "0", "body": "Oh, sure. Thanks." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T21:22:04.207", "Id": "225299", "ParentId": "225295", "Score": "2" } } ]
{ "AcceptedAnswerId": "225299", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T21:03:50.640", "Id": "225295", "Score": "3", "Tags": [ "c#", "validation", "error-handling", "hash-map" ], "Title": "Validating partially filled objects" }
225295
<p>I'm trying to upgrade my javascript to be more functional. I have used function composition and curry successful on less complicated code but i'm now running into a point where i'm not sure on how to approach it.</p> <p>Given the below relational data structures.</p> <pre><code>// Contains all node types and its property definitions. Including any additional information like readable descriptions etc.. const nodes = [{ id: '0ec7deff-91af-e911-812a-00155d0a5146', description: 'Airplanes', properties: [{ id: '0fc7deff-91af-e911-812a-00155d0a5146', description: 'Weight' }, { id: '06c7deff-91af-e911-812a-00155d0a5146', description: 'Color' }] }, { id: '278182d0-4ba2-4813-b74e-277a2296e864', description: 'Manufacturers', properties: [{ id: '003e14d7-c11a-41e1-ad08-ab8896a3cb55', description: 'Boeing' }] }] // Contains only the to be used nodes and there relations(defined through children nodes) in the eventual output. The above definitions can be used to pull in additional data. const rootNode = { id: '0ec7deff-91af-e911-812a-00155d0a5146', properties: [{ id: '0fc7deff-91af-e911-812a-00155d0a5146', }], children: [{ id: '278182d0-4ba2-4813-b74e-277a2296e864', properties: [{ id: '003e14d7-c11a-41e1-ad08-ab8896a3cb55', }] }], } </code></pre> <p>The rootNode is the starting point. It can contain an infinite amount of children including properties that need to be displayed. Each node needs to be checked for child nodes and be added to the eventual result. For example a linear set to be displayed on the x axis where the properties will be shown on a next row also on the x axis.</p> <pre><code>[{ id: '0ec7deff-91af-e911-812a-00155d0a5146', description: 'Airplanes', properties: [{ id: '0fc7deff-91af-e911-812a-00155d0a5146', description: 'Weight' }] }, { id: '278182d0-4ba2-4813-b74e-277a2296e864', description: 'Manufacturers', properties: [{ id: '003e14d7-c11a-41e1-ad08-ab8896a3cb55', description: 'Boeing' }] }] </code></pre> <p>The eventual output will be shown in a 2 dimensional grid or table.</p> <pre><code>Airplanes Manufacturers Weight Boeing </code></pre> <p>Or in a more elaborate example if i would provide more data and a larger query.</p> <pre><code>Airplanes Manufacturers Weight Color Type Boeing Lockhead </code></pre> <p>I build a function that works and uses recursion but it just doesn't feel right. I want to pull it apart into smaller units. Note that lodash is used here, hence the shorthands etc.</p> <pre><code>function initializeNodeMapper(nodes) { const result = [] return function mapNodes(node) { const usedPropertyIds = map(node.properties, 'id') const currentNode = find(nodes, ['id', node.id]) const nodeWithReducedProperties = reduce(currentNode, (acc, value) =&gt; ({ ...acc, properties: filter(value, property =&gt; indexOf(usedPropertyIds, property.id) !== -1), }), currentNode) result.push(nodeWithReducedProperties) if (node.children &amp;&amp; node.children.length &gt; 0) { forEach(node.children, mapNodes) } return result } } const mapData = initializeNodeMapper(nodes) const mappedData = mapData(initialNode) </code></pre> <p>Using functional patterns i want to find a more optimal pattern of mapping and testing the code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T23:56:32.110", "Id": "437448", "Score": "1", "body": "@200_success Thanks! I've tried describing it a bit better." } ]
[ { "body": "<p>Some slight improvements:</p>\n\n<ul>\n<li>You could do without the <code>result</code> array (less state ).</li>\n<li>I think using vanilla object destructuring is more clear than the lowdash <code>reduce</code> method which is confusing to me (unless I <em>still</em> don't understand it and my code actually is not equivalent to yours ).</li>\n</ul>\n\n<pre class=\"lang-js prettyprint-override\"><code>const allNodes = [\n];\n\nconst rootNode = {\n};\n\nfunction initializeNodeMapper(nodes) {\n return function mapNodes(node) {\n const propertyIds = node.properties.map(({ id }) =&gt; id);\n const currentNode = nodes.find(({ id }) =&gt; id === node.id);\n const nodeWithFilteredProperties = {\n ...currentNode,\n properties: currentNode.properties.filter(({ id }) =&gt;\n propertyIds.includes(id)\n )\n };\n\n return node.children\n ? [nodeWithFilteredProperties].concat(node.children.map(mapNodes))\n : [nodeWithFilteredProperties];\n };\n}\n\nconst mappedData = initializeNodeMapper(allNodes)(rootNode);\n</code></pre>\n\n<p><strong>Update</strong>:</p>\n\n<p>Are you looking for something like this?</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>const nodes = [\n];\n\nconst rootNode = {\n};\n\nconst pipe = (...fns) =&gt; x =&gt; fns.reduce((v, f) =&gt; f(v), x);\n\nconst getFlattenedNodes = node =&gt;\n node.children\n ? [node].concat(\n node.children.reduce(\n (acc, val) =&gt; acc.concat(getFlattenedNodes(val)),\n []\n )\n )\n : [node];\n\nconst getPropertyIds = node =&gt; node.properties.map(({ id }) =&gt; id);\n\nconst getNodeWithProperties = nodesWithProperties =&gt; node =&gt;\n nodesWithProperties.find(({ id }) =&gt; id === node.id);\n\nconst getNodesWithFilteredProperties = propertyIdsAndNodesToBeFiltered =&gt;\n propertyIdsAndNodesToBeFiltered.map(([propertyIds, nodeWithProperties]) =&gt; ({\n ...nodeWithProperties,\n properties: nodeWithProperties.properties.filter(({ id }) =&gt;\n propertyIds.includes(id)\n )\n }));\n\nconst getPropertyIdsAndNodes = nodesWithProperties =&gt; flattenNodes =&gt;\n flattenNodes.map(node =&gt; [\n getPropertyIds(node),\n getNodeWithProperties(nodesWithProperties)(node)\n ]);\n\nconst mappedData = pipe(\n getFlattenedNodes,\n getPropertyIdsAndNodes(nodes),\n getNodesWithFilteredProperties\n)(rootNode);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T18:22:13.380", "Id": "437602", "Score": "0", "body": "Far more clearer with vanilla! Why did i not think of it before :) I have been thinking of how you could compose a mapper like this through compose or a pipe but i'm not sure if it is even possible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T23:40:17.947", "Id": "437629", "Score": "0", "body": "That's exactly what i had in mind but could not lay my finger on. Thanks! Your opening eyes. :) So in functional it's perfectly fine to compose recursive functions together? And i see you first call getPropertyIdsAndNodes which returns a function. I had been thinking about that approach but wondered if it would be a proper way of composing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-05T14:57:44.073", "Id": "438046", "Score": "0", "body": "> So in functional it's perfectly fine to compose recursive functions together?\nYou mean `getPropertyIdsAndNodes`? I don't think it's good code, it's a bit hard to read imo. But it's functional \n\nFeel free to accept the answer if it helped!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T16:34:21.567", "Id": "225364", "ParentId": "225304", "Score": "2" } } ]
{ "AcceptedAnswerId": "225364", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T22:40:26.010", "Id": "225304", "Score": "4", "Tags": [ "javascript", "functional-programming", "join", "lodash.js" ], "Title": "Finding optimal mapping patterns that transform relational data into a linear format" }
225304
<p>This code and updates are available on <a href="https://github.com/harleypig/dotfiles/blob/master/bin/showvars" rel="nofollow noreferrer">Github</a>.</p> <p>I've written a small utility to dump the variables that are assigned in a bash script.</p> <p>Please note:</p> <ul> <li>This script depends on the shfmt and jq apps.</li> <li>I am not looking to make this script posix compliant, only bash specific.</li> </ul> <p>Some possible areas for improvement:</p> <ul> <li>Can the jq query be improved?</li> <li>Are there other entries in the json output of shfmt that I can look for variable assignments.</li> <li>Any gotchas I'm missing?</li> </ul> <p>As I type out this question, it occurs to me that showing variables used in a script would be a good thing to allow as an option. I'll look into it, but if anyone has any ideas in this respect, I'm interested in hearing your input.</p> <pre class="lang-bsh prettyprint-override"><code>#!/bin/bash #------------------------------------------------------------------------------ warn() { printf '%s\n' "$*" &gt;&amp;2; } die() { (($#)) &amp;&amp; warn "$*" exit 1 } command_exists() { command -v "$1" &amp;&gt; /dev/null; } #------------------------------------------------------------------------------ _showvars() { local filename=$1 [[ -f $filename ]] || die "$filename is not a file or does not exist." [[ -r $filename ]] || die "$filename is not readable." jq_query='[ .. | select(.Assigns?) | .. | select(.Name?) | .Name.Value ] | unique[]' # shellcheck disable=SC2046 printf ' %s\n' $(shfmt -tojson &lt; "$filename" | jq "$jq_query" | tr -d '"') } #------------------------------------------------------------------------------ (($#)) || { cat &lt;&lt; EOH showvars is a simple script that shows what variables are assigned in a bash script usage: showvars filename [filename ...] EOH exit 1 } for r in shfmt jq; do command_exists $r || die This script depends on $r and it is not found. done for f in "$@"; do printf '\n%s:\n' "$f" _showvars "$f" shift done echo </code></pre> <p>Edit: Fixed copy-paste error with <code>(($#))...</code> line Edit: Removed code that removes lower case variables (an artifact from another code solution)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T18:16:41.337", "Id": "437601", "Score": "1", "body": "Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 4 → 3" } ]
[ { "body": "<h3>The difference between <code>$*</code> and <code>$@</code></h3>\n\n<blockquote>\n<pre><code>warn() { printf '%s\\n' \"$*\" &gt;&amp;2; }\n</code></pre>\n</blockquote>\n\n<p>This is equivalent to the simpler:</p>\n\n<pre><code>warn() { echo \"$*\" &gt;&amp;2; }\n</code></pre>\n\n<p>The <code>printf</code> version is useful if you want to produce one line per parameter,\nand in that case you must use <code>\"$@\"</code> instead of <code>\"$*\"</code>.\nAlso in callers of <code>warn</code>.</p>\n\n<h3>Use <code>-r</code> for raw output of <code>jq</code></h3>\n\n<p>Instead of <code>jq \"...\" | tr -d '\"'</code> a better way is <code>jq -r \"...\"</code>.</p>\n\n<h3>An alternative to <code>printf</code> and a sub-shell</h3>\n\n<p>Instead of this:</p>\n\n<blockquote>\n<pre><code> # shellcheck disable=SC2046\n printf ' %s\\n' $(shfmt -tojson &lt; \"$filename\" | jq \"$jq_query\" | tr -d '\"')\n</code></pre>\n</blockquote>\n\n<p>I recommend this way (and no need to disable shellcheck):</p>\n\n<pre><code>shfmt -tojson &lt; \"$filename\" | jq -r \"$jq_query\" | sed -e 's/^/ /'\n</code></pre>\n\n<h3>Use a bit more double-quotes</h3>\n\n<p>You did a good job of double-quoting the most important things.\nI would double-quote here too:</p>\n\n<blockquote>\n<pre><code>command_exists $r || die This script depends on $r and it is not found.\n</code></pre>\n</blockquote>\n\n<p>To train good habits:</p>\n\n<pre><code>command_exists \"$r\" || die \"This script depends on $r and it is not found.\"\n</code></pre>\n\n<h3><code>\"$@\"</code> is the default list for <code>for</code></h3>\n\n<p>Instead of <code>for f in \"$@\"; do</code>, you can simply write <code>for f; do</code>.</p>\n\n<h3>The shebang</h3>\n\n<p>In some systems Bash is not in <code>/bin/bash</code>.\nFor that reason I prefer to use <code>#!/usr/bin/env bash</code> as the shebang, it makes the script more portable.</p>\n\n<h3>Simplify the readable file check?</h3>\n\n<blockquote>\n<pre><code> [[ -f $filename ]] || die \"$filename is not a file or does not exist.\"\n [[ -r $filename ]] || die \"$filename is not readable.\"\n</code></pre>\n</blockquote>\n\n<p>The <code>-r</code> implies <code>-f</code>. I would simplify this to one line:</p>\n\n<pre><code>[[ -r $filename ]] || die \"$filename is not a readable file.\"\n</code></pre>\n\n<h3>Use <code>echo</code> when it's good enough</h3>\n\n<p>Instead of <code>printf '\\n%s:\\n' \"$f\"</code> I would write:</p>\n\n<pre><code>echo\necho \"$f:\"\n</code></pre>\n\n<h3>Here-documents</h3>\n\n<p><code>EOH</code> is an unusual symbol for the here-document marker.\nThat's not a problem, but I think the less surprising elements in a script,\nthe better.\nI don't see a good reason to not call this <code>EOF</code> as usual.</p>\n\n<h3>Your questions</h3>\n\n<blockquote>\n <p>Some possible areas for improvement:</p>\n \n <ul>\n <li>Can the jq query be improved?</li>\n <li>Are there other entries in the json output of shfmt that I can look for variable assignments.</li>\n </ul>\n</blockquote>\n\n<p>Unfortunately I'm not able to answer these. \nYou might want to wait for another reviewer who can!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T18:14:39.943", "Id": "437600", "Score": "0", "body": "Thank you. I implemented some of your suggestions, while others prompted a different change. I've included details in my question." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T06:49:33.920", "Id": "225322", "ParentId": "225305", "Score": "2" } } ]
{ "AcceptedAnswerId": "225322", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T22:42:08.483", "Id": "225305", "Score": "6", "Tags": [ "bash" ], "Title": "Small app to show variables declared in a bash script" }
225305
<pre><code>import math def generate_primes(limit): """Generates and prints a list of primes up to a given limit""" prime_list = [2, 3] num = 5 increment_2 = True # When True increment by 2. When False increment by 4 while num &lt;= limit: is_prime = True sqr_lim = math.sqrt(num) for x in prime_list: # Loop through list of prime numbers and check divisibility if x &gt; sqr_lim: break if num % x == 0: is_prime = False break if is_prime: # Add primes to list to only check prime numbers prime_list.append(num) # Alternate step size between 2 and 4 to skip multiples of 2 and 3 if increment_2: num += 2 increment_2 = False else: num += 4 increment_2 = True print(prime_list) return prime_list def main(): generate_primes(200) if __name__ == "__main__": main() </code></pre> <p>I'm writing a program to generate a list of prime numbers to a given limit through the use of trial division. I was wondering if there is a way to further optimize this code. Currently it: skips multiples of 2 and 3; stores primes in a list and the list is used to check for primality; and checks divisibility up until the square root of the number it's analyzing.</p> <p>I would also appreciate it if someone could critique me on my coding style such as comments, white space, and organization because I know its pretty rough around the edges. Thanks for the help.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T03:27:09.203", "Id": "437455", "Score": "0", "body": "I’ve rolled back your most recent edit. You cannot update the question to include feedback given in the answers, below, as that invalidates the answers. See [what can I do when someone answers](https://codereview.stackexchange.com/help/someone-answers), especially the “what should I **not** do” section." } ]
[ { "body": "<p>The function <code>generate_primes()</code> shouldn’t print the list it generated. The caller should print the returned value, if desired. </p>\n\n<hr>\n\n<p>Calling <code>generate_primes(2)</code> will unexpectedly return <code>[2, 3]</code>, as will <code>generate_primes(1)</code> or <code>generate_primes(-500)</code>.</p>\n\n<hr>\n\n<p>The <code>increment_2</code> flag is awkward. When <code>True</code>, increment by 2 seems ok, but when <code>False</code> the increment is ... what? 0? 1? </p>\n\n<p>Instead of an <code>increment_2</code> flag, you could use an <code>increment</code> amount, starting with 2 ...</p>\n\n<pre><code>increment = 2\n</code></pre>\n\n<p>... and then toggle that value between 2 &amp; 4:</p>\n\n<pre><code>num += increment\n\n# Alternate step size between 2 and 4\nincrement = 6 - increment\n</code></pre>\n\n<p>No more <code>if ... else ...</code>, reducing the complexity of the function slightly. </p>\n\n<hr>\n\n<p>Stretch goal:</p>\n\n<p>After <code>generate_primes(200)</code>, if a call is made to <code>generate_primes(500)</code>, you will recalculate all of the primes beneath 200. Perhaps there is a way to cache the computed values for future generate calls?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T03:33:18.623", "Id": "437456", "Score": "0", "body": "Caching the primes and computed values should be simple enough, but I'm mostly looking for other ways to optimize the code. Either the square root function or increments would be a good place to start in my opinion. However, trial division has its limits and I would be glad if you or someone else could point me another direction to approach this problem in." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T03:36:44.517", "Id": "437457", "Score": "1", "body": "The [sieve of Eratosthenes](https://codereview.stackexchange.com/questions/tagged/sieve-of-eratosthenes) is a good next step in prime number generation." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T01:44:44.417", "Id": "225314", "ParentId": "225310", "Score": "1" } }, { "body": "<p>You could use the <a href=\"https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops\" rel=\"nofollow noreferrer\"><code>else</code> feature of loops</a>, which gets executed iff no <code>break</code> statement was executed. This gets rid of your flag variable:</p>\n\n<pre><code>while num &lt;= limit:\n sqr_lim = math.sqrt(num)\n for x in prime_list:\n # Loop through list of prime numbers and check divisibility\n if x &gt; sqr_lim:\n break\n if num % x == 0:\n break\n else:\n # Add primes to list to only check prime numbers\n prime_list.append(num)\n</code></pre>\n\n<p>However, this would mean that the condition that breaks the loop because you have reached the square limit would avoid this from being triggered.</p>\n\n<p>To avoid this, you could have a look at the <a href=\"https://docs.python.org/3/library/itertools.html\" rel=\"nofollow noreferrer\"><code>itertools</code></a> module, which provides the <a href=\"https://docs.python.org/3/library/itertools.html#itertools.takewhile\" rel=\"nofollow noreferrer\"><code>takewhile</code> function</a>:</p>\n\n<pre><code>for p in takewhile(lambda p: p &lt;= sqr_lim, prime_list):\n if num % p == 0:\n break\nelse:\n prime_list.append(num)\n</code></pre>\n\n<p>Your variable increment also boils down to the observation that all prime numbers larger than 3 are of the form <code>6k + 1</code> or <code>6k + 5</code> with <code>k = 0, 1, ...</code>. This is for the same reason you used the variable increment, all numbers of the form <code>6k + 0, 2, 4</code> are divisible by two and all numbers of the form <code>6k + 3</code> by three.</p>\n\n<p>You could use this with the <a href=\"https://docs.python.org/3/library/itertools.html#recipes\" rel=\"nofollow noreferrer\"><code>itertools</code> recipe <code>roundrobin</code></a> to generate all candidate numbers.</p>\n\n<blockquote>\n<pre><code>from itertools import cycle, islice\n\ndef roundrobin(*iterables):\n \"roundrobin('ABC', 'D', 'EF') --&gt; A D E B F C\"\n # Recipe credited to George Sakkis\n num_active = len(iterables)\n nexts = cycle(iter(it).__next__ for it in iterables)\n while num_active:\n try:\n for next in nexts:\n yield next()\n except StopIteration:\n # Remove the iterator we just exhausted from the cycle.\n num_active -= 1\n nexts = cycle(islice(nexts, num_active))\n</code></pre>\n</blockquote>\n\n<pre><code>candidates = roundrobin(range(7, limit, 6), # 6k + 1, k = 1, 2, ...\n range(5, limit, 6)) # 6k + 5, k = 0, 1, ...\nfor num in candidates:\n ... \n</code></pre>\n\n<p>However, if you want to get all primes up to some large(ish) number, sieves are really hard to beat. The easiest one to implement is the <a href=\"https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow noreferrer\">Sieve of Eratosthenes</a>, which can for example be done like this:</p>\n\n<pre><code>def prime_sieve(limit):\n prime = [True] * limit\n prime[0] = prime[1] = False\n\n for i, is_prime in enumerate(prime):\n if is_prime:\n yield i\n for n in range(i * i, limit, i):\n prime[n] = False\n</code></pre>\n\n<p>If you need even more speed, you could take a look at the <a href=\"https://en.wikipedia.org/wiki/Sieve_of_Atkin\" rel=\"nofollow noreferrer\">Sieve of Atkin</a>. However, using the above implementation of the Sieve of Eratosthenes, I can generate all primes up to 100.000.000 in less than 30 seconds, which is usually fast enough.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T05:37:30.307", "Id": "437736", "Score": "0", "body": "Just a typo: \"executed iff no break \", ``` iff -> if```. Too few characters for me to propose an edit (min 6)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T07:23:47.987", "Id": "437745", "Score": "0", "body": "@Abdur-RahmaanJanhangeer That's no typo! [It is mathematical shorthand for \"if, and only if\"](https://en.m.wikipedia.org/wiki/If_and_only_if). Here I thought it was not important enough that I write it out, but the `else` can only not be executed if there was a `break` and no other way (except for an exception halting the whole program)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T07:25:32.453", "Id": "437746", "Score": "1", "body": "ok thanks for info! ^^_" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T14:58:16.140", "Id": "225358", "ParentId": "225310", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-31T23:54:22.693", "Id": "225310", "Score": "3", "Tags": [ "python", "beginner", "python-3.x", "primes" ], "Title": "Trial Division Prime Generator" }
225310
<p>I am just getting in to following design patterns.</p> <p>I have create a class that allows for performing a couple operations on different remote storage systems: drive, dropbox, .etc (I call these <code>drivers</code> although there might be a better name). The main class accepts the driver whether it be one of the previous, and uses common methods to perform actions. All of the drivers conform to an interface.</p> <p>Am I using the adapter pattern correctly? Are there any things I should take in to consideration to improve my code?</p> <pre><code>&lt;?php namespace RestorePoint\Adapters; use RestorePoint\Adapters\RemoteFilesDriver\RemoteFilesDriverInterface; use RestorePoint\Traits\FilesystemTrait; use RestorePoint\Helpers\Benchmark; use RestorePoint\Exception; use Psr\Log\LoggerInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\Exception\InvalidArgumentException; use Cake\Filesystem\File; final class RemoteStorageAdapter { use FilesystemTrait; public $options; private $driver; private $driverClass; private $benchmark; private $log; public function __construct(RemoteFilesDriverInterface $driver, Benchmark $benchmark, LoggerInterface $log, array $options = []) { $this-&gt;benchmark = $benchmark; $this-&gt;driver = $driver; $this-&gt;log = $log; $resolver = new OptionsResolver(); $resolver-&gt;setDefined(array_keys($options)); $this-&gt;configureOptions($resolver); $this-&gt;options = $resolver-&gt;resolve($options); $this-&gt;driverClass = $this-&gt;driver-&gt;handle(); } public function configureOptions(OptionsResolver $resolver) { $resolver-&gt;setDefaults([ 'uploadCheckQuota' =&gt; true, 'cleanup' =&gt; true, 'backupAmountRemote' =&gt; null, 'uploadChunkSize' =&gt; 1024 * 1024 * 5, 'uploadFileSizeLimit' =&gt; -1, ]); $resolver -&gt;setRequired('backupFolderName') -&gt;setAllowedTypes('backupAmountRemote', ['null', 'int']) -&gt;setAllowedTypes('uploadCheckQuota', 'boolean') -&gt;setAllowedTypes('cleanup', 'boolean') -&gt;setAllowedTypes('backupFolderName', 'string') -&gt;setAllowedTypes('uploadChunkSize', 'int'); $resolver-&gt;setNormalizer('backupAmountRemote', function (Options $options, $value) { if ($options['cleanup'] == true &amp;&amp; is_null($value)) { throw new InvalidArgumentException(__CLASS__ . ': When cleanup is true, backupAmountRemote cannot be null.'); } return $value; }); } /** * __call * * @param string $method * @param array $arguments * @throws Exception * @return mixed */ public function __call($method, $arguments) { if (method_exists($this-&gt;driver, $method)) { return call_user_func_array(array($this-&gt;driver, $method), $arguments); } else { throw new Exception("Method {$method} does not exist in {$this-&gt;driverClass}"); } } /** * Get service folder * * @return string */ public function getFolder() { if (($folder = $this-&gt;driver-&gt;folderExists($this-&gt;options['backupFolderName'])) === FALSE) { $folder = $this-&gt;driver-&gt;makeFolder($this-&gt;options['backupFolderName']); } return $folder; } /** * Adds files available locally to the service * This WILL NOT delete old files on the server * * @param string $localDir Full path to local files folder * @return boolean * @throws Exception */ public function sync($localDir) { $folder = $this-&gt;getFolder(); $localFiles = $this-&gt;listFilesByCreated($localDir); $remoteFiles = $this-&gt;driver-&gt;listFilesByCreated($folder); $localFilesCol = array_column($localFiles, 'name'); foreach ($remoteFiles as $key =&gt; $value) { $index = array_search($value['name'], $localFilesCol); if ($index !== false) { unset($localFiles[$index]); } } $ct = count($localFiles); $this-&gt;log-&gt;debug("Sync determined {$ct} files should be added to {$this-&gt;driverClass}."); if ($ct == 0) { return false; } foreach ($localFiles as $file) { $this-&gt;log-&gt;debug($this-&gt;driverClass . ': Attempting to add ' . $file['name'] . '...'); $this-&gt;uploadFile($localDir . $file['name']); } return $ct; } /** * Will remove old backup files on the server according to backupAmt * * The oldest files are the ones furthest in the past that were uploaded to the server. * If you have backupAmt set to 1 and just added a backup to the remote folder from 2015, * while having a backup file from 2019 on the server, the file from 2015 will technically * be the newest file, and thus the one from 2019 will be deleted. * * This is due to APIs marking the time the file was created as the time they were uploaded, * despite that not being the time the file was actually generated. * * Under normal circumstances, if your local and remote systems maintain sync, this point * is not of much concern. Just keep this in mind. * * @return int Files removed * @throws Exception */ public function cleanup() { $folder = $this-&gt;getFolder(); $i = 0; if (is_null($this-&gt;options['backupAmountRemote'])) { $this-&gt;log-&gt;info("{$this-&gt;driverClass}: backupAmountRemote is null. Calling cleanup will have no effect."); return $i; } $files = $this-&gt;driver-&gt;listFilesByCreated($folder); $files = array_slice($files, $this-&gt;options['backupAmountRemote']); $ct = count($files); if ($ct &gt; 0) { $this-&gt;log-&gt;debug("{$this-&gt;driverClass}: Cleanup determined {$ct} files should be removed remotely."); foreach ($files as $file) { $this-&gt;log-&gt;debug($this-&gt;driverClass . ': Attempting to delete ' . $file['name'] . '...'); $this-&gt;driver-&gt;deleteFile($file['id']); $this-&gt;log-&gt;debug($this-&gt;driverClass . ': ' . $file['name'] . ' successfully deleted.'); $i++; } } return $i; } /** * Upload file to service * * @param string $file The file to upload * @return string Name and ext of file uploaded * @throws Exception */ public function uploadFile($file) { ini_set('max_execution_time', -1); $folder = $this-&gt;getFolder(); $file = new File($file); if ($this-&gt;driver-&gt;fileExists($file-&gt;name, $folder)) { throw new Exception("{$this-&gt;driverClass}: {$file-&gt;name} already exists."); } if ($this-&gt;options['uploadCheckQuota']) { $this-&gt;hasSpace($file-&gt;size()); } if ($this-&gt;options['uploadFileSizeLimit'] &gt; 0 &amp;&amp; $file-&gt;size() &gt; $this-&gt;options['uploadFileSizeLimit']) { throw new Exception("{$this-&gt;driverClass}: It is likely the script will take too long to complete. Backup file is too big at {$file-&gt;size()} bytes to be uploaded to the service."); } $this-&gt;benchmark-&gt;mark('uploadStart'); $ret = $this-&gt;driver-&gt;addFile($file, $folder, $this-&gt;options['uploadChunkSize']); $elapsedTime = $this-&gt;benchmark-&gt;elapsedTime('uploadStart'); $this-&gt;log-&gt;debug("{$this-&gt;driverClass}: File {$file-&gt;name} successfully added. Task took {$elapsedTime} seconds."); return $ret; } /** * Checks if a file can be added to service based on its size and the quota available * * @param int $fileSize Bytes * @return void * @throws Exception */ private function hasSpace($fileSize) { $spaceRemaining = $this-&gt;driver-&gt;getSpaceRemaining(); if ($spaceRemaining === -1) { return; // -1 = driver doesn't support this command } if ($spaceRemaining - $fileSize &lt;= 0) { throw new Exception("{$this-&gt;driverClass}: Not enough space for {$fileSize} bytes. Only {$spaceRemaining} bytes available."); } } } </code></pre> <p>So as to avoid posting too much code, here is the interface all of the drivers follow:</p> <pre><code>&lt;?php namespace RestorePoint\Adapters\RemoteFilesDriver; use RestorePoint\Adapters\Service\ServiceInterface; use Cake\Filesystem\File; interface RemoteFilesDriverInterface { public function __construct(ServiceInterface $service); /** * Should return a human name version of the driver * * @return string */ public function handle(); /** * Simply checks if a file exists remotely * * @param string $file * @param string $folder * @return boolean */ public function fileExists($file, $folder); /** * Deletes a remote file * * @param string $file * @throws Exception */ public function deleteFile($file); /** * Check if a folder exists, if so, return ID or path * * @param string $folder * @return mixed The ID or path of the folder */ public function folderExists($folder); /** * Makes folder and returns folder ID or path * * @param string $folder * @return mixed The ID or path of the folder */ public function makeFolder($folder); /** * Gets free space - used space * * @return int * @throws Exception */ public function getSpaceRemaining(); /** * Lists files in order from newest to oldest * Conforms file to an associative array with keys * name, id, created * * Name: somefile.zip * Id: /path/to/file or 123123 * Created: timestamp representation of date created * * @param mixed $folder ID or path of folder * @return array * @throws Exception */ public function listFilesByCreated($folder); /** * Uploads a file to remote service * * @param File $file Instance of Cake\Filesystem\File * @param mixed $folder Path or ID of folder * @param int $chunkSizeBytes * @return string filename * @throws Exception */ public function addFile(File $file, $folder, $chunkSizeBytes); /** * Not yet implemented * * @param mixed $file * @param string $destination */ public function download($file, $destination); } </code></pre> <p>I would also argue, based on my understanding, that the drivers themselves are adapters for the service libraries they implement (Google Client Services, Dropbox API) to get a predefined output. But I am unsure of this.</p> <p>update:</p> <p>example driver: <a href="https://pastebin.com/9QEyHZ8f" rel="nofollow noreferrer">https://pastebin.com/9QEyHZ8f</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T09:56:42.947", "Id": "437653", "Score": "0", "body": "... or is it a strategy pattern??" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T01:33:31.107", "Id": "225312", "Score": "3", "Tags": [ "php", "object-oriented", "design-patterns", "file-system", "network-file-transfer" ], "Title": "Adapter pattern to support multiple file storage systems" }
225312
<p>I wrote a infinite terrain script which works! Saddly everytime the player moves a chunk it lags for a moment. I know my code isn't great but I'm here to learn why and get this working too :D </p> <pre><code>using System.Collections; using System.Collections.Generic; using UnityEngine; public class GEN_InfiniteTerrain : MonoBehaviour { public GameObject targetObject; public GameObject chunkObject; public int chunkSize; public float unitSize; public int renderDistance; Dictionary&lt;Vector2, GameObject&gt; gridOfChunks = new Dictionary&lt;Vector2, GameObject&gt;(); List&lt;Vector2&gt; expectedChunkGridPositions = new List&lt;Vector2&gt;(); public float noiseScale; // Infinite terrain values float absoluteChunkSize; private void Start() { // Calculate absolute chunk size GetAbsoluteChunkSize(); // Generate base world GenerateBase(); } Vector2 lastTargetGridPosition = Vector2.zero; private void LateUpdate() { // Get the targets position in world space Vector3 targetAbsolutePosition = targetObject.transform.position; // Convert the targets world position to grid position (/ 10 * 10 is just rounding to 10) Vector2 targetGridPosition = new Vector2(); targetGridPosition.x = Mathf.RoundToInt(targetAbsolutePosition.x / 10) * 10 / absoluteChunkSize; targetGridPosition.y = Mathf.RoundToInt(targetAbsolutePosition.z / 10) * 10 / absoluteChunkSize; if (targetGridPosition - lastTargetGridPosition != Vector2.zero) { GenerateExpectedChunkAreas(targetGridPosition); UpdateChunkPositions(targetGridPosition); } lastTargetGridPosition = targetGridPosition; } void GenerateBase() { for (int x = -renderDistance / 2; x &lt; renderDistance / 2; x++) { for (int z = -renderDistance / 2; z &lt; renderDistance / 2; z++) { Vector2 gridPosition = new Vector2(x, z); Vector3 worldPosition = new Vector3(x * (unitSize * chunkSize), 0, z * (unitSize * chunkSize)); GameObject chunk = Instantiate(chunkObject, worldPosition, Quaternion.identity); chunk.GetComponent&lt;GEN_Chunk&gt;().gridPosition = gridPosition; gridOfChunks.Add(gridPosition, chunk); } } GenerateExpectedChunkAreas(Vector2.zero); } void GenerateExpectedChunkAreas(Vector2 targetGridPosition) { expectedChunkGridPositions.Clear(); for (int x = -renderDistance / 2; x &lt; renderDistance / 2; x++) { for (int z = -renderDistance / 2; z &lt; renderDistance / 2; z++) { Vector2 gridPosition = new Vector2(x, z) + targetGridPosition; expectedChunkGridPositions.Add(gridPosition); } } } void UpdateChunkPositions(Vector2 targetGridPosition) { List&lt;Vector2&gt; positionsWithoutChunks = new List&lt;Vector2&gt;(); List&lt;Vector2&gt; positionsWithOldChunks = new List&lt;Vector2&gt;(); for (int chunkCount = 0, x = -renderDistance / 2; x &lt; renderDistance / 2; x++) { for (int z = -renderDistance / 2; z &lt; renderDistance / 2; z++) { Vector2 gridPosition = new Vector2(x, z) + targetGridPosition; if(!gridOfChunks.ContainsKey(gridPosition)) { positionsWithoutChunks.Add(gridPosition); } chunkCount++; } } foreach (GameObject chunk in gridOfChunks.Values) { if(!expectedChunkGridPositions.Contains(chunk.GetComponent&lt;GEN_Chunk&gt;().gridPosition)) { positionsWithOldChunks.Add(chunk.GetComponent&lt;GEN_Chunk&gt;().gridPosition); } } for (int i = 0; i &lt; positionsWithOldChunks.Count; i++) { Vector3 worldPosition = new Vector3(positionsWithoutChunks[i].x * absoluteChunkSize, 0, positionsWithoutChunks[i].y * absoluteChunkSize); gridOfChunks[positionsWithOldChunks[i]].transform.position = worldPosition; // Recalculating noise for chunk based on its new position does lag more but even WITHOUT this it still stutters when player moves around. ( plan to learn threading just to calculate noise on seperate threads ) // gridOfChunks[positionsWithOldChunks[i]].GetComponent&lt;GEN_Chunk&gt;().ApplyNoise(); } } void GetAbsoluteChunkSize() { absoluteChunkSize = unitSize * chunkSize; } } </code></pre>
[]
[ { "body": "<p>I can only give you some general tips; I'm afraid Unity is outside my expertise.</p>\n\n<ul>\n<li><p>I would consider redefining what <code>renderDistance</code> means. Currently it seems like a diameter; the rendered terrain consists of renderDistance<sup>2</sup> chunks. What that means in practice is that every time you reference renderDistance, you divide it by 2. What happens if it is odd? It may be easier to treat this value as a radius instead (and just use values that are about twice as large).</p></li>\n<li><p>You have a list of <code>expectedGridChunkPositions</code>, and it's not clear to me why it exists. It may just be that I'm not understanding the work done in the latter third of <code>UpdateChunkPositions</code>. What is troubling is that you have a lookup on this list (<code>expectedChunkGridPositions.Contains</code>). I doubt that your performance problems are coming from this alone... but if it's not possible to remove this List, you might consider changed it to a HashSet.</p></li>\n<li><p>The latter two thirds of <code>UpdateChunkPositions</code> could be combined, in fact. You spend one foreach-loop building up <code>positionsWithOldChunks</code>, just to iterate through it and do work in another for-loop. Why not do the work right away?</p></li>\n<li><p>It's possible that, as you examine the behavior of your game more closely, you will find opportunities for broad optimizations, and you will be able to keep the game running smoothly on a single thread. I recommend<sup>1</sup> that you treat multithreading as a last resort, due to the inherent complexity increase it will cause in your code. You may find <a href=\"https://docs.microsoft.com/en-us/visualstudio/profiling/profiling-feature-tour?view=vs-2019\" rel=\"nofollow noreferrer\">Visual Studio's performance analysis tooling</a> very helpful here, especially its capability to show which functions are consuming the most resources.</p></li>\n<li><p>It's also possible that, as the player crosses a chunk boundary, there's just too much terrain generation work to handle in the next dozen milliseconds, and lag will be unavoidable. In that case, good luck with your multithreading adventure. One thing you'll want to avoid as you explore that space is the use of Systems.Collections.Generic for anything that might be shared across threads. Instead, you'll need to use specialized collections like <code>ConcurrentDictionary</code> and <code>ConcurrentBag</code>, which have very handy functions with built-in locking mechanisms (such as <code>GetOrAdd</code>, and <code>AddOrUpdate</code>).</p></li>\n</ul>\n\n<p><sup>1</sup>On the other hand, I've never programmed a game before. Maybe multithreading is considered a best practice for Unity3d games? If so, then my recommendation isn't worth much.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-07T20:51:12.673", "Id": "225742", "ParentId": "225315", "Score": "1" } }, { "body": "<p>Since I don’t see any function of type <code>IEnumerable</code>, I guess you have not taken advantage of Unity’s <code>StartCoroutine</code> function.</p>\n<p>It starts a new thread that runs parallel to the main thread.\nThe main thread is the one making sure the game renders without lag. So from your description it sound exactly like the solution to the kind of problem you are having.</p>\n<p>I would suggest first looking up the examples for <code>StartCoroutine</code>; it takes a little time to figure out how it works, but after that it’s really easy to implement.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-26T11:17:09.773", "Id": "256465", "ParentId": "225315", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T02:54:53.783", "Id": "225315", "Score": "4", "Tags": [ "c#", "performance", "unity3d" ], "Title": "Optimizing Infinite terrain in Unity" }
225315
<p>I'm trying to create a script that receive command from other script, and based on the command received it will execute a method with a while loop or stop it. I manage to make it works with the code below:</p> <pre><code>import rospy import threading from std_msgs.msg import String class MonitoringInterrupt(Exception): pass def cbCmd(nData): """Call back function when receive command from a topic""" cmd=nData.data print("Received cmd: ", cmd) global is_monitoring global t try: if cmd=='1': is_monitoring = False raise MonitoringInterrupt elif cmd=='0': is_monitoring = True t = threading.Thread(target=do_something) t.start() else: print("Unknown cmd") except MonitoringInterrupt: pass def do_something(): try: while is_monitoring: print(str(rospy.get_time())) rate.sleep() except MonitoringInterrupt: pass def talker(): while not rospy.is_shutdown(): rate.sleep() if __name__ == '__main__': global is_monitoring is_monitoring = False global t rospy.init_node('Testing_command', anonymous=True) rospy.Subscriber('cmd', String, cbCmd) rate = rospy.Rate(20) try: talker() except rospy.ROSInterruptException: pass </code></pre> <p>But it look a little bit messy. And I read in the forum that we shouldn't use exception to interrupt method. So is there any other cleaner way to do this? Some people recommend using <code>thread.Event</code> but I haven't success to implement that with is one. Also, when should I call <code>t.join()</code>? I want to call the method multiple times, and as I understand you can only start a thread once.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T05:32:27.897", "Id": "437735", "Score": "0", "body": "In Python, exceptions are actually used to control program flow and is not an anti-pattern as opposed to some other languages." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-05T01:12:54.937", "Id": "437967", "Score": "0", "body": "So, what about `t.join()`, should I call it somewhere or just leave it?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T03:27:30.510", "Id": "225316", "Score": "2", "Tags": [ "python", "multithreading" ], "Title": "Execute a command repeatedly until a stop message is received" }
225316
<p>I'm getting into Swift iOS development, and decided to create a <a href="https://en.wikipedia.org/wiki/Cookie_Clicker" rel="nofollow noreferrer">Cookie Clicker</a> application as a first attempt. Since I am very new with Swift, I would like feedback and criticism on everything possible, to kick bad habits to the curb early. Any and all feedback is welcome, appreciated and considered! </p> <p><em>Since all of the code that I wrote is contained in the <code>ViewController</code> class, I'm only posting the class. If needed, I can post other classes. A screenshot of the layout of my app will also be available below.</em></p> <p><strong>ViewController.swift</strong></p> <pre><code>//MARK: Import Statements import UIKit class ViewController: UIViewController { //MARK: Properties //Labels @IBOutlet weak var cookiesPerClick: UILabel! @IBOutlet weak var numberOfCookies: UILabel! @IBOutlet weak var mainCookie: UILabel! //Buttons @IBOutlet weak var upgradeButton: UIButton! @IBOutlet weak var cookieButton: UIButton! //Cookie Stuff var cookies: Int = 0 var cookiesAClick: Int = 1 var cookieUpgradeCost: Int = 10 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. formatItems() } //MARK: Actions @IBAction func upgradeClicker(_ sender: UIButton) { if (cookies &gt;= cookieUpgradeCost) { cookiesAClick += 1 cookies -= cookieUpgradeCost cookieUpgradeCost *= 2 upgradeButton.setTitle( "Upgrade Cookie | Cost: \(cookieUpgradeCost) Cookies", for: .normal ) numberOfCookies.text = "\(cookies)" cookiesPerClick.text = "Cookie Per Click: \(cookiesAClick)" } } @IBAction func getCookie(_ sender: UIButton) { cookies += cookiesAClick numberOfCookies.text = "\(cookies)" } //MARK: Local Functions func formatItems() { //Upgrade Button Formatting upgradeButton.layer.borderWidth = 1 upgradeButton.layer.cornerRadius = 5 upgradeButton.layer.borderColor = UIColor.black.cgColor //Get Cookie Button Formatting cookieButton.layer.borderWidth = 1 cookieButton.layer.cornerRadius = 5 cookieButton.layer.borderColor = UIColor.black.cgColor //Number Of Cookies Label Formatting numberOfCookies.layer.borderWidth = 1 numberOfCookies.layer.cornerRadius = 5 numberOfCookies.layer.borderColor = UIColor.black.cgColor //Set main cookie to bold mainCookie.font = UIFont.boldSystemFont(ofSize: 35.0) } } </code></pre> <p><strong>App Layout Screenshot</strong></p> <p><a href="https://i.stack.imgur.com/ShlKw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ShlKw.png" alt="Screenshot of app layout"></a></p>
[]
[ { "body": "<p>Since there isn't much code there are only few things that can be improved and all of them are styling:</p>\n\n<ul>\n<li>when working with outlets, make sure to specify the outlet type in the property name.\nex. <code>cookiesPerClick</code> -> <code>cookiesPerClickLabel</code>\nSame applies for the <code>@IBAction</code>. Common approach is to add <code>buttonTapped</code> at the end <code>getCookieButtonTapped</code>. A bit more android way is <code>onAction</code> but still acceptable</li>\n</ul>\n\n<p>The main reason for adding those suffixes is to make it clear what are you dealing with (button action, property label or whatever)</p>\n\n<ul>\n<li><p>I would rename <code>cookies</code> to <code>cookiesCount</code>. <code>cookies</code> sounds more like list of cookies</p></li>\n<li><p>delete generated comments like <code>// Do any additional setup after loading the view.</code></p></li>\n<li><p>If you are not gonna expose some properties/functions (<code>cookies</code>, <code>cookiesAClick</code>, <code>cookieUpgradeCost</code>, <code>func formatItems()</code>) mark them as <code>private</code></p></li>\n<li><p>In general an \"early return\" strategy is preferred where applicable as opposed to nesting code in if statements. Using guard statements for this use-case is often helpful and can improve the readability of the code</p></li>\n</ul>\n\n<pre><code>@@IBAction func upgradeClicker(_ sender: UIButton) {\n guard cookies &lt; cookieUpgradeCost else { return }\n\n cookiesAClick += 1\n ...\n }\n</code></pre>\n\n<ul>\n<li>You have three different views in <code>formatItems</code> that are styled the same way so it will be easier to maintain (and less code) to just separate the styling. I would add it in extension of <code>UIView</code></li>\n</ul>\n\n<pre><code>extension UIView {\n func addBorder() {\n layer.borderWidth = 1\n layer.cornerRadius = 5\n layer.borderColor = UIColor.black.cgColor\n }\n</code></pre>\n\n<p>and in <code>private func formatItems()</code> you will only have:</p>\n\n<pre><code>private func formatItems() {\n upgradeButton.addBorder()\n cookieButton.addBorder()\n numberOfCookies.addBorder()\n\n //Set main cookie to bold\n mainCookie.font = UIFont.boldSystemFont(ofSize: 35.0)\n}\n\n</code></pre>\n\n<p>Naming conventions are a bit optional since most of the companies have their own (or don't have at all) but you can find some official style guides</p>\n\n<ul>\n<li><a href=\"https://github.com/linkedin/swift-style-guide#311-using-guard-statements\" rel=\"nofollow noreferrer\">LinkedIn's Official Swift Style Guide</a></li>\n<li><a href=\"https://github.com/raywenderlich/swift-style-guide\" rel=\"nofollow noreferrer\">The official Swift style guide for raywenderlich.com</a></li>\n<li>they both start with <a href=\"https://swift.org/documentation/api-design-guidelines/\" rel=\"nofollow noreferrer\">Apple's API Design Guidelines.</a></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-06T12:55:28.887", "Id": "225645", "ParentId": "225318", "Score": "3" } } ]
{ "AcceptedAnswerId": "225645", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T04:59:45.100", "Id": "225318", "Score": "2", "Tags": [ "swift", "ios" ], "Title": "Cookie Clicker Game" }
225318
<p>Here is a program for conversion of an infix expression to a postfix expression using a stack. I would like to know how I could improve my checking for invalid input, make my code more expressive, and also improve the performance if possible. </p> <p>I am using gcc 7.4.0. I can use C++17 if needed. This program compiles with C++11.</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; #include &lt;stack&gt; #include &lt;string&gt; #include &lt;cctype&gt; #include &lt;stdexcept&gt; class digitException : public std::runtime_error { using std::runtime_error::runtime_error; }; class unbalancedParentheses : public std::runtime_error { using std::runtime_error::runtime_error; }; inline bool isOpeningParenthesis(char c) {return c == '(';} inline bool isClosingParenthesis(char c) {return c == ')';} inline bool isOperator(char c) { return (c == '+' || c == '-' || c == '*' || c == '/' || c == '^'); } void checkValidInfix(const std::string&amp; expr) { std::stack&lt;char&gt; parentheses; for(auto curr : expr) { if(isdigit(curr)) throw digitException {"Digits not supported."}; if(isOpeningParenthesis(curr)) parentheses.push(curr); else if(isClosingParenthesis(curr)) { if(parentheses.empty()) throw unbalancedParentheses {"Parentheses unbalanced."}; parentheses.pop(); } } if(!parentheses.empty()) throw unbalancedParentheses {"Parentheses unbalanced."}; } void getInfixExpression(std::istream&amp; is, std::string&amp; expr) { is &gt;&gt; expr; checkValidInfix(expr); } bool isHigherPrecedenceThan(char currSymbol, char onStack) //Returns true if precedence of current symbol is higher than //the symbol on stack. //False otherwise. False if something other than an operand is given. { if(!isOperator(currSymbol) || !isOperator(onStack)) return false; if(currSymbol == '+' &amp;&amp; onStack == '+') return false; if(currSymbol == '+' &amp;&amp; onStack == '-') return false; if(currSymbol == '+' &amp;&amp; onStack == '*') return false; if(currSymbol == '+' &amp;&amp; onStack == '/') return false; if(currSymbol == '+' &amp;&amp; onStack == '^') return false; if(currSymbol == '-' &amp;&amp; onStack == '+') return false; if(currSymbol == '-' &amp;&amp; onStack == '-') return false; if(currSymbol == '-' &amp;&amp; onStack == '*') return false; if(currSymbol == '-' &amp;&amp; onStack == '/') return false; if(currSymbol == '-' &amp;&amp; onStack == '^') return false; if(currSymbol == '*' &amp;&amp; onStack == '+') return true; if(currSymbol == '*' &amp;&amp; onStack == '-') return true; if(currSymbol == '*' &amp;&amp; onStack == '*') return false; if(currSymbol == '*' &amp;&amp; onStack == '/') return false; if(currSymbol == '*' &amp;&amp; onStack == '^') return false; if(currSymbol == '/' &amp;&amp; onStack == '+') return true; if(currSymbol == '/' &amp;&amp; onStack == '-') return true; if(currSymbol == '/' &amp;&amp; onStack == '*') return false; if(currSymbol == '/' &amp;&amp; onStack == '/') return false; if(currSymbol == '/' &amp;&amp; onStack == '^') return false; if(currSymbol == '^' &amp;&amp; onStack == '+') return true; if(currSymbol == '^' &amp;&amp; onStack == '-') return true; if(currSymbol == '^' &amp;&amp; onStack == '*') return true; if(currSymbol == '^' &amp;&amp; onStack == '/') return true; if(currSymbol == '^' &amp;&amp; onStack == '^') return true; } std::string convertToPostfix(const std::string&amp; infix) { std::stack&lt;char&gt; operatorStack; std::string result; auto inputSymbol = infix.begin(); while(inputSymbol != infix.end()) { char currSymbol = *inputSymbol; if(std::isalpha(currSymbol)) result.push_back(currSymbol); else if(isOperator(currSymbol)) { if(operatorStack.empty() || isOpeningParenthesis(operatorStack.top())) operatorStack.push(currSymbol); else if(isHigherPrecedenceThan(currSymbol, operatorStack.top())) operatorStack.push(currSymbol); else { while(!operatorStack.empty() &amp;&amp; !isOpeningParenthesis(operatorStack.top()) &amp;&amp; !isHigherPrecedenceThan(currSymbol, operatorStack.top())) { result.push_back(operatorStack.top()); operatorStack.pop(); } operatorStack.push(currSymbol); } } else if(isOpeningParenthesis(currSymbol)) operatorStack.push(currSymbol); else if(isClosingParenthesis(currSymbol)) { while(!isOpeningParenthesis(operatorStack.top())) { result.push_back(operatorStack.top()); operatorStack.pop(); } operatorStack.pop(); } ++inputSymbol; } while(!operatorStack.empty()) { result.push_back(operatorStack.top()); operatorStack.pop(); } return result; } int main() { try { std::string infixExpr; std::cout &lt;&lt; "Enter Infix Expression: "; getInfixExpression(std::cin, infixExpr); std::cout &lt;&lt; "Postfix Expression: " &lt;&lt; convertToPostfix(infixExpr) &lt;&lt; "\n"; } catch(const unbalancedParentheses&amp; up) { std::cerr &lt;&lt; up.what() &lt;&lt; "\n"; } catch(const digitException&amp; de) { std::cerr &lt;&lt; de.what() &lt;&lt; "\n"; } } </code></pre> <p>Here are some examples :</p> <pre><code>Enter Infix Expression: a-b-c Postfix Expression: ab-c- </code></pre> <pre><code>Enter Infix Expression: a*b+c/g-h^j Postfix Expression: ab*cg/+hj^- </code></pre> <pre><code>Enter Infix Expression: a+b*c+(d*e+f)*g Postfix Expression: abc*+de*f+g*+ </code></pre>
[]
[ { "body": "<p>Here are some things that may help you improve your code.</p>\n\n<h2>Make sure all paths return a value</h2>\n\n<p>The <code>isHigherPrecedenceThan</code> routine returns an explicit value for many different combinations of characters, but if none of those conditions match, the routine falls through and does not return a value. It would better to make sure that a value is always returned, as in the following suggestion.</p>\n\n<h2>Simplify your code</h2>\n\n<p>In the <code>isHigherPrecedenceThan</code> routine, the code only returns <code>true</code> in nine specific cases and false in all other cases. For this reason, we can greatly simplify the code:</p>\n\n<pre><code>bool isHigherPrecedenceThan(char currSymbol, char onStack) {\n return ((currSymbol == '*' || currSymbol == '/' || currSymbol == '^') \n &amp;&amp; (onStack == '+' || onStack == '-')) \n || (currSymbol == '^' \n &amp;&amp; (onStack == '*' || onStack == '/' || onStack == '^'));\n}\n</code></pre>\n\n<h2>Consider the use of objects</h2>\n\n<p>If you had an <code>Operator</code> class, a number of things would be simplified. For example, instead of having the code above as a standalone function, one could implement it as <code>operator&gt;</code> and keep all of operator-specific parts in once place.</p>\n\n<h2>Use return values</h2>\n\n<p>The <code>main</code> routine defines an empty string and the passes it to the <code>convertToPostfix</code> routine to fill in. I'd expect instead that <code>convertToPostfix</code> would return the string. Also, if you have the C++17 <code>std::optional</code> available, I think I'd prefer that to using exceptions.</p>\n\n<h2>Consider better error checking</h2>\n\n<p>The current code accepts <code>;;';'[]^_=!@#$%</code> as a valid infix string. That doesn't seem correct. It may be better to check for only valid characters.</p>\n\n<h2>Consider unary vs. binary functions</h2>\n\n<p>If we write \"-8\" it's clear that \"-\" is being used as a unary function with a single argument \"8\". If we write \"9-8\" the \"-\" is a binary function that has a somewhat different purpose. The current code makes no such distinction and accepts \"-a\" and renders \"a-\" which may be acceptable, but it's unlikely that \"a^\" is currectly translated as \"a^\".</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T11:21:08.877", "Id": "225339", "ParentId": "225323", "Score": "4" } } ]
{ "AcceptedAnswerId": "225339", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T07:12:17.053", "Id": "225323", "Score": "7", "Tags": [ "c++", "performance", "validation", "math-expression-eval" ], "Title": "Infix to postfix conversion in C++" }
225323
<p>I have very typical problem:</p> <p>Given big text file, containing text. The task is to calculate occurence of each word and print this info from most occured to less.</p> <p>Example input:</p> <pre><code>cat cat cat dog dog mouse </code></pre> <p>Correct answer:</p> <pre><code>cat -&gt; 3 dog -&gt; 2 mouse -&gt; 1 </code></pre> <p>First I solved this using <code>Scanner</code>. But this solutions seems to be slow, cause IO was blocking.</p> <p>After some time and cookie spent I wrote this solution:</p> <pre class="lang-java prettyprint-override"><code>final Path path = FileSystems.getDefault().getPath("/tmp/", "file.txt"); Map&lt;String, Long&gt; occ = Files .lines(path) .flatMap(line -&gt; Arrays.stream(line.split(delimRegex))) .filter(line -&gt; line.length() &gt; 0) .map(String::toLowerCase) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); occ .entrySet() .stream() .sorted((e1, e2) -&gt; e2.getValue().compareTo(e1.getValue())) .forEach(e -&gt; System.out.println(e.getKey() + " -&gt; " + e.getValue())); </code></pre> <p>I think solution is good (but not sure). Is there any other optimization techniques I've ignored?</p>
[]
[ { "body": "<p>I have one comment: \n<a href=\"https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#lines-java.nio.file.Path-java.nio.charset.Charset-\" rel=\"nofollow noreferrer\"><code>Files.lines()</code></a> method has the following comment in the JDK documentation:</p>\n\n<blockquote>\n <p>The returned stream encapsulates a Reader. If timely disposal of file\n system resources is required, the try-with-resources construct should\n be used to ensure that the stream's close method is invoked after the\n stream operations are completed.</p>\n</blockquote>\n\n<p>in other words, in order to prevent resource leak, you need to construct the stream in a try-with-resources block </p>\n\n<pre><code>try (Stream&lt;String&gt; linesStream = Files.lines(path)) {\n Map&lt;String, Long&gt; occ = linesStream\n .flatMap(line -&gt; Arrays.stream(line.split(delimRegex)))\n ....\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T11:33:13.080", "Id": "225341", "ParentId": "225324", "Score": "2" } }, { "body": "<p>One other comment about your code: variable names are not perfect:</p>\n\n<pre><code> ...\n Files\n .lines(path)\n .flatMap(line -&gt; Arrays.stream(line.split(delimRegex))) // OK, this is a line\n .filter(line -&gt; line.length() &gt; 0) // But this is a word\n ....\n</code></pre>\n\n<p>Also: consider using <code>String::isEmpty</code> instead of the lambda filter expression.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T03:57:42.000", "Id": "225393", "ParentId": "225324", "Score": "1" } }, { "body": "<p>Some comments about things that you said in the question:</p>\n\n<blockquote>\n <p>\"First I solved this using Scanner. But this solutions seems to be slow, cause IO was blocking.\"</p>\n</blockquote>\n\n<p>If you are reading from a file, I/O will not be blocking. It is possible that Scanner is using a buffer that is too small, but I think that is unlikely. You were probably doing something else wrong.</p>\n\n<blockquote>\n <p>\"I think solution is good (but not sure). Is there any other optimization techniques I've ignored?\"</p>\n</blockquote>\n\n<p>Using streams is not an optimization technique. Accepted wisdom is that using streams is currently <em>a bit</em> slower than an equivalent algorithm implemented using loops. The real advantage of streams is that they are simpler to write and understand than old-fashioned loops, especially when the transformation is complex. For example, you have implemented your problem with just two statements.</p>\n\n<p>Not that I would rewrite your code. It is rarely worthwhile rewriting code to get a small performance boost. Developer time is more precious than computer time.</p>\n\n<blockquote>\n <p>\"After some time and cookie spent I wrote this solution:\"</p>\n</blockquote>\n\n<p>Here's the real problem. Too many cookies are bad for your health. Black coffee with no sugar is a much better aid for programming ... and it is better for your waistline and your teeth :-)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T15:33:20.863", "Id": "225468", "ParentId": "225324", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T07:25:28.683", "Id": "225324", "Score": "2", "Tags": [ "java", "performance", "io" ], "Title": "Reading words and counting their occurence in Java" }
225324
<p>Trying to write fast non dependency IP4 string validator for embedded system, It should counts leading zeros, values over 255 and other corrupted strings. Not sure if I missed something. Сan you guys take a look:</p> <pre><code>// Return 0 on error, store result to segs, if segs != 0. int is_valid_ip4(const char *str, unsigned char* segs) { int dots = 0; // Dot count. int chcnt = 0; // Character count within segment. int accum = 0; // Accumulator for segment. // Catch NULL pointer. if (str == 0) return 0; // Process every character in string. for (;;) { // Check numeric. if (*str &lt; '0' || *str &gt; '9') return 0; // Prevent leading zeros. if (chcnt &gt; 0 &amp;&amp; accum == 0) return 0; // Accumulate and check segment. accum = accum * 10 + *str - '0'; if (accum &gt; 255) return 0; // Store result. if (segs) segs[dots] = (unsigned char)accum; // Advance other segment specific stuff. ++chcnt; ++str; // Finish at the end of the string when 3 points are found. if (*str == '\0' &amp;&amp; dots == 3) return 1; // Segment changeover. if (*str == '.') { // Limit number of segments. ++dots; if (dots == 4) return 0; // Reset segment values. chcnt = 0; accum = 0; ++str; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T09:31:50.217", "Id": "437494", "Score": "10", "body": "C or C++? They are different languages with very different programming idioms and techniques." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T15:47:55.370", "Id": "437568", "Score": "0", "body": "The whole project has written on cpp, however, there are not too much space in MCU Flash/RAM memory, so I can’t use std::strings, std::vectors etc. I agree, for clarity, it is better to remove the cpp tag, thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T15:50:12.547", "Id": "437569", "Score": "0", "body": "Do you need the IP address to stay as a string? I imagine at some point or another you'll be decomposing it into an integer to be able to compute masks, etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T16:00:25.273", "Id": "437573", "Score": "0", "body": "@Alexander as a side effect here is decomposition into octets (`segs` parameter)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T16:02:39.160", "Id": "437575", "Score": "4", "body": "Any reason for not using `inet_pton` and friends?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T16:03:15.323", "Id": "437576", "Score": "1", "body": "@VladimirGamalyan Oh I missed it, that's rather obscure. I would suggest you make an `IPv4Address` struct, or something to that effect, and rename this function to something like `IPv4Address_new()`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T15:18:04.763", "Id": "437685", "Score": "1", "body": "Next time you should post your test suite as well so that we can immediately see which strings are accepted and which are not." } ]
[ { "body": "<h2><code>&lt;stdbool.h&gt;</code></h2>\n\n<p>Unless you need compatibility with C89 for some reason, I would use <code>bool</code> for the return type of the function and <code>true</code> and <code>false</code> as the possible values.</p>\n\n<p>It helps readability.</p>\n\n<hr>\n\n<h2><code>sscanf()</code></h2>\n\n<p>This one depends on your performance needs. A solution using <code>sscanf()</code> will be much easier to understand with a simple look and also shorter in code, but may also be much slower (a benchmark would be appropriate).</p>\n\n<p>Update: I would discard <code>sscanf()</code> because it would accept spaces before the numbers; better use <code>inet_pton()</code> as @vnp suggested.</p>\n\n<hr>\n\n<h2><code>&lt;stdint.h&gt;</code></h2>\n\n<p>Same as with <code>bool</code>: <code>segs</code> seems at first glance to be some string, but after some time I realized it's just an array of 8-bit unsigned integers. You should use <code>uint8_t</code> for that.</p>\n\n<p>In case of <code>&lt;stdint.h&gt;</code> I would say that if you don't have it, you should do the <code>typedef</code>s yourself (enclosed in some <code>#if</code>) anyway. Don't do that with <code>bool</code>, however, which is very dangerous.</p>\n\n<hr>\n\n<h2>Unneeded cast</h2>\n\n<pre><code>unsigned char *p;\nint i;\n\n...\n*p = (unsigned char)i;\n</code></pre>\n\n<p>This cast is not needed.</p>\n\n<p>Usually casts are very dangerous: they can hide bugs that otherwise the compiler would catch easily. Don't ever cast, unless you know a very good reason to.</p>\n\n<hr>\n\n<h2>BUG! (No, I was wrong)</h2>\n\n<pre><code>// Check numeric.\nif (*str &lt; '0' || *str &gt; '9')\n return 0;\n</code></pre>\n\n<p>This line returns 0 at the first dot it finds. The function doesn't work!</p>\n\n<p>This if that comes later is always false due to that:</p>\n\n<pre><code>// Segment changeover.\nif (*str == '.') {\n /// Unreachable code!!!\n}\n</code></pre>\n\n<hr>\n\n<h2><code>&lt;ctype.h&gt;</code></h2>\n\n<p>There are some functions in <code>&lt;ctype.h&gt;</code> that you should use:</p>\n\n<pre><code>// Check numeric.\nif (*str &lt; '0' || *str &gt; '9')\n return 0;\n</code></pre>\n\n<p>That code above can be simplified to this one (and the comment is now even more obvious and therefore removed ;-):</p>\n\n<pre><code>if (!isdigit((unsigned char)*str))\n return 0;\n</code></pre>\n\n<blockquote>\n <p>NOTES: The standards require that the argument <code>c</code> for these functions is either <code>EOF</code> or a value that is representable in the type <code>unsigned char</code>. If the argument <code>c</code> is of type <code>char</code>, it must be cast to <code>unsigned char</code>.</p>\n \n <p>This is necessary because <code>char</code> may be the equivalent of <code>signed char</code>, in which case a byte where the top bit is set would be sign extended when converting to <code>int</code>, yielding a value that is outside the range of <code>unsigned char</code>.</p>\n</blockquote>\n\n<p>See <a href=\"http://man7.org/linux/man-pages/man3/isdigit.3.html\" rel=\"nofollow noreferrer\"><code>man isdigit</code></a>.</p>\n\n<p>If you're going to use these functions, I would create an <code>unsigned char</code> pointer to alias the <code>char *</code> parameter, so that you don't need to cast all the time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T15:55:10.560", "Id": "437572", "Score": "0", "body": "Thank you! I added recommended changes to my project. BTW - it is intentionally to check only digits at the very begin of loop, because valid IP strings cannot begin with a dot, and, when we see the digits, we move string position forward (++str), where we can see the dot (after which there should be digit on the next iteration of the loop)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T16:53:14.347", "Id": "437581", "Score": "0", "body": "@VladimirGamalyan But at some iteration you will want to find a dot,and you won't. Try the function yourself and see." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T18:03:40.197", "Id": "437598", "Score": "0", "body": "I agree with Vladimir: after a digit is found, the string pointer gets advanced; if the *next* character is a dot, the string pointer is advanced again. This seems good to me as it doesn't allow a dot at the start (just as it shouldn't) but catches dots after digits." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T18:48:36.623", "Id": "437608", "Score": "0", "body": "@Guntram @Vladimir Oh, now I see it. The iterations where the pointer would point to the dots are being skipped. I would use `inet_pton()` as @vnp mentioned in a comment, or use `sscanf()`; any of them would be much more readable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T18:50:58.180", "Id": "437609", "Score": "2", "body": "@VladimirGamalyan I would say however, that a forever loop isn't the most readable way to write this. Your intentions are not a forever loop, so you should avoid the form of a forever loop." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T10:49:15.637", "Id": "225337", "ParentId": "225325", "Score": "9" } }, { "body": "<p>I'll flag another issue that wasn't pointed out: it seems that the output array of segs (maybe rename it to segments?) is assumed to be allocated by the caller. Since there is no comment that describes that it needs to be of size 4, then the caller might send a smaller array and then the segs[dots] access would seg fault in the best case and overwrite memory silently in the worst case.\nI would either document that requirement or allocate the memory internally and ask the caller to delete[] it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T21:09:14.203", "Id": "437715", "Score": "1", "body": "`uint8_t segs[static restrict 4]` would be a good way to document this :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T18:22:13.437", "Id": "225428", "ParentId": "225325", "Score": "5" } }, { "body": "<p>The first thing to improve the readability of the code is to define proper data types. Having an <code>unsigned char *</code> is confusing, both to humans and to the compiler.</p>\n\n<pre><code>#include &lt;stdint.h&gt;\n\ntypedef struct {\n uint8_t part[4];\n} ip4_address;\n</code></pre>\n\n<p>Next, I found your code hard to follow because of the forever loop and the many if clauses. You do have a point though because you mention '0' and '9' and '.' only once in the code, which is good.</p>\n\n<p>One thing I don't like is that you write unfinished parsing results to the returned IPv4 address. For example, when parsing <code>123.456</code>, the returned IPv4 address would be <code>123.45.?.?</code>. It's just the unnecessary memory access that I don't like. I prefer code that keeps the intermediate values in local variables and only writes them back when it is completely calculated.</p>\n\n<p>I find it much simpler to read if the code is grouped by things from the application domain, which in this case is numbers and dots. I would write it like this:</p>\n\n<pre><code>#include &lt;stdbool.h&gt;\n#include &lt;stdint.h&gt;\n#include &lt;stdio.h&gt;\n\ntypedef struct {\n uint8_t part[4];\n} ip4_address;\n\nbool is_valid_ip4(const char *str, ip4_address *addr) {\n if (!str) return false;\n\n for (int i = 0; i &lt; 4; i++) {\n\n if (!(*str &gt;= '1' &amp;&amp; *str &lt;= '9')) return false;\n unsigned n = *str++ - '0';\n\n if (*str &gt;= '0' &amp;&amp; *str &lt;= '9') {\n n = 10 * n + *str++ - '0';\n if (*str &gt;= '0' &amp;&amp; *str &lt;= '9') {\n n = 10 * n + *str++ - '0';\n if (n &gt; 255) return false;\n }\n }\n\n addr-&gt;part[i] = n;\n\n if (i == 3) return *str == '\\0';\n if (*str++ != '.') return false;\n }\n\n return false;\n}\n\nint main(int argc, char **argv) {\n ip4_address addr;\n if (1 &lt; argc &amp;&amp; is_valid_ip4(argv[1], &amp;addr)) {\n printf(\"%d.%d.%d.%d\\n\",\n addr.part[0], addr.part[1], addr.part[2], addr.part[3]);\n } else return 1;\n}\n</code></pre>\n\n<p>An IPv4 address, in the usual syntax, consists of 4 numbers. This is expressed by the <code>for</code> loop that contains exactly 4 iterations.</p>\n\n<p>An IPv4 address must start with a number. Therefore the upper part of the <code>for</code> loop is concerned with parsing and validating this number. The lower part handles the dots.</p>\n\n<p>Organizing the code like this produces fewer jumps when stepping through it, and as a result, the execution position is simple to follow. Inside the <code>for</code> loop, it just goes straight from the top to the bottom. In your code, on the other hand, it jumps around much more often, which makes the code hard to follow.</p>\n\n<p>Sure, my code repeats the character constants more often and is therefore more susceptible to typos, but finding these is the job of the test suite.</p>\n\n<p>I took care of only defining the minimum necessary variables since keeping track of changing variable values is difficult.</p>\n\n<p>As in your code, I explicitly test against the digits 0 to 9 instead of calling <code>isdigit</code>, just in case the code runs with an Arabic execution character set that defines some more digits. IPv4 addresses, according to the RFC, are written in ASCII digits.</p>\n\n<p>I didn't write any comments in my code because I think that its structure is so simple and follows common practice that there is nothing surprising to it. By contrast, you wrote many comments, most of which are redundant.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T14:11:25.430", "Id": "437801", "Score": "0", "body": "Thank you! I like this shortened version! If correctly understood, leading zeros are not taken into account here? (like 192.168.1.001)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-04T08:37:15.273", "Id": "437883", "Score": "1", "body": "Oops, that was a mistake on my side. I fixed it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-08T04:16:22.523", "Id": "438454", "Score": "0", "body": "I used your code with slight modification -- reverted first condition to `*str >= '0' && *str <= '9'` and added `if (!n) return false;` after second condition. Otherwise lines with only zero in octets (192.168.0.1) do not pass the test. Thank you!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T20:04:41.120", "Id": "225433", "ParentId": "225325", "Score": "4" } } ]
{ "AcceptedAnswerId": "225337", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T07:35:12.200", "Id": "225325", "Score": "7", "Tags": [ "c", "validation", "embedded", "ip-address" ], "Title": "IP4 strings validator" }
225325
<p>I am learning about survival analysis and I made some implementation in Python using <code>lifelines</code> and <code>plotly</code>. However depending on the number of arguments I would have to almost rewrite my function again because of all these ifs and fors. Could you suggest the way I could make it smarter? Here is my code:</p> <pre><code>def classicLifelineFigure(frames, timeName = None, protocol = None, mutation = None, getter = getDfToSurvivalAnalysis): ''' Function that returns lifeline figure object to be displayed on the website Parameters: frames --&gt; dictionary with frames for features, mutations etc. timeName --&gt; time on which we perform analysis protocol --&gt; name of protocol if present in analysis mutation --&gt; name of mutation if present in analysis getter --&gt; function to get separate dataframes for analysis from one big dataframe ''' kmf = KaplanMeierFitter() fig = go.Figure() if timeName == None: return fig dfToAnalysis = getter(frames, timeName, protocol, mutation) dfToAnalysis['TIME'] = dfToAnalysis['TIME'] / 365 if protocol != None: if mutation != None: for prot in set(dfToAnalysis['PROTOCOL'].values): for mut in set(dfToAnalysis['MUTATION'].values): tempDf = dfToAnalysis[(dfToAnalysis['PROTOCOL'] == prot) &amp; (dfToAnalysis['MUTATION'] == mut)] results = kmf.fit(tempDf['TIME'], tempDf['EVENT']) traceDf = results.survival_function_.copy() fig.add_trace(go.Scatter( x = traceDf.index, y = traceDf.iloc[:,0], mode = 'lines', name = 'Protocol value = {}, mutation value = {}'.format(prot, mut) )) if mutation == None: for prot in set(dfToAnalysis['PROTOCOL'].values): tempDf = dfToAnalysis[dfToAnalysis['PROTOCOL'] == prot] results = kmf.fit(tempDf['TIME'], tempDf['EVENT']) traceDf = results.survival_function_.copy() fig.add_trace(go.Scatter( x = traceDf.index, y = traceDf.iloc[:,0], mode = 'lines', name = 'Protocol value = {}'.format(prot) )) elif mutation != None: for mut in set(dfToAnalysis['MUTATION'].values): tempDf = dfToAnalysis[dfToAnalysis['MUTATION'] == mut] results = kmf.fit(tempDf['TIME'], tempDf['EVENT']) traceDf = results.survival_function_.copy() fig.add_trace(go.Scatter( x = traceDf.index, y = traceDf.iloc[:,0], mode = 'lines', name = 'Mutation value = {}'.format(mut) )) else: results = kmf.fit(dfToAnalysis['TIME'], dfToAnalysis['EVENT']) traceDf = results.survival_function_.copy() fig.add_trace(go.Scatter( x = traceDf.index, y = traceDf.iloc[:,0], mode = 'lines', name = 'Survival function' )) fig.update_layout(showlegend = True) return fig </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T08:49:22.183", "Id": "437491", "Score": "0", "body": "Welcome to Code Review! Here on this site, complete code is preferred in order to see the program in context, i.e. that it's often better to post the code including all imports and maybe a small example on how the function is supposed to be used." } ]
[ { "body": "<p><a href=\"https://www.python.org/dev/peps/pep-0008/#programming-recommendations\" rel=\"nofollow noreferrer\">Comparisons to <code>None</code> should always be done with <code>is</code> or <code>is not</code>.</a> This is because <code>None</code> is a singleton object and this will give you the right behavior even if you override some objects <code>__eq__</code> method or similar. This is mentioned in Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>. It also recommends no spaces around <code>=</code> for keyword arguments and using <code>lower_case</code> for variables and functions.</p>\n\n<p>As to your actual question, what you really want to do is apply some function (fitting and plotting) to either the whole dataset or grouped by one or more categorical values.\nThe latter is what <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html\" rel=\"nofollow noreferrer\"><code>pandas.DataFrame.groupby</code></a> is for.</p>\n\n<pre><code>kmf = KaplanMeierFitter()\n\ndef plot_fit(df, fig, name='Survival function'):\n results = kmf.fit(df['TIME'], df['EVENT'])\n trace_df = results.survival_function_.copy() # Is this copy really needed?\n fig.add_trace(go.Scatter(\n x=trace_df.index,\n y=trace_df.iloc[:,0],\n mode='lines',\n name=name\n ))\n\ndef do_fit(df, by=None):\n fig = go.Figure()\n if by is None:\n plot_fit(df, fig)\n else:\n for group, df2 in df.groupby(by):\n name = ... # Somehow determine label from group\n plot_fit(df2, fig, name)\n fig.update_layout(showlegend=True)\n return fig\n</code></pre>\n\n<p>This function can be called either as <code>do_fit(df)</code>, <code>do_fit(df, \"PROTOCOL\")</code> or <code>do_fit(df, [\"PROTOCOL\", \"MUTATION\"])</code>. The <code>group</code> variable is a tuple telling you which protocol and/or mutation it is, extracting a correct label from this is left as an exercise. I also omitted getting the dataframe with your <code>getter</code> function and other preparations. These should probably be done in the function calling this function.</p>\n\n<p>It could be argued that this should be divided up even further and the fitting should be separated from the plotting.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-06T08:06:36.047", "Id": "438165", "Score": "0", "body": "Wow, that's great way to do that. I figured out to use groupby for that one but this solution is great. Thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T15:21:43.393", "Id": "225360", "ParentId": "225326", "Score": "2" } } ]
{ "AcceptedAnswerId": "225360", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T07:37:22.783", "Id": "225326", "Score": "2", "Tags": [ "python", "pandas" ], "Title": "Optimal way to filter DataFrame by many arguments, without usage of multiple ifs and for loops" }
225326
<p>I tried this problem below and solved it in O(test_cases * string_length * pattern_length) complexity involving three nested loops.I want to know how can i further decrease time. I figured as much:</p> <p>1:I'm comparing few patterns more than once.</p> <p>2:Should find a way to not repeat the comparisons which i am unable to do.</p> <p>The problem is as below:-</p> <p>We are given a string S and a Pattern P. You need to find all matches of hash of P in string S. Also, print the index (0 based) at which the pattern's hash is found. If no match is found, print -1.</p> <p>Note: All the matches should have same length as pattern P.</p> <p>The hash of pattern P is calculated by summing the values of characters as they appear in the alphabets table. For reference, a is 1, b is 2, ...z is 26. Now, using the mentioned values, hash of ab is 1+2=3.</p> <p>Input:</p> <p>The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase contains two lines of input. The first line contains the string S. The second line contains the pattern P.</p> <p>Output:</p> <p>For each testcase, in a new line, print the matches and index separated by a space. All the matches should be printed in their own separate lines.</p> <p>Constraints:</p> <p>1 &lt;= T &lt;= 100</p> <p>1 &lt;= |S|, |P| &lt;= 105</p> <p>Examples:</p> <p>Input:</p> <pre><code>1 bacdaabaa aab </code></pre> <p>Output:</p> <pre><code>aab 4 aba 5 baa 6 </code></pre> <p>Explanation:</p> <p>Testcase1: P is aab, and S is bacdaabaa Now, the hash of P: aab is 1+1+2=4 In the string S, the hash value of 4 is obtained by the following:</p> <pre><code>aab=1+1+2=4, at index 4 aba=1+2+1=4, at index 5 baa=2+1+1=4, at index 6 </code></pre> <p>My code in c++ :-</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;vector&gt; using namespace std; int main() { long ind,j,test,kal; cin&gt;&gt;test; //testcases' input// for(ind=0;ind&lt;test;ind++) { long len1,len2,sum1=0,sum2=0; string s1,s2,s3; //s1 for the input string,s2 for pattern,s3 to print the patterns that we find// cin&gt;&gt;s1&gt;&gt;s2; len1=s1.size(); //length of input string// len2=s2.size(); //length of pattern // for(j=0;j&lt;len2;j++) { sum2=sum2+(int)s2[j]-96; //doing the hash sum of pattern first so that i need not do pattern matching// } for(j=0;j&lt;=len1-len2;j++) //iterate len1-len2 times since we get those many distinct or duplicate patterns// { for(kal=j;kal&lt;j+len2;kal++) //iterate j+len2 times which is size of the pattern each time// { sum1=sum1+(int)s1[kal]-96; //updating the sum obtained// s3.push_back(s1[kal]); //since we also need to print the pattern which has the hash sum// } if(sum1==sum2) //if the sum matches print the string and starting index// cout&lt;&lt;s3&lt;&lt;" "&lt;&lt;j&lt;&lt;endl; s3.erase(); //clear the string for next testcase// sum1=0; //clear the sum for next testcase// } } return 0;} </code></pre> <p>Please suggest changes that reduces the time. Thanks for reading and any help will be a great favor .</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-04T20:18:12.180", "Id": "437949", "Score": "0", "body": "As a side note: this whole thing is solved really fast in unix 'grep' I think: https://stackoverflow.com/questions/12629749/how-does-grep-run-so-fast" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-04T20:24:06.340", "Id": "437950", "Score": "0", "body": "Actually, this explanation is a demo, and it's brilliantly easy to follow: https://www.cs.utexas.edu/users/moore/best-ideas/string-searching/fstrpos-example.html" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-05T05:20:05.687", "Id": "437980", "Score": "1", "body": "@JCx thanks for that man, I'm also learning Linux programming, this is of some help to me." } ]
[ { "body": "<p>So far, your code has some general problems that are much more urgent than performance:</p>\n\n<ol>\n<li><p>You are <code>using namespace std;</code>. This is an extremely bad habit and will ruin your life (\"this is a contest and I write everything in main\" is not an acceptable excuse). See <a href=\"https://stackoverflow.com/q/1452721\">Why is <code>using namespace std;</code> considered bad practice?</a>.</p></li>\n<li><p>The <code>main</code> function is very long and a reader cannot tell at a glance what it does. If you need so many comments, you should consider refactoring your code. (Also, why do your comments end with <code>//</code>?)</p></li>\n<li><p>You are not making enough use of the standard library.</p></li>\n<li><p>There is too little space. And the indentation is inconsistent.</p></li>\n<li><p>The variable names are not helpful. What is <code>sum1</code>? <code>s3</code>?</p></li>\n<li><p><code>j++</code> is being used instead of the correct <code>++j</code>. See <a href=\"https://stackoverflow.com/q/484462\">Difference between pre-increment and post-increment in a loop?</a>.</p></li>\n</ol>\n\n<p>Also, please avoid <code>std::endl</code> when not necessary. Use <code>'\\n'</code> instead. See <a href=\"https://stackoverflow.com/q/213907\">C++: <code>std::endl</code> vs <code>\\n</code></a>.</p>\n\n<p>And <code>str.erase()</code> is much less intuitive than <code>str.clear()</code>. (In fact, I didn't know until today that <code>erase</code> can be invoked this way.)</p>\n\n<p>Here's I would write the same code, at the very least: (30 seconds code, not tested comprehensively)</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;numeric&gt;\n#include &lt;string&gt;\n\nint hash_code(const std::string&amp; pattern)\n{\n // note: c - 'a' + 1 is not portable\n return std::accumulate(pattern.begin(), pattern.end(), 0,\n [](int x, char c){ return x + (c - 'a' + 1); });\n}\n\nvoid search(const std::string&amp; string, const std::string&amp; pattern)\n{\n const int pattern_hash = hash_code(pattern);\n for (std::size_t i = 0; i + pattern.size() &lt;= string.size(); ++i) {\n auto str = string.substr(i, pattern.size());\n if (hash_code(str) == pattern_hash)\n std::cout &lt;&lt; str &lt;&lt; \" \" &lt;&lt; i &lt;&lt; \"\\n\";\n }\n}\n\nint main()\n{\n int n;\n std::cin &gt;&gt; n;\n\n for (int i = 0; i &lt; n; ++i) {\n std::string string, pattern;\n std::cin &gt;&gt; string &gt;&gt; pattern;\n search(string, pattern);\n }\n} \n</code></pre>\n\n<p>(Also, the input style is quite strange, I have to admit, but that seems to be beyond your control.)</p>\n\n<p>Incidentally, I don't think you properly implemented the sentence \"If no match is found, print -1.\"</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T12:18:00.793", "Id": "437516", "Score": "0", "body": "First of all thanks for answering here and responding to my other question on stackoverflow XD.I tried your your code (copy_pasted it prior to examining it) it still gave me timeout(should be less than 0.6 secs).I agree i need to use libraries more and figure out which ones are effective keeping in mind the time constraints.If you wanna try out the question yourself [link]https://practice.geeksforgeeks.org/contest-problem/rolling-hash510436075531/0/ .Thanks again!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T17:08:06.490", "Id": "437582", "Score": "2", "body": "As a standalone statement (like in a for loop) it does not really matter if you use `++i` or `i++`. Saying that pre-increment is the \"correct\" one is a matter of taste." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-04T18:22:13.867", "Id": "437935", "Score": "1", "body": "@danielspaniol yes I know about that but am afraid I might get downvoted even if I remotely sound confronting their opinion lol." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-05T02:35:56.023", "Id": "437970", "Score": "1", "body": "@Ananthhokage No, of course not. There is absolutely no reason to downvote you for that. If you challenge my opinion, I will happily discuss with you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-05T02:48:45.637", "Id": "437971", "Score": "0", "body": "@danielspaniol For some strange reason I didn't noticed your comment, sorry for that. My take is that in theory they are indeed the same in this particular situation, but `++i` does logically what we want to do here, and in general `++i` is faster than `i++`, so sticking to `++i` is probably a good idea. A discarded value `i++` just look as \"wrong\" as `*(&x) + char(1) + 2 + 0[\"\\003\"] - (short)5 + 9` in place of `x + 10` to many of us (well, that's a bit exaggerated), also any decent compiler should generate equivalent code for them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-05T05:56:16.227", "Id": "437984", "Score": "0", "body": "@L.F. Thank you! I just read this thread and now understand your point [link]https://stackoverflow.com/questions/24901/is-there-a-performance-difference-between-i-and-i-in-c" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T10:01:08.933", "Id": "225334", "ParentId": "225327", "Score": "10" } }, { "body": "<p>This code does not implement a rolling hash. For every iteration of the main loop, the hash is reset and then entirely re-calculated from nothing with an inner loop. A rolling hash would remove a character from the hash and then add a new character, doing only a constant amount of work per sub-string.</p>\n\n<p>There are some edge-cases for you to work out, but main element of the technique is this:</p>\n\n<pre><code>hash = hash - s1[kal - len2] + s1[kal]\n</code></pre>\n\n<p>No inner loop. Also no <code>- 96</code> because it is cancelled out.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T12:21:33.403", "Id": "437518", "Score": "0", "body": "Thanks!This is not exactly the rolling hash algorithm , it was just named like that.The code i wrote works the way i wanted , its just that the time needs to reduced." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T12:45:42.010", "Id": "437520", "Score": "0", "body": "@Ananthhokage using a rolling hash should help with the time" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T14:37:09.030", "Id": "437544", "Score": "0", "body": "so i should learn rolling hash algorithm first?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T14:42:30.650", "Id": "437547", "Score": "0", "body": "@Ananthhokage well it's really simple, it comes down to that one line of code that I wrote above.. with suitable initialization of course. In general with a hash function that also involves multiplying the hash by a constant, there may be some trickier math concepts involved (modular multiplicative inverse etc) but the code is still really simple." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T11:25:37.570", "Id": "225340", "ParentId": "225327", "Score": "10" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T07:39:07.530", "Id": "225327", "Score": "5", "Tags": [ "c++", "performance", "strings" ], "Title": "Reducing the time for rolling hash" }
225327
<p>I am trying to learn data structures by taking this Udemy Course, <a href="https://www.udemy.com/introduction-to-data-structures/" rel="nofollow noreferrer">Easy to Advanced Data Structures</a> by William Fiset. The course provided an <a href="https://github.com/williamfiset/data-structures/blob/master/com/williamfiset/datastructures/dynamicarray/DynamicArray.java" rel="nofollow noreferrer">implementation</a> of Dynamic Array in Java. To ensure I fully understood the material, I tried to re-implement it in Python. Have provided the code below. Please let me know if I am doing it right or if there is anything wrong with it. Much thanks for your help!</p> <pre><code>""" A generic dynamic array implementation """ class DynamicArray: def __init__(self, capacity=0): self._index = 0 self.capacity = capacity # actual array size self.arr = [None for _ in range(self.capacity)] self.size = 0 # length user thinks array is def __len__(self): return self.size def isEmpty(self): return self.size == 0 def __getitem__(self, index): return self.arr[index] def __setitem__(self, index, elem): self.arr[index] = elem def clear(self): for i in range(self.size): self.arr[i] = None def add(self, elem): # To resize if self.size + 1 &gt;= self.capacity: if self.capacity == 0: self.capacity = 1 else: self.capacity *= 2 new_arr = DynamicArray(self.capacity) for i in range(self.size): new_arr[i] = self.arr[i] self.arr = new_arr self.arr[self.size] = elem self.size += 1 # Removes an element at the specified index in this array def removeAt(self, rm_index): if rm_index &gt;= self.size or rm_index &lt; 0: raise IndexError data = self.arr[rm_index] new_arr = DynamicArray(self.size - 1) i, j = 0, 0 while i &lt; self.size: #self.size = 3 if i == rm_index: j -= 1 else: new_arr[j] = self.arr[i] i += 1 j += 1 self.arr = new_arr self.size -= 1 return data def remove(self, elem): index = self.indexOf(elem) if index == -1: return False self.removeAt(index) return True def indexOf(self, elem): for i in range(self.size): if elem == self.arr[i]: return i return -1 def __contains__(self, elem): return self.indexOf(elem) != -1 def __iter__(self): return self def __next__(self): if self._index &gt; self.size: raise StopIteration else: data = self.arr[self._index] self._index += 1 return data def __str__(self): if self.size == 0: return "[]" else: ans = "[" for i in range(self.size - 1): ans += str(self.arr[i]) + ", " ans += str(self.arr[self.size - 1]) + "]" return ans </code></pre>
[]
[ { "body": "<p>Your code looks good, but there are four things I would improve:</p>\n\n<h2>Style</h2>\n\n<p>Overall your code follows the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8 Style Guide</a>, but:</p>\n\n<ul>\n<li>Names should use snake_case, so <code>index_of</code> instead of <code>indexOf</code>, etc</li>\n<li>Comments after code should leave 2 white spaces after the code:</li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>self.size = 0 # length user thinks array is &lt;- wrong\nself.size = 0 # length user thinks array is &lt;- correct\n</code></pre>\n\n<p>I don't know if this is just my preference, but I think it's better to group the public methods like <code>is_empty</code>, <code>index_of</code> etc and group the overloads like <code>__getitem__</code>, <code>__setitem__</code></p>\n\n<h2>Clear</h2>\n\n<p>At least for me, what I would expect of a method called <code>clear</code> is that it removes all objects, leaving the array empty. So in my opinion your <code>clear</code> method should just set <code>self.size = 0</code>. You don't need to set the elements to null because they don't matter anymore.</p>\n\n<h2>Is empty?</h2>\n\n<p>In Python, you can check if a list contains any elements by doing:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if my_list:\n</code></pre>\n\n<p>I think users would expect the same behaviour for your class, which you can implement with the <code>__bool__</code> (Python 3.x) or <code>__nonzero__</code> (Python 2.x) methods. Just return <code>not is_empty()</code></p>\n\n<h2>Iterator</h2>\n\n<p>The biggest flaw I see in the code is your implementation of iteration. You are keeping the index in the array object; this means that the user cannot do:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for x in my_array:\n for y in my_array:\n</code></pre>\n\n<p>Because the <code>_index</code> is shared in both loops.</p>\n\n<p>You can solve this by implementing the iterator in a different class. I would declare it as a nested class, starting with an underscore to indicate the user that it should be considered private:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class DynamicArray:\n class _Iterator:\n def __init__(self, dynamic_array):\n # ....\n # Implement '_index' and '__next__' in this class\n\n def __iter__(self):\n # Return a different object every time you are requested an iterator\n return _Iterator(self)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T09:40:21.107", "Id": "225332", "ParentId": "225328", "Score": "4" } }, { "body": "<p>In order to adhere to the interface defined by <code>list</code>, some methods should have different names:</p>\n\n<pre><code>indexOf -&gt; find\nremoveAt -&gt; __delitem__\nisEmpty -&gt; __bool__\nadd -&gt; append\n</code></pre>\n\n<p>Currently you don't have consistent bound checks:</p>\n\n<pre><code>x = DynamicArray(10)\nx[0] = None\nx[0] # returns None as expected\nx[5] # also returns None although was not set\nx[10] # raises IndexError because of the size of the internal array\n</code></pre>\n\n<p>Instead, add a check in <code>__getitem__</code>:</p>\n\n<pre><code>def __getitem__(self, index):\n if not -self.size &lt;= index &lt; self.size:\n raise IndexError(...)\n return self.arr[index]\n</code></pre>\n\n<p>Initially the internal array is a <code>list</code>, but after the first resize it is suddenly another <code>DynamicArray</code>. I would stick to one, probably the <code>list</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T15:50:41.923", "Id": "225362", "ParentId": "225328", "Score": "3" } } ]
{ "AcceptedAnswerId": "225332", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T08:11:06.630", "Id": "225328", "Score": "3", "Tags": [ "python", "array" ], "Title": "Dynamic Array implementation in Python" }
225328
<p>I have a file where I keep some initial values for some form fields base on field type. Some of them are primitive values, like <code>'' or 0 or false</code> but some of them are non-primitive reference values, like <code>[] or {}</code>. For example:</p> <p><strong>INITIAL_VALUES.js</strong></p> <pre><code>const INITIAL_VALUES= { SINGLE_CHOICE: '', MULTIPLE_CHOICE: [], OBJECT: {}, BOOLEAN: false, NUMBER: 0, STRING: '' }; export default INITIAL_VALUES; </code></pre> <p>The fact is that I have to <strong>be careful when using non-primitive initial values, because since they come as reference,</strong> I might change them, and get them a second time with some residual value, instead of being empty.</p> <p>I've tought about some options to deal with this:</p> <hr> <p><strong>OPTION #1</strong></p> <p>Make the <code>INITIAL_VALUES.js</code> export a function that returns the new values object and call that function inside my component.</p> <p>Example:</p> <p><strong>getInitialValues.js</strong></p> <pre><code>function getInitialValues() { return({ SINGLE_CHOICE: '', MULTIPLE_CHOICE: [], OBJECT: {}, // and so on... }); } export default getInitialValues; </code></pre> <p><strong>SomeComponent.js</strong></p> <pre><code>import getInitialValues from './getInitialValues' function SomeComponent() { const INITIAL_VALUES = getInitialValues(); } </code></pre> <hr> <p><strong>OPTION #2</strong></p> <p>Keep the initial values as an object and everytime I use them, I need to check if it's a non-primitive and create a new one (instead of using the same reference from <code>INITIAL_VALUES</code>).</p> <p>Example:</p> <p><strong>SomeComponent.js</strong></p> <pre><code>myVariable = INITIAL_VALUES[fieldType]; if (Array.isArray(myVariable)) { myVariable = [...myVariable]; // CREATE A NEW ARRAY } else if (typeof(myVariable) === 'object') { myVariable = {...myVariable}; // CREATE A NEW OBJECT } </code></pre> <hr> <p><strong>OPTION #3</strong></p> <p>Use only non-primitive values. And set <code>null</code> instead of empty arrays <code>[]</code> and empty objects <code>{}</code>.</p> <p>Example:</p> <p><strong>INITIAL_VALUES.js</strong></p> <pre><code>const INITIAL_VALUES= { SINGLE_CHOICE: '', MULTIPLE_CHOICE: null, OBJECT: null, BOOLEAN: false, NUMBER: 0, STRING: '' }; </code></pre> <p>But doing so, whenever I try to populate those fields, I'll need to check if the object/array exists, and create it if it doesn't.</p> <p>Example</p> <p><strong>SomeComponent.js</strong></p> <pre><code>function pushValueToArrayField(newValue) { setState((prevState) =&gt; { const aux = {...prevState}; if (aux.someArrayField === null) { aux.someArrayField = []; } aux.someArrayField.push(newValue); return aux; }); } </code></pre> <p>What is my best option here?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T10:14:11.803", "Id": "437499", "Score": "2", "body": "\"I have a file\" How big? What does your current code look like, exactly? On Code Review, we don't deal well with hypotheticals. Please take a look at the [help/on-topic] and consider what you really want to ask here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T10:21:25.580", "Id": "437501", "Score": "0", "body": "The `INITIAL_VALUES.js` file is my exact file. And the options are the consequences that I'll have to embrace whatever road I take." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T14:38:04.263", "Id": "437545", "Score": "0", "body": "Why don't you have the default for your textarea component in your textarea-component.js, for your multiple choice component in multiple-choice-component.js, etc?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T14:50:10.350", "Id": "437549", "Score": "0", "body": "@Mohrn because then my initial values would be hard coded across multiple files. And I might want to change them at some point." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T14:50:45.470", "Id": "437550", "Score": "0", "body": "I've ended up choosing OPTION #1 and it's working alright so far!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T18:04:49.047", "Id": "437599", "Score": "1", "body": "Cant you just freeze it? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T18:46:38.850", "Id": "437607", "Score": "0", "body": "@konijn no.. I really need a new instance everytime because I'll modify it." } ]
[ { "body": "<p>So here's what I've ended up doing:</p>\n\n<p><strong>INITIAL_VALUES.js</strong></p>\n\n<pre><code>function GET_FEATURE_TYPES_INITIAL_VALUES() {\n const FEATURE_TYPE_INITIAL_VALUES = {\n SINGLE_CHOICE: '',\n MULTIPLE_CHOICE: [],\n BOOLEAN: false,\n NUMBER: 0,\n STRING: ''\n };\n return FEATURE_TYPE_INITIAL_VALUES;\n}\n\nfunction GET_FILTER_TYPES_INITIAL_VALUES() {\n const FILTER_TYPE_INITIAL_VALUES = {\n NUMBER_RANGE_ALLOW_MULTIPLE: [],\n NUMBER_ACUM_RANGE_ALLOW_SINGLE: [],\n SINGLE_CHOICE_ALLOW_SINGLE: [],\n SINGLE_CHOICE_ALLOW_MULTIPLE: [],\n MULTIPLE_CHOICE_ALLOW_MULTIPLE: [],\n BOOLEAN_ALLOW_MULTIPLE: [],\n STRING_ALLOW_MULTIPLE: []\n };\n return FILTER_TYPE_INITIAL_VALUES;\n}\n\nfunction GET_FIELD_TYPES_INITIAL_VALUES() {\n const FIELD_TYPE_INITIAL_VALUES = {\n STRING_FIELD: '',\n BOOLEAN_FIELD: '',\n NUMBER_FIELD: 0,\n ARRAY_STRINGS_FIELD: [],\n ARRAY_OBJECTS_FIELD: [],\n OBJECT_FIELD: {}\n };\n return FIELD_TYPE_INITIAL_VALUES;\n}\n\nexport {\n GET_FEATURE_TYPES_INITIAL_VALUES,\n GET_FILTER_TYPES_INITIAL_VALUES,\n GET_FIELD_TYPES_INITIAL_VALUES\n};\n\n</code></pre>\n\n<p><strong>SomeComponent.js</strong></p>\n\n<pre><code>import { GET_FEATURE_TYPES_INITIAL_VALUES } from '@constants/INITIAL_VALUES';\n\nfunction SomeComponent() {\n const FEATURE_TYPES_INITIAL_VALUES = GET_FEATURE_TYPES_INITIAL_VALUES();\n\n // FRESH NEW INITIAL_VALUES AVAILABLE ON EVERY RENDER\n}\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T21:17:16.210", "Id": "437622", "Score": "0", "body": "This neither follows best practices for React (defaultProps) nor for Javascript (camel case)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T18:49:37.053", "Id": "225375", "ParentId": "225333", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T09:50:50.797", "Id": "225333", "Score": "1", "Tags": [ "javascript", "comparative-review", "react.js" ], "Title": "Getting initial values of non-primitive types from another Javascript file?" }
225333
<p>`I made this Tic-Tac-Toe game first, by using user input in the console here: <a href="https://pastebin.com/6zLjrWcf" rel="nofollow noreferrer">https://pastebin.com/6zLjrWcf</a> , and now new and improved using Tkinter:</p> <pre><code>import tkinter as tk from tkinter import ttk import time def create_button(relx, rely): button = tk.Button(width=10, height=2, command=lambda: callback(button)) button.place(relx=relx, rely=rely) return button def check_win(): if (buttons[0]['text'] == buttons[1]['text'] == buttons[2]['text'] != '') or \ (buttons[3]['text'] == buttons[4]['text'] == buttons[5]['text'] != '') or \ (buttons[6]['text'] == buttons[7]['text'] == buttons[8]['text'] != '') or \ (buttons[0]['text'] == buttons[3]['text'] == buttons[6]['text'] != '') or \ (buttons[1]['text'] == buttons[4]['text'] == buttons[7]['text'] != '') or \ (buttons[2]['text'] == buttons[5]['text'] == buttons[8]['text'] != '') or \ (buttons[2]['text'] == buttons[4]['text'] == buttons[6]['text'] != '') or \ (buttons[0]['text'] == buttons[4]['text'] == buttons[8]['text'] != ''): return True else: return False def callback(button): global turn, x if x == 1: time.sleep(1) game.quit() invalid['text'] = '' if button['text'] != '': invalid['text'] = 'Invalid space try again' return button['text'] = turn if check_win(): invalid['text'] = 'Player ' + turn + ' WINS!!!!!' x = 1 turn = ('0' if turn == 'X' else 'X') label_button['text'] = 'PLAYER ' + turn + '\'S TURN.' x = 0 turn = 'X' game = tk.Tk() game.title('TicTacToe') game.geometry('700x500') buttons = [] for i in range(1, 10): button_created = create_button(0.25 if i / 3 &lt;= 1 else 0.45 if i / 3 &lt;= 2 else 0.65, 0.2 if i in [1, 4, 7] else 0.4 if i in [2, 5, 8] else 0.6) buttons.append(button_created) label_button = ttk.Button(game, text='PLAYER ' + turn + '\'S TURN.', style='Fun.TButton', width=20, state='disabled') label_button.pack(pady=30) invalid = tk.Label(text='') invalid.place(relx=0.4, rely=0.12) game.mainloop() </code></pre> <p>My main question is if there is a way to compact check_win()? Also please review the rest of the code.</p>
[]
[ { "body": "<p>From : \n<a href=\"https://codereview.stackexchange.com/questions/108738/python-tic-tac-toe-game\">Python Tic Tac Toe Game</a></p>\n\n<pre><code> win_commbinations = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6))\n\nfor a in win_commbinations:\n if board[a[0]] == board[a[1]] == board[a[2]] == \"X\":\n print(\"Player 1 Wins!\\n\")\n print(\"Congratulations!\\n\")\n return True\n\n if board[a[0]] == board[a[1]] == board[a[2]] == \"O\":\n print(\"Player 2 Wins!\\n\")\n print(\"Congratulations!\\n\")\n return True\n for a in range(9):\n if board[a] == \"X\" or board[a] == \"O\":\n count += 1\n if count == 9:\n print(\"The game ends in a Tie\\n\")\n return True\n</code></pre>\n\n<p>This alternative solution is a bit cleaner + includes a \"Tie\" check, which your original solution doesn't check ( just remove if you consider it irrelevant ofc )</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T16:11:52.087", "Id": "437579", "Score": "0", "body": "You have not reviewed the code, but instead presented your own solution. While the code may improve some aspects, it does not have a tkinter GUI like the original code does." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T15:28:20.097", "Id": "225361", "ParentId": "225342", "Score": "-1" } }, { "body": "<p>Let us begin with some layout. This is a typical grid use case so that you won't have to manually manage grid. At the lowest level, a grid structure essentially places buttons by calculating coordinates. But this gets tedious over time, that's why a grid layout is provided. Also, it was a clever way of cheking win by being symbol agnostic. A normal tic tac toe game would have used checkwin(symbol) to determine win.</p>\n\n<h2>On strings</h2>\n\n<p>To escape <code>'</code> within <code>' '</code> you can use <code>\"</code> instead. From</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>'\\'S TURN.'\n</code></pre>\n\n<p>to</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>\"'S TURN.\"\n</code></pre>\n\n<p>and you can also use string formatting to clear up some clutter.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>\"PLAYER {}'S TURN.\".format(turn)\n</code></pre>\n\n<h2>On layout</h2>\n\n<p>Modifying your <code>create_button</code> function to this allows a grid structure</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def create_button(x, y):\n button = tk.Button(width=10, height=2, command=lambda: callback(button))\n button.grid(row=x, column=y)\n return button\n</code></pre>\n\n<p>Then we modify others since different layouts can't be mixed</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>label_button = ttk.Button(\n game, \n text=\"PLAYER {}'S TURN.\".format(turn), \n style='Fun.TButton', width=20, \n state='disabled')\nlabel_button.grid(row=0, column=1)\ninvalid = tk.Label(text='')\ninvalid.grid(row=4, column=1)\n</code></pre>\n\n<p>adding the buttons can be then done as</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>buttons = []\n\nbuttons.append(create_button(1, 0))\nbuttons.append(create_button(1, 1))\nbuttons.append(create_button(1, 2))\nbuttons.append(create_button(2, 0))\nbuttons.append(create_button(2, 1))\nbuttons.append(create_button(2, 2))\nbuttons.append(create_button(3, 0))\nbuttons.append(create_button(3, 1))\nbuttons.append(create_button(3, 2))\n</code></pre>\n\n<p>You can use a loop for the row and <code>itertools.cycle</code> for the <code>0, 1, 2</code> if you want to simplify it.</p>\n\n<h2>The <code>check_win</code> function</h2>\n\n<ul>\n<li>Simplifying if</li>\n</ul>\n\n<p>Adding a <code>()</code> to if statements allows you to write <code>or</code> without <code>\\</code></p>\n\n<pre><code>\nif ... :\n ...\n\nto\n\nif (...):\n ...\n\n</code></pre>\n\n<p>thus the win_function can be simplified from</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if (buttons[0]['text'] == buttons[1]['text'] == buttons[2]['text'] != '') or \\\n(buttons[3]['text'] == buttons[4]['text'] == buttons[5]['text'] != '') or \\\n</code></pre>\n\n<p>to</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def check_win():\n if (\n (buttons[0]['text'] == buttons[1]['text'] == buttons[2]['text'] != '') or\n (buttons[3]['text'] == buttons[4]['text'] == buttons[5]['text'] != '') or\n ...\n ):\n return True\n else:\n return False\n</code></pre>\n\n<ul>\n<li>Simplifying values write-up </li>\n</ul>\n\n<p>This can also be further simplified by defining a function to replace <code>buttons[0]['text']</code></p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def btext(i):\n return buttons[i]['text']\n</code></pre>\n\n<p>and using it</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def check_win():\n if (\n (btext(0) == btext(1) == btext(2) != '') or\n (btext(3) == btext(4) == btext(5) != '') or\n (btext(6) == btext(7) == btext(8) != '') or\n (btext(0) == btext(3) == btext(6) != '') or\n (btext(1) == btext(4) == btext(7) != '') or\n (btext(2) == btext(5) == btext(8) != '') or\n (btext(2) == btext(4) == btext(6) != '') or\n (btext(0) == btext(6) == btext(8) != '')\n ):\n return True\n else:\n return False\n</code></pre>\n\n<h2>On architecture</h2>\n\n<p>A common pattern is the MVC (Model, View, Controller). While checking and updating gui directly works here, you might consider adding states in a structure like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>board = [\n ['', '', ''],\n ['', '', ''],\n ['', '', '']\n]\n</code></pre>\n\n<p>Operations are done on this and the gui is updated according to this.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T05:16:13.490", "Id": "225441", "ParentId": "225342", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T11:48:38.997", "Id": "225342", "Score": "3", "Tags": [ "python", "python-3.x", "tic-tac-toe", "tkinter" ], "Title": "Tic-Tac-Toe code using Python with Tkinter" }
225342
<p>I have an Angular 5 project with a method named <code>createForm</code>. It will basically create just a form. However, the form created changes depends on the flight inventory code. If flight inventory code id TAG_ON I will create a form omitting <code>messagePrefixSMSValidator</code> and also form control named message to empty.</p> <pre><code>createForm() { this.formGroup = this.fb.group( { defaultTemplate: [this.defaultInitialValue], language: [null, Validators.required], message: [ this.messagePrefix ? this.messagePrefix:'', [Validators.required]], longUrl: [''] }, { validator: [ hasUrlTagValidator(TemplatesService.urlTag), messagePrefixSMSValidator(this.messagePrefix? this.messagePrefix: null, 'message') ] } ); if(this.flight.inventory.code === FlightInventoryCode.TAG_ON) { this.formGroup = this.fb.group( { defaultTemplate: [this.defaultInitialValue], language: [null, Validators.required], message: [ '', [Validators.required]], longUrl: [''] }, { validator: [ hasUrlTagValidator(TemplatesService.urlTag), ] } ); } } </code></pre> <p>Is there a way to rewrite my code so that it looks simple?</p>
[]
[ { "body": "<p><a href=\"https://codepen.io/a-morn/pen/dxzbBb?editors=0010#0\" rel=\"nofollow noreferrer\">Suggested changes</a></p>\n\n<ul>\n<li>Formatting. Typically you want to use TSLint, and possible also Prettier. I've ran your code through Prettier with the standard configuration. (Note that the point is <em>consistency</em> and <em>readability</em>. It doesn't matter if you want to use <code>'</code> or <code>\"</code>, tabs or spaces, etc)</li>\n<li><code>this.messagePrefix ? this.messagePrefix : \"\"</code> can be simplified as <code>this.messagePrefix || \"\"</code></li>\n<li>Looking at your code, it looks like we want to assign different values to <code>message</code> and <code>validator</code> depending on the values of <code>this.flight.inventory.code</code>. So lets keep everything else the same rather than having separate code paths. <em>If</em> we were to keep the current structure, then we should at least put the first assignment to <code>this.formGroup</code> in an else block, so we don't assign it twice.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T15:01:28.923", "Id": "437554", "Score": "0", "body": "i didnt understand the last point . could you clarify more ," }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T15:08:22.720", "Id": "437558", "Score": "0", "body": "I think the best way to understand it is to compare the codepen I linked to your original code. Hopefully you can see the gain in readability and terseness. It's much more clear that `message` and `validator` (but nothing else) depends on `this.flight.inventory.code` in the codepen version." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T15:13:44.883", "Id": "437562", "Score": "1", "body": "thank you so much .. i saw it in codepen ...brilliant" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T15:17:35.407", "Id": "437563", "Score": "0", "body": "Great! Feel free to up vote or accept my answer if it helped you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T15:27:28.627", "Id": "437565", "Score": "0", "body": "done . iforgot to voteup .thank u" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T14:33:31.520", "Id": "225357", "ParentId": "225343", "Score": "0" } } ]
{ "AcceptedAnswerId": "225357", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T11:59:29.650", "Id": "225343", "Score": "1", "Tags": [ "typescript", "angular-2+" ], "Title": "Creating a form based on flight intentory" }
225343
<p>I have written a VBA code that copies data from source sheets into destination sheets. The destination sheets are formatted as a table so that formulas can be calculated automatically to update a pivot graph.</p> <p>I need to run the code daily. It works fine but a takes about 2 hours to run, some sheets have about 50,000 rows and about 3000 rows are added daily. My question is, is there a stack exchange site where I can find someone knowledgeable in VBA to review my code to make is run faster/more efficient? I've looked into ways of making VBA more efficient, but I'm not very familiar with it. Maybe I'm missing something.</p> <p>EDIT: The code copies data from four different workbooks (each workbook has one sheet), into four different workbooks (three of the workbooks have one sheet, and one of the workbooks has two sheets). From each source sheet, it copies data starting from cell A9, selecting all cells with data below it and to its right (about 5 columns and 2000 - 6000 rows).</p> <p>I've added the following to my code to make it run a bit faster but the I want to find other ways to make it run much faster:</p> <pre><code>Sub Auto_Open() 'Message box before running script CarryOn = MsgBox("Do you want to update data?", vbYesNo, "Daily Traffic Report") If CarryOn = vbYes Then 'Minimize workbook ActiveWindow.WindowState = xlMinimized 'Switch to manual calculation of formulae Application.Calculation = xlManual ActiveWorkbook.PrecisionAsDisplayed = False Application.ScreenUpdating = False Application.DisplayStatusBar = False Application.EnableEvents = False Dim x, y, o, p, u, j, k, s As Workbook Dim win As Window Dim LastRow As Long Dim oFS As Object Dim StrFile As String Dim rot_cnt As Integer rot_cnt = 1 Dim current As Date Dim newest As Date Dim right_file As String Dim my_path As String Dim file_name As String 'Source Files location my_path = "C:\Users\xxxxx" 'Open latest source files file_name = "filename*.xlsx" StrFile = Dir(my_path &amp; file_name) Do While Len(StrFile) &gt; 0 Set oFS = CreateObject("Scripting.FileSystemObject") If rot_cnt = 1 Then newest = oFS.GetFile(my_path &amp; StrFile).DateCreated End If If rot_cnt &gt;= 1 Then current = oFS.GetFile(my_path &amp; StrFile).DateCreated End If If DateSerial(Year(current), Month(current), Day(current)) &gt;= _ DateSerial(Year(newest), Month(newest), Day(newest)) _ And Right(StrFile, 6) &lt;&gt; "*.xlsm" Then newest = oFS.GetFile(my_path &amp; StrFile).DateCreated right_file = my_path &amp; StrFile End If StrFile = Dir Set oFS = Nothing rot_cnt = rot_cnt + 1 Loop Set x = Workbooks.Open(right_file) file_name1 = "file_name1*.xlsx" StrFile = Dir(my_path &amp; file_name1) Do While Len(StrFile) &gt; 0 Set oFS = CreateObject("Scripting.FileSystemObject") If rot_cnt = 1 Then newest = oFS.GetFile(my_path &amp; StrFile).DateCreated End If If rot_cnt &gt;= 1 Then current = oFS.GetFile(my_path &amp; StrFile).DateCreated End If If DateSerial(Year(current), Month(current), Day(current)) &gt;= _ DateSerial(Year(newest), Month(newest), Day(newest)) _ And Right(StrFile, 6) &lt;&gt; "*.xlsm" Then newest = oFS.GetFile(my_path &amp; StrFile).DateCreated right_file = my_path &amp; StrFile End If StrFile = Dir Set oFS = Nothing rot_cnt = rot_cnt + 1 Loop Set o = Workbooks.Open(right_file) file_name2 = "file_name2*.xlsx" StrFile = Dir(my_path &amp; file_name2) Do While Len(StrFile) &gt; 0 Set oFS = CreateObject("Scripting.FileSystemObject") If rot_cnt = 1 Then newest = oFS.GetFile(my_path &amp; StrFile).DateCreated End If If rot_cnt &gt;= 1 Then current = oFS.GetFile(my_path &amp; StrFile).DateCreated End If If DateSerial(Year(current), Month(current), Day(current)) &gt;= _ DateSerial(Year(newest), Month(newest), Day(newest)) _ And Right(StrFile, 6) &lt;&gt; "*.xlsm" Then newest = oFS.GetFile(my_path &amp; StrFile).DateCreated right_file = my_path &amp; StrFile End If StrFile = Dir Set oFS = Nothing rot_cnt = rot_cnt + 1 Loop Set p = Workbooks.Open(right_file) file_name3 = "file_name3*.xlsx" StrFile = Dir(my_path &amp; file_name3) Do While Len(StrFile) &gt; 0 Set oFS = CreateObject("Scripting.FileSystemObject") If rot_cnt = 1 Then newest = oFS.GetFile(my_path &amp; StrFile).DateCreated End If If rot_cnt &gt;= 1 Then current = oFS.GetFile(my_path &amp; StrFile).DateCreated End If If DateSerial(Year(current), Month(current), Day(current)) &gt;= _ DateSerial(Year(newest), Month(newest), Day(newest)) _ And Right(StrFile, 6) &lt;&gt; "*.xlsm" Then newest = oFS.GetFile(my_path &amp; StrFile).DateCreated right_file = my_path &amp; StrFile End If StrFile = Dir Set oFS = Nothing rot_cnt = rot_cnt + 1 Loop Set j = Workbooks.Open(right_file) 'Open destination files Set y = Workbooks.Open(ThisWorkbook.Path &amp; "\f1.xlsx") Set u = Workbooks.Open(ThisWorkbook.Path &amp; "\f2.xlsx") Set k = Workbooks.Open(ThisWorkbook.Path &amp; "\f3.xlsx") Set s = Workbooks.Open(ThisWorkbook.Path &amp; "\f4.xlsx") 'Wait for 03s Application.Wait (Now + TimeValue("0:00:03")) 'Minimize all excel files For Each win In Windows If win.Visible Then win.WindowState = xlMinimized Next win 'Wait for 03s Application.Wait (Now + TimeValue("0:00:03")) 'Copy data from source files into destination files '2G Voice x.Sheets("Sheet1").Range(x.Sheets("Sheet1").Range("A9"), x.Sheets("Sheet1").Range("A9").End(xlDown).End(xlToRight)).Copy y.Sheets("xxxxx").Range("A" &amp; Rows.Count).End(xlUp).Offset(1, 0).PasteSpecial '2G Data o.Sheets("Sheet1").Range(o.Sheets("Sheet1").Range("A9"), o.Sheets("Sheet1").Range("A9").End(xlDown).End(xlToRight)).Copy y.Sheets("xxxxxx").Range("A" &amp; Rows.Count).End(xlUp).Offset(1, 0).PasteSpecial '3G Voice and Data p.Sheets("Sheet1").Range(p.Sheets("Sheet1").Range("A9"), p.Sheets("Sheet1").Range("A9").End(xlDown).End(xlToRight)).Copy u.Sheets("xxxx").Range("A" &amp; Rows.Count).End(xlUp).Offset(1, 0).PasteSpecial '4G Data j.Sheets("Sheet1").Range(j.Sheets("Sheet1").Range("A9"), j.Sheets("Sheet1").Range("A9").End(xlDown).End(xlToRight)).Copy k.Sheets("xxxxx").Range("A" &amp; Rows.Count).End(xlUp).Offset(1, 0).PasteSpecial 'Total Traffic x.Sheets("Sheet1").Range(x.Sheets("Sheet1").Range("A9"), x.Sheets("Sheet1").Range("A9").End(xlDown).End(xlToRight)).Copy s.Sheets("xxxxxx").Range("A" &amp; Rows.Count).End(xlUp).Offset(1, 0).PasteSpecial 'Disable alerts before closing/saving workbooks Application.DisplayAlerts = False x.Close o.Close p.Close j.Close 'Save destination files y.Save u.Save k.Save s.Save 'Close destination files y.Close u.Close k.Close s.Close 'Refresh and Save current workbook ThisWorkbook.RefreshAll ThisWorkbook.Save 'Disable display alerts Application.DisplayAlerts = True 'Switch to automatic calculation of formulae Application.Calculation = xlAutomatic ActiveWorkbook.PrecisionAsDisplayed = True Application.ScreenUpdating = True Application.DisplayStatusBar = True Application.EnableEvents = True SendMail = MsgBox("Report complete. Send as attachement?", vbYesNo) If SendMail = vbYes Then 'Mail last saved version of report Call Mail_workbook_Outlook Else MsgBox ("Report Complete") End If End If End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T12:20:39.710", "Id": "437517", "Score": "0", "body": "One quick thing I noticed is that you are creating a new `FileSystemObject` at the top of **every single loop**. You only need to create that object once, at the top of your code and then reuse it for the rest of the routine. You'll likely see a performance increase just by doing this alone." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T12:24:15.647", "Id": "437519", "Score": "0", "body": "@PeterT Thanks. I'll give it a try." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T13:17:16.027", "Id": "437531", "Score": "1", "body": "\"into three different 5 differents (workbooks)\" 3 or 5 what? Did you mean 3 workbooks with a total of 5 sheets?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T13:30:30.383", "Id": "437535", "Score": "1", "body": "@Mast It copies data from four different workbooks (each workbook has one sheet), into four different workbooks (three of the workbooks have one sheet, and one of the workbooks has two sheets)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T18:31:04.027", "Id": "437604", "Score": "0", "body": "Thank you for clarifying your question. Welcome to Code Review!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T19:57:31.680", "Id": "437617", "Score": "0", "body": "Is all the data stored in ListObjects (Excel Tables)?" } ]
[ { "body": "<p>A few items as I look through the code:</p>\n\n<p>Use <code>Option Explicit</code>. Always. Every time. Every module. No exception.</p>\n\n<p>When I added <code>Option Explicit</code> (well, OK, I have it set to always add it), your code won't compile because you are using undeclared variables. Without it, VBA \"helpfully\" declares any new variable name you type as a <code>Variant</code>. <code>Variant</code>s have use, but they're slow and 99% of the time you don't need to use a variant, and your code is more readable and will be faster since VBA won't have to figure out what type of data the variable <em>currently</em> contains then convert it to what it <em>thinks</em> you need at this point. </p>\n\n<p>Oh, VBA will also \"helpfully\" create 2 variables for when you use <code>KeePass = \"KeePass\"</code> in one place and <code>If KeepPass &lt;&gt; vbNullString</code> somewhere else, creating very difficult to track down bugs.</p>\n\n<p>You <s>can</s> should have the VBE automatically insert <code>Option Explicit</code> for you in <em>every</em> code module by going to 'Tools | Options' then on the <code>Editor</code> tab check the <code>Require Variable Declaration</code> checkbox. <strong>Highly recommended.</strong></p>\n\n<p><em>Always</em>. <strong>Every time</strong>.</p>\n\n<hr>\n\n<pre><code>Dim oFS As Object\n</code></pre>\n\n<p>Drop the Hungarian Notation. You use it inconsistently, so it's not egregious and overly offensive, but you, along with about 99.9% of other programmers use it inappropriately. <a href=\"https://www.joelonsoftware.com/2005/05/11/making-wrong-code-look-wrong/\" rel=\"nofollow noreferrer\">Read this</a> on why HN, as most people use it, is bad form. There's absolutely nothing wrong with it when used properly.</p>\n\n<p>Additionally, there's no need to late bind <code>oFS</code> by declaring it as <code>Object</code> now, then later</p>\n\n<pre><code>Set oFS = CreateObject(\"Scripting.FileSystemObject\")\n</code></pre>\n\n<p><em>unless</em>, you expect there's the possibility that some machines your code may run on won't have the <code>Scripting</code> DLL installed and you've got error handling around it to catch that situation. Considering that every version of Windows since... Win95? (maybe earlier) has the <code>Scripting</code> DLL installed by default, it's highly unlikely you'll run into this situation.</p>\n\n<p>An additional benefit of declaring it properly (<code>Dim fileSystem as Scripting.FileSystemObject</code>) is that you get Intellisense helping you at coding time, ensuring you're typing function names properly, minimizing typing (thanks auto-complete!), and getting parameter list prompts. <strong>Note:</strong> to early bind this, you'll have to add a reference <code>Tools | References</code> to <code>Microsoft Scripting Runtime</code>, but it's worth the few moments to make the one-time change to your project.</p>\n\n<p>Another specific advantage for your code, as <a href=\"https://codereview.stackexchange.com/questions/225344/exvcel-vba-code-that-copies-data-from-one-sheet-to-another#comment437517_225344\">PeterT mentioned</a> is that you only declare it once and don't have to create and destroy the object 7 times.</p>\n\n<hr>\n\n<pre><code>Do While Len(StrFile) &gt; 0\n</code></pre>\n\n<p>the <code>Dir()</code> function returns <code>\"\"</code> if it doesn't find a matching file name or when it's exhausted the list of matching files. In VBA land, <code>\"\"</code> is the same as <code>vbNullString</code>, so lets use that to avoid the <code>Len()</code> function call to speed up your processing by just a smidge more.</p>\n\n<hr>\n\n<pre><code>Dim x, y, o, p, u, j, k, s As Workbook\n</code></pre>\n\n<p>Gives you 7 <code>variant</code> variables and one <code>Workbook</code> variable (<code>s</code>). These all seem to be assigned the result of a <code>Workbook.Open()</code> statement, so declaring them all as <code>Workbook</code> will a) make that more obvious, and b) eliminate the constant implicit conversion from <code>Variant</code> to <code>Workbook</code>.</p>\n\n<p>While you're at it, give them some sort of meaningful names. Since you didn't pick 8 consecutive letters, they must mean something to you, make it easier on future you and anyone else who may have to look at your code and change those single letters to something helpful. You get 256 characters in a variable name, and with Intellisense helping, you won't ever have to type the whole variable name (once it's been <code>Dim</code>med, that is).</p>\n\n<hr>\n\n<pre><code>'Source Files location\nmy_path = \"C:\\Users\\xxxxx\"\n</code></pre>\n\n<p>As written, that doesn't have a trailing <code>\\</code>, so when you <code>Dir(my_path &amp; file_name)</code>, you'll get <code>\"c:\\users\\xxxxxfilename*.xlsx\"</code> which probably won't be found. This may simply be a copy/pasta/privacy/obsfucation error in your post, so it's probably a minor issue. You may consider writing a small function to ensure a path (passed to the function as a parameter) has a trailing slash, just to be sure.</p>\n\n<hr>\n\n<pre><code>If DateSerial(Year(current), Month(current), Day(current)) &gt;= _\nDateSerial(Year(newest), Month(newest), Day(newest)) _\nAnd Right(StrFile, 6) &lt;&gt; \"*.xlsm\" Then\n newest = oFS.GetFile(my_path &amp; StrFile).DateCreated\n right_file = my_path &amp; StrFile\nEnd If\n</code></pre>\n\n<p>Is rather difficult to read because of that first line continuation. Maybe it's a matter of style and preference, but if you put one complete condition on one line, it's much easier to mentally parse. No, the compiler doesn't care, so make it easier on the person reading it. If the line is too long for your liking, declare a couple of temporary variables to hold your dates. Maybe something like this:</p>\n\n<pre><code>Dim currentYear as Date\ncurrentDate = DateSerial(Year(current), Month(current), Day(current))\nDim newestDate as Date\nnewestDate = DateSerial(Year(newest), Month(newest), Day(newest))\nIf currentDate &gt;= newestDate _\nAnd Right(StrFile, 6) &lt;&gt; \"*.xlsm\" Then\n newest = oFS.GetFile(my_path &amp; StrFile).DateCreated\n right_file = my_path &amp; StrFile\nEnd If\n</code></pre>\n\n<p><strong>However</strong>, even <em>that</em> is way overkill! <code>oFS.GetFile(my_path &amp; StrFile).DateCreated</code> kindly returns a <code>Date</code> which you're storing in either <code>newest</code> or <code>current</code>, so the first part of that <code>If</code> statement can read:</p>\n\n<pre><code>If current &gt;= newest _\nAnd ...\n</code></pre>\n\n<p>and simply be done with it. As you can see, though, it's now even less clear that <code>current</code> and <code>newest</code> are actually file dates, so you may want to consider renaming those to something a bit more meaningful and descriptive.</p>\n\n<p>In that same <code>If</code> statement, there's a second condition</p>\n\n<pre><code>And Right(StrFile, 6) &lt;&gt; \"*.xlsm\" Then\n</code></pre>\n\n<p>If you look back up the code a bit, you'll notice</p>\n\n<pre><code>file_name = \"filename*.xlsx\"\nStrFile = Dir(my_path &amp; file_name)\n</code></pre>\n\n<p>See that <code>*.xlsx\"</code> part of <code>file_name</code>? Yeah, you'll never get a <code>*.xlsm</code> file being returned by <code>Dir()</code> so this bit of the check is totally unnecessary. (NB: if you find that you <em>are</em> getting <code>*.xlsm</code> files when passing that file name mask to <code>Dir()</code> <em>please</em> file a bug report with Microsoft to save the rest of us from hitting this, too!)</p>\n\n<p>While we're there, <code>file_name</code> is a poor choice for a variable name because of the <code>_</code>. VBA uses underscores in events and interfaces and it will create problems when implementing classes. It doesn't appear that this code is in a class, but if/when you do start writing classes, this will create problems for you, so it's probably best to get out of the habit of using them in the first place. </p>\n\n<p>Assuming we meet the conditions of the <code>If</code> statement, we drop into the <code>TRUE</code> clause (for lack of a better term).</p>\n\n<pre><code>newest = oFS.GetFile(my_path &amp; StrFile).DateCreated\n</code></pre>\n\n<p>You're now hitting the OS again to get the <code>.DateCreated</code>, but you've already got it stored in <code>current</code>. It would be much faster to do</p>\n\n<pre><code>newest = current\n</code></pre>\n\n<p>and be done with it.</p>\n\n<p>Then there's </p>\n\n<pre><code>right_file = my_path &amp; StrFile\n</code></pre>\n\n<p>Again, we've got an underscore, but why <code>\"Right\"file</code>? What makes it \"right\"? How 'bout something like <code>mostCurrentSourceFileName</code>. Sure it's longer, but with Intellisense, you'll only have to type it once and there will be no question about <em>why</em> it's the right file!</p>\n\n<pre><code>rot_cnt = rot_cnt + 1\n</code></pre>\n\n<p>OK, you're keeping track of whether you're testing the first file or not, but <code>rot_cnt</code> doesn't really tell me that. How 'bout </p>\n\n<pre><code>Dim firstFile As Boolean\n</code></pre>\n\n<p>and set <code>firstFile = True</code> before you start the loop, then unconditionally set <code>firstFile = False</code> within the loop. Now you know exactly what conditions you're looking for a few lines back where you're evaluating <code>rot_cnt</code>.</p>\n\n<p>Finally, we get to:</p>\n\n<pre><code>Set oFS = Nothing\n</code></pre>\n\n<p>Frankly, since this is <em>within</em> the <code>Do...Loop</code> and you're recreating the object at the top of the loop, I'm not really certain <em>how</em> you're getting the newest file each time. <code>Dir</code> is known for giving you files back in a somewhat random order, but once it's been initialized with <code>Dir(path &amp; filemask)</code> I believe it's pretty much guaranteed to give you every file matching the mask. Since you're killing the instance of the <code>FSO</code> that holds <code>Dir</code>s current pointer there's no telling what you're going to get each time through. That <em>has</em> to come out of the loop.</p>\n\n<p>Put all those changes together and that little bit of code ends up looking something like this:</p>\n\n<pre><code>Const SOURCE_PATH As String = \"c:\\users\\xxxx\\\"\n\nDim firstFile As Boolean\nfirstFile = False\nDim FSO As Scripting.FileSystemObject\nSet FSO = New Scripting.FileSystemObject\nDim fileMask As String\nfileMask = \"Filename*.xlsx\"\n\nDim currentFileName As String\ncurrentFileName = Dir(SOURCE_PATH &amp; currentFileName)\nDo While currentFileName &lt;&gt; vbNullString\n If firstFile Then\n newest = FSO.GetFile(SOURCE_PATH &amp; currentFileName).DateCreated\n current = newest\n firstFile = False\n Dim mostCurrentSourceFileName As String\n mostCurrentSourceFileName = currentFileName\n Else\n current = FSO.GetFile(SOURCE_PATH &amp; currentFileName).DateCreated\n End If\n\n If current &gt; newest Then\n mostCurrentSourceFileName = currentFileName\n newest = current\n End If\n\n currentFileName = Dir\nLoop\nSet x = Workbooks.Open(SOURCE_PATH &amp; mostCurrentSourceFileName)\n</code></pre>\n\n<p><em>Yes, yes, there's an underscore in <code>SOURCE_PATH</code>, but someone, somewhere deemed it appropriate and conventional to shoutcase constant names and separate the words with <code>_</code>, so who am I to buck convention? Besides, as a <code>Const</code>, there won't be any issues with that being confused with an event handler, so that problem goes away.</em></p>\n\n<hr>\n\n<p>Now that you've got that little bit of code cleaned up, you can copy/paste that yourself 8 times and change the variable names so that you aren't overwriting things. Oh, wait. That's a royal PITA, so make a <code>Function</code> out of it and call it 8 times! Something like this</p>\n\n<pre><code>Private Function GetNewestSourceFileFullName(ByVal fileMask As String) As String\n\n Const SOURCE_PATH As String = \"c:\\users\\xxxx\\\"\n\n Dim firstFile As Boolean\n firstFile = False\n Dim FSO As Scripting.FileSystemObject\n Set FSO = New Scripting.FileSystemObject\n\n Dim currentFileName As String\n currentFileName = Dir(SOURCE_PATH &amp; currentFileName)\n Do While currentFileName &lt;&gt; vbNullString\n If firstFile Then\n newest = FSO.GetFile(SOURCE_PATH &amp; currentFileName).DateCreated\n current = newest\n firstFile = False\n Dim mostCurrentSourceFileName As String\n mostCurrentSourceFileName = currentFileName\n Else\n current = FSO.GetFile(SOURCE_PATH &amp; currentFileName).DateCreated\n End If\n\n If current &gt; newest Then\n mostCurrentSourceFileName = currentFileName\n newest = current\n End If\n\n currentFileName = Dir\n Loop\n\n GetNewestSourceFileFullName = SOURCE_PATH &amp; mostCurrentSourceFileName\n\nEnd Function\n</code></pre>\n\n<hr>\n\n<p>Now, it's a simple matter of </p>\n\n<pre><code>Set x = Workbooks.Open(GetNewestSourceFileFullName(\"filename*.xlsx\"))\nSet o = Workbooks.Open(GetNewestSourceFileFullName(\"file_name1*.xlsx\"))\nSet p = Workbooks.Open(GetNewestSourceFileFullName(\"file_name2*.xlsx\"))\n</code></pre>\n\n<p>etc...</p>\n\n<p>Now, if you ever need to change/fix the logic in <code>GetNewestSourceFileFullName</code>, you can do it once and not 8 times. </p>\n\n<p>Oh, wait, I guess you only have to do it 4 times for <code>x</code>, <code>o</code>, <code>p</code>, and <code>j</code>. After reading through nearly 3/4 of the code, I finally discovered that <em>those</em> are the 4 <em>source</em> files. <em>Did I mention that some better naming would help a lot?</em></p>\n\n<hr>\n\n<p>I'm not sure what the <code>Application.Wait()</code>s are for, but if it floats your boat, they only add 6 seconds to the processing time.</p>\n\n<p>Also, I'm not sure why you do the <code>win.WindoState = xlMinimized</code>, but again, if it floats your boat, go for it.</p>\n\n<hr>\n\n<p>Hey, guess what! I just discovered that <code>Workbooks</code> object <code>x</code> is \"2G Voice\" data. I think I have a great new name for <code>x</code> and <code>y</code>:</p>\n\n<pre><code>Dim source2gVoice as Workbook\nDim destination2gVoice as Workbook\n</code></pre>\n\n<p>thanks to making the <code>Function</code>, we only need to change <code>x</code> to <code>source2gVoice</code> in <em>one</em> place - where we assigned the workbook!</p>\n\n<hr>\n\n<p>I'm not a huge fan of the <code>range.copy</code>/<code>range.paste</code> methods of copying cells, but in this case where there are some unknown number of rows to be copied, this may well be the best way to do it.</p>\n\n<p>I'm not certain what you're getting out of specifying <code>.PasteSpecial</code>, but that may be slowing down the copy. The default value for <code>.PasteSpecial</code> (which is what you're getting by <em>not</em> specifying a parameter to the method call) is <code>xlPasteAll</code> which is going to get you values and formatting and everything. If that's what you need, then carry on. If all you want is values then you need to specify <code>xlPasteValues</code>. Rummage through the Intellisense list of available options to make sure you're not pasting anything more than you need.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T17:06:47.147", "Id": "225368", "ParentId": "225344", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T12:02:18.403", "Id": "225344", "Score": "3", "Tags": [ "vba", "excel" ], "Title": "Excel VBA code that copies data from one sheet to another" }
225344
<p>A Fenwick Tree, or a Binary Indexed tree, is an interesting data structure that can efficiently update its elements. You can read more about it in <a href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.14.8917" rel="nofollow noreferrer">this</a> paper.</p> <p><a href="https://gist.github.com/ielyamani/f586600cccb0845a73ae429e26f75120" rel="nofollow noreferrer">Here</a> is a generic implementation of a Fenwick Tree, which could take any two reversible operations:</p> <pre><code>class FenwickTree&lt;T&gt; { private let count : Int private let neutral : T private let forward : (T,T) -&gt; T private let reverse : (T,T) -&gt; T private var data : [T] private var tree : [T] init( count: Int, neutralElement: T, forward: @escaping (T,T) -&gt; T, reverse: @escaping (T,T) -&gt; T ) { self.count = count self.neutral = neutralElement self.forward = forward self.reverse = reverse self.data = Array(repeating: neutralElement, count: count) self.tree = Array(repeating: neutralElement, count: count + 1) } func update(index: Int, with newValue: T) { let oldValue = data[index]; let delta = reverse(newValue, oldValue) data[index] = newValue var treeIndex = index + 1 while treeIndex &lt;= count { tree[treeIndex] = forward(tree[treeIndex], delta) treeIndex += treeIndex &amp; -treeIndex } } func accumulated(at index: Int) -&gt; T { var sum = neutral var treeIndex = index + 1 while 0 &lt; treeIndex { sum = forward(tree[treeIndex], sum) treeIndex -= treeIndex &amp; -treeIndex } return sum } func accumulated(in range: Range&lt;Int&gt;) -&gt; T { let low = range.lowerBound, high = range.upperBound - 1 let cumulatedLow = low == 0 ? neutral : accumulated(at: low - 1) let cumulatedHigh = accumulated(at: high) return low == high ? data[low] : reverse(cumulatedHigh,cumulatedLow) } } </code></pre> <p>Here are some example usecases:</p> <pre><code>let n = 10 let additiveTree = FenwickTree(count: n, neutralElement: 0, forward: +, reverse: -) for i in 0..&lt;n { additiveTree.update(index: i, with: i + 1) } additiveTree.accumulated(at: 5) additiveTree.accumulated(at: 9) additiveTree.accumulated(in: 8..&lt;10) let multiplicativeTree = FenwickTree(count: n, neutralElement: 1, forward: *, reverse: /) for i in 0..&lt;n { multiplicativeTree.update(index: i, with: i + 1) } multiplicativeTree.accumulated(at: 5) multiplicativeTree.accumulated(at: 9) multiplicativeTree.accumulated(in: 8..&lt;10) </code></pre> <p>I am mainly concerned about the naming of functions and variables:</p> <ul> <li><code>neutral</code>: This is the neutral element for <code>forward</code> and <code>reverse</code></li> <li><code>forward</code> and <code>reverse</code> should be transitive verbs since they have side effects. Preferably, the names should have the same number of letters. </li> <li><code>accumulated(at:)</code> is an unusual name, more familiar would be <code>foldLeft</code> from Scala, or <code>foldl</code> from Haskell. </li> <li><code>accumulated(at:)</code> and <code>accumulated(in:)</code> have too similar names.</li> </ul> <p>I can see some possible improvements:</p> <ul> <li>Performance: <code>accumulated(in:)</code> could have better time complexity at the expense of some auxiliary space;</li> <li>Enforcing the reversibility of <code>forward</code> and <code>reverse</code> in code;</li> </ul> <p>Other areas of improvement are welcome.</p>
[]
[ { "body": "<h3>Choosing the generic type (and parameters)</h3>\n\n<p>The Fenwick tree stores cumulative values of its elements, and is based on the ability to compute the sum and difference of those elements. You made a very general implementation, where “sum” and “difference” are provided as closure parameters. But it cannot be ensured that these are proper inverse operations of each other, and a slight variation of your <code>multiplicativeTree</code> example demonstrates the problem:</p>\n\n<pre><code>let multiplicativeTree = FenwickTree(count: 4, neutralElement: 1,\n forward: *, reverse: /)\n\nmultiplicativeTree.update(index: 0, with: 5)\nprint(multiplicativeTree.accumulated(at: 0)) // 5 OK\n\nmultiplicativeTree.update(index: 0, with: 10)\nprint(multiplicativeTree.accumulated(at: 0)) // 10 still OK\n\nmultiplicativeTree.update(index: 0, with: 13)\nprint(multiplicativeTree.accumulated(at: 0)) // 10 what?\n\nmultiplicativeTree.update(index: 0, with: 11)\nprint(multiplicativeTree.accumulated(at: 0)) // 0 what???\n</code></pre>\n\n<p>I would require the elements to conform to the <a href=\"https://developer.apple.com/documentation/swift/additivearithmetic\" rel=\"nofollow noreferrer\"><code>AdditiveArithmetic</code></a> protocol instead. That protocol</p>\n\n<ul>\n<li>requires addition and subtraction, making the <code>forward</code> and <code>reverse</code> parameter obsolete,</li>\n<li>requires a <code>.zero</code> element, making the <code>neutralElement</code> parameter obsolete, and</li>\n<li>provides <em>semantics:</em> according to <a href=\"https://github.com/apple/swift-evolution/blob/master/proposals/0233-additive-arithmetic-protocol.md\" rel=\"nofollow noreferrer\">SE-0223</a>, it <em>“roughly corresponds to the mathematic notion of an <a href=\"https://en.wikipedia.org/wiki/Additive_group\" rel=\"nofollow noreferrer\">additive group</a>.”</em></li>\n</ul>\n\n<p><code>AdditiveArithmetic</code> is adopted by all binary integer and floating point types, that probably covers most use-cases. If you really need a data structure where updating a value is done via multiplication then you can define a custom type which implements <code>AdditiveArithmetic</code> accordingly.</p>\n\n<p>The declaration and initialization then simplifies to</p>\n\n<pre><code>class FenwickTree&lt;T: AdditiveArithmetic&gt; {\n\n private let count : Int\n\n private var data : [T]\n private var tree : [T]\n\n init(count: Int) {\n self.count = count\n self.data = Array(repeating: .zero, count: count)\n self.tree = Array(repeating: .zero, count: count + 1)\n }\n\n // ...\n}\n</code></pre>\n\n<p>and sums/differences can just be computed with <code>+</code> and <code>-</code>, making the code even better readable.</p>\n\n<h3>Accessing the elements</h3>\n\n<p>There is a </p>\n\n<pre><code>func update(index: Int, with newValue: T) {\n</code></pre>\n\n<p>to set new value at an index, but no method to <em>get</em> a single value. I would suggest to implement the <code>subscript</code> method instead, with both a getter and a setter:</p>\n\n<pre><code>subscript(index: Int) -&gt; T {\n get {\n return data[index]\n }\n set {\n // ... update `data` and `tree`\n }\n}\n</code></pre>\n\n<p>And not much more work is needed to make <code>FenwickTree</code> a (mutable, random access) <code>Collection</code>.</p>\n\n<h3>A wider range of ranges ...</h3>\n\n<p>The <code>accumulated(in:)</code> method becomes much more flexible if it takes a <code>RangeExpression</code> parameter instead of a <code>Range</code>:</p>\n\n<pre><code>func accumulated&lt;R&gt;(in range: R) -&gt; T\nwhere R: RangeExpression, R.Bound == Int\n{\n let realRange = range.relative(to: 0..&lt;count)\n let cumulatedLow = accumulated(at: realRange.lowerBound - 1)\n let cumulatedHigh = accumulated(at: realRange.upperBound - 1)\n return cumulatedHigh - cumulatedLow\n}\n</code></pre>\n\n<p>Now you can call it with half-open, closed, or partial ranges:</p>\n\n<pre><code>additiveTree.accumulated(in: 1..&lt;2))\nadditiveTree.accumulated(in: 1...3))\nadditiveTree.accumulated(in: 2...))\nadditiveTree.accumulated(in: ..&lt;4))\nadditiveTree.accumulated(in: ...3))\n</code></pre>\n\n<p>The last line is equivalent to your </p>\n\n<pre><code>additiveTree.accumulated(at: 3))\n</code></pre>\n\n<p>which means that <code>accumulated(at:)</code> is no longer needed as a public method (which solves the problem of the similar names of those methods.)</p>\n\n<h3>Further suggestions</h3>\n\n<p>The index operations</p>\n\n<pre><code> treeIndex += treeIndex &amp; -treeIndex\n treeIndex -= treeIndex &amp; -treeIndex\n</code></pre>\n\n<p>look like magic to the first reader of your code. I would move that to helper methods (which the compiler inlines) and document it.</p>\n\n<p>The <code>tree[0]</code> element is never accessed. With slight modifications of the index calculations you can save one element in that array, i.e. initialize it as</p>\n\n<pre><code> self.tree = Array(repeating: .zero, count: count)\n</code></pre>\n\n<p>For example, the accumulation would be</p>\n\n<pre><code>func accumulated(at index: Int) -&gt; T {\n guard index &gt;= 0 else { return .zero }\n var sum = tree[0]\n var treeIndex = index\n while treeIndex &gt; 0 {\n sum += tree[treeIndex]\n treeIndex -= treeIndex &amp; -treeIndex\n }\n return sum\n}\n</code></pre>\n\n<p>Finally, a single element can be retrieved from the <code>tree</code> array alone, by computing the difference of two tree nodes (this is also described in the Fenwick article). Therefore, at the cost of slightly more computation, you can get rid of the <code>self.data</code> array and save memory.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T21:01:26.380", "Id": "437619", "Score": "0", "body": " Learned a lot from this answer, really liked the second to last suggestion" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T21:02:20.323", "Id": "437620", "Score": "1", "body": "@ielyamani: And I learned what a Fenwick tree is :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T18:59:51.623", "Id": "225377", "ParentId": "225346", "Score": "2" } } ]
{ "AcceptedAnswerId": "225377", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T12:17:22.330", "Id": "225346", "Score": "3", "Tags": [ "tree", "swift" ], "Title": "Generic Fenwick Tree" }
225346
<p>according to the problem:</p> <blockquote> <p>A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers.</p> </blockquote> <p>Here is my code:</p> <pre><code>def largest_palindrome_product(n:int) -&gt; int: ''' Returns largest palindrome whose a product of two n digit(base 10) integer :param n: the number of digits in the numbers we compute the product of :return: largest palindrome whose a product of two n digit(base 10) integer or -1 if non were found ''' # Dealing with edge cases if n == 1: return 9 elif n &lt; 1: raise ValueError("Expecting n to be &gt;= 1") mul_max = -1 upper_boundary = (10**n) - 1 lower_boundary = 10**(n-1) # Searching for the largest palindrome between the upper boundary and the lower one. for i in range(upper_boundary, lower_boundary, -1): for j in range(i, lower_boundary, -1): str_prod = str(i*j) if i*j &gt; mul_max and str_prod[::-1] == str_prod: mul_max = i*j return mul_max </code></pre> <p>Here is a small test case for this code:</p> <pre><code>from ProjectEuler.problem4 import largest_palindrome_product if __name__ == "__main__": # largest prime product is of 91*99 -&gt; returns 9009 print(largest_palindrome_product(2)) # Checking edge cases -&gt; returns 9 print(largest_palindrome_product(1)) # largest prime product is of 993*913 -&gt; returns 906609 print(largest_palindrome_product(3)) </code></pre> <p>Let me know your thoughts on this solution :)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T14:57:45.427", "Id": "437553", "Score": "4", "body": "I've rolled back your edit. You cannot incorporate information from any answers (below) into your question, as this invalidates the answers. See [what should I do when someone answers my question](https://codereview.stackexchange.com/help/someone-answers), especially the \"what should I **_not_** do\" section." } ]
[ { "body": "<h2>Errors</h2>\n\n<p><code>range(start, end)</code> goes from the <code>start</code> value, inclusive, to the <code>end</code> value, exclusive. So</p>\n\n<pre><code>for i in range(upper_boundary, lower_boundary, -1):\n</code></pre>\n\n<p>will not include <code>lower_boundary</code> in the values which will be tested, so you will be ignoring products where <code>i</code> would be <code>10</code> (two digit case) and <code>100</code> (three digit case).</p>\n\n<p>Similarly, <code>for j in range(i, lower_boundary, -1)</code> will ignore products where <code>j</code> would be <code>10</code> and <code>100</code>.</p>\n\n<p>The solution is to use <code>range(..., lower_boundary - 1, -1)</code>.</p>\n\n<h2>Special Case</h2>\n\n<p>Why is <code>n == 1</code> special cased, to return <code>9</code>? Why don’t you trust the algorithm to return the correct value? Oh, right, <code>9*1</code> wouldn’t be tested, because <code>lower_boundary = 1</code>, and got excluded due to the bug above.</p>\n\n<p>Perhaps you should have examined this special case closer.</p>\n\n<h2>Optimizations</h2>\n\n<p>You compute <code>i*j</code> up to 3 times each loop. You should compute it once, and store it in a variable, such as <code>prod</code>.</p>\n\n<pre><code> prod = i * j\n str_prod = str(prod)\n if prod &gt; mul_max and str_prod[::-1] == str_prod:\n mul_max = prod\n</code></pre>\n\n<p>You are searching in decreasing ranges for the outer and inner loops. Why? True: You’ll find the target value faster. But you still search all product values where <code>j &lt;= i</code>. Is there any way of determining there won’t be any larger <code>mul_max</code> value, either from the inner loop, or from the outer loop, or both? For instance, if <code>i*j &gt; mul_max</code> is not true, would it be true for any <strong>smaller</strong> value of <code>j</code>?</p>\n\n<p>Turning a integer into a string is an <span class=\"math-container\">\\$O(\\log n)\\$</span> operation. Can you skip doing it for every product?</p>\n\n<pre><code> for j in range(i, lower_boundary - 1, -1):\n prod = i * j\n\n if prod &lt;= mul_max:\n break\n\n str_prod = str(prod)\n if str_prod[::-1] == str_prod:\n mul_max = prod \n</code></pre>\n\n<p>Can something similar be done with the <code>for i in range(...)</code> loop, to speed things up even further?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T13:56:29.877", "Id": "225353", "ParentId": "225348", "Score": "5" } } ]
{ "AcceptedAnswerId": "225353", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T12:22:07.907", "Id": "225348", "Score": "3", "Tags": [ "python", "beginner", "python-3.x", "programming-challenge", "palindrome" ], "Title": "Project Euler - Problem No.4 - Largest palindrome product" }
225348
<p>I'm currently working on a PSR-15 middleware for authenticating GitHub webhooks.</p> <pre class="lang-php prettyprint-override"><code>&lt;?php class Auth implements MiddlewareInterface, LoggerAwareInterface { const LOG_MSG_MISSING_HEADER = 'Authentication failed, X-Hub-Signature missing'; const LOG_MSG_SIGNATURE_NOT_MATCHING = 'Authentication failed, signature did not match'; const LOG_MSG_SUCCESS = 'Authentication successful'; use LoggerAwareTrait; private const SIGNATURE_NAME = 'X-Hub-Signature'; private $responseFactory; private $secret; public function __construct(string $secret, ResponseFactoryInterface $responseFactory) { $this-&gt;responseFactory = $responseFactory; $this-&gt;secret = $secret; $this-&gt;logger = new NullLogger(); } public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { if (!$request-&gt;hasHeader(self::SIGNATURE_NAME)) { $this-&gt;logger-&gt;warning(self::LOG_MSG_MISSING_HEADER); return $this-&gt;responseFactory-&gt;createResponse(400, 'Bad Request'); } $signature = $this-&gt;getSignature($this-&gt;secret, $request-&gt;getBody()); if (!hash_equals($request-&gt;getHeader(self::SIGNATURE_NAME)[0], $signature)) { $this-&gt;logger-&gt;warning(self::LOG_MSG_SIGNATURE_NOT_MATCHING); return $this-&gt;responseFactory-&gt;createResponse(401, 'Unauthorized'); } $this-&gt;logger-&gt;info(self::LOG_MSG_SUCCESS); return $handler-&gt;handle($request); } private function getSignature(string $secret, string $body): string { return 'sha1=' . hash_hmac('sha1', $body, $secret); } } </code></pre> <p><em>I have removed comments and the use statements for the sake of brevity. The complete code lives in this <a href="https://github.com/anfly0/PSR-15-github-auth/tree/d72653220b1e89e2b2b802de0dc2f3d28ea9d5e5" rel="nofollow noreferrer">repo</a>.</em></p> <p>At the moment, I'm trying to figure out the best way to handle the case if the stream representing the request body is not seekable.</p> <p>The problem this introduces is that when the handler is called, it might not be possible to rewind the stream. This will, of course, makes it impossible for any subsequent handlers/middlewares to access the body content. </p> <p>As I see it, there are two options:</p> <ol> <li><p>Check if the stream is seekable and throw an exception if it's not.</p> <p><em>This solution is simple and would not introduce any real complexity. On the other hand, it shifts responsibility to the calling code, and that might not be the cleanest way of handling the issue.</em></p></li> <li><p>Change the constructor signature to require a PSR-17 StreamFactory and use that to create a new seekable stream and copy the content from the original non-seekable stream to the new one.</p></li> </ol> <p>Any feedback on this or any other part of the code is most welcome!</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T13:23:41.830", "Id": "225351", "Score": "2", "Tags": [ "php", "authentication", "stream", "git" ], "Title": "Middleware for authenticating GitHub webhooks" }
225351
<p>I would like to make a function that checks if something is valid, but if it can't then I want to return an error message that will probably be used to to throw an exception.</p> <pre class="lang-php prettyprint-override"><code>public function isTodayWithinDateRange(\DateTime $start, \DateTime $end) { $now = new \DateTime(); if($now &gt;= $start &amp;&amp; $now &lt;= $end) return true; if($now &lt; $start) return 'Today is before the start date'; if($now &gt; $end) return 'Today is later than the end date'; } </code></pre> <p>And would probably use within a foreach as a validation check such as...</p> <pre class="lang-php prettyprint-override"><code>if(isTodayWithinDateRange($myStart, $myEnd) !== true) { throw new Exception(isTodayWithinDateRange($myStart, $myEnd)); } </code></pre> <p>Is this a good way to go about it? I thought about putting the exception within the function, but this doesn't seem right as all that function should be doing is doing a check and the thing calling it should decide if an error is exceptional or not.</p> <p>I also thought about returning an array such as...</p> <pre class="lang-php prettyprint-override"><code> return array( 'success' =&gt; false, 'error' =&gt; 'Today is later than the end date' ); </code></pre> <p>But I would expect isTodayWithinDateRange to return <code>true</code> if the answer is 'yes'.</p>
[]
[ { "body": "<p>Simply , the method <strong>isTodayWithinDateRange</strong> can throw the exception in this case since the responsability of the method is to check the constraint . \nSo , i think that you can try it as : </p>\n\n<pre><code>function isTodayWithinDateRange(\\DateTime $start, \\DateTime $end) {\n $now = new \\DateTime();\n if($now &lt; $start) throw new Excception('Today is before the start date') ;\n if($now &gt; $end) throw new Exception('Today is later than the end date'); \n return true;\n\n}\n</code></pre>\n\n<p>First , start with case where you are looking to throw exception , in this case , it's not clearly , but think about a case where you have a lot of logic , here you should start with cases where you don't need to manipulate your logic (like if the argument is null , or missing ...) . </p>\n\n<p>Call you method as : </p>\n\n<pre><code>$myStart = new Datetime('01-06-2012');\n$myEnd = new Datetime('01-06-2020');\n\n// loop \n\ntry{\n\nif(isTodayWithinDateRange($myStart, $myEnd)) {\n echo 'contraint validated';\n\n}\n}catch(Exception $e){\n\n echo $e-&gt;getMessage();\n}\n//end loop\n</code></pre>\n\n<p>I hope this help you . </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T17:24:50.157", "Id": "437586", "Score": "2", "body": "This is what I would have answered, but `isTodayWithinDateRange()` does not need to return `true` nor does it need to be inside a `if (...)` because it will only return when today is in the date range. I would also change the name to `validateTodayIsWithinDateRange()`, or something similar." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T17:42:03.760", "Id": "437592", "Score": "0", "body": "Returning _true_ vs throwing an error is a pattern I've seen before in frameworks in other languages. Not sure whether this goes against php guidelines though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T17:45:08.493", "Id": "437593", "Score": "0", "body": "@dfhwze It is common pratice to let a function return something. That's regarded better than not returning anything. So, I have no real problem with returning true here, but the code here almost seems to suggest the function could return false, which it cannot." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T17:47:48.477", "Id": "437594", "Score": "0", "body": "@KIKOSoftware Java uses this pattern in _add_ methods in collections: http://fuseyism.com/classpath/doc/java/util/AbstractQueue-source.html. Just to show that the pattern is not that uncommon." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T17:50:42.823", "Id": "437595", "Score": "0", "body": "@dfhwze But do you ever see something like `if (s.add(\"Welcome\")) { ... }` in Java? What if an `else` block is added to that `if (...)`? It won't ever work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T19:35:19.767", "Id": "437611", "Score": "0", "body": "@KIKOSoftware You are correct. It all depends on a good specification of the method to know how to call it." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T17:15:53.737", "Id": "225370", "ParentId": "225352", "Score": "1" } } ]
{ "AcceptedAnswerId": "225370", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T13:51:41.290", "Id": "225352", "Score": "2", "Tags": [ "php", "error-handling" ], "Title": "PHP function to check if something valid or return error message" }
225352
<p>I own a parking lot that can hold up to 'n' cars at any given point in time. Each slot is given a number starting at 1 increasing with increasing distance from the entry point in steps of one. I want to create an automated ticketing system that allows my customers to use my parking lot without human intervention.</p> <p>When a car enters my parking lot, I want to have a ticket issued to the driver. The ticket issuing process includes us documenting the registration number (number plate) and the colour of the car and allocating an available parking slot to the car before actually handing over a ticket to the driver (we assume that our customers are nice enough to always park in the slots allocated to them). The customer should be allocated a parking slot which is nearest to the entry. At the exit the customer returns the ticket which then marks the slot they were using as being available.</p> <p>Due to government regulation, the system should provide me with the ability to find out:</p> <p>● Registration numbers of all cars of a particular colour.</p> <p>● Slot number in which a car with a given registration number is parked.</p> <p>● Slot numbers of all slots where a car of a particular colour is parked.</p> <pre><code>import heapq from collections import defaultdict, OrderedDict class Car: def __init__(self, registration_number, color): self.registration_number = registration_number self.color = color def __str__(self): return "Car [registration_number=" + self.registration_number + ", color=" + self.color + "]" class ParkingLot: def __init__(self, total_slots): self.registration_slot_mapping = dict() self.color_registration_mapping = defaultdict(list) # we need to maintain the orders of cars while showing 'status' self.slot_car_mapping = OrderedDict() # initialize all slots as free self.available_parking_lots = [] # Using min heap as this will always give minimun slot number in O(1) time for i in range(1, total_slots + 1): heapq.heappush(self.available_parking_lots, i) def status(self): for slot, car in self.slot_car_mapping.items(): print("Slot no: {} {}".format(slot, car)) def get_nearest_slot(self): return heapq.heappop(self.available_parking_lots) if self.available_parking_lots else None def free_slot(self, slot_to_be_freed): found = None for registration_no, slot in self.registration_slot_mapping.items(): if slot == slot_to_be_freed: found = registration_no # Cleanup from all cache if found: del self.registration_slot_mapping[found] car_to_leave = self.slot_car_mapping[slot_to_be_freed] self.color_registration_mapping[car_to_leave.color].remove(found) del self.slot_car_mapping[slot_to_be_freed] print("leave ", slot_to_be_freed) else: print("slot is not in use") def park_car(self, car): slot_no = self.get_nearest_slot() if slot_no is None: print("Sorry, parking lot is full") return self.slot_car_mapping[slot_no] = car self.registration_slot_mapping[car.registration_number] = slot_no self.color_registration_mapping[car.color].append(car.registration_number) # ● Registration numbers of all cars of a particular colour. def get_registration_nos_by_color(self, color): return self.color_registration_mapping[color] # ● Slot numbers of all slots where a car of a particular colour is parked. def get_slot_numbers_by_color(self, color): return [self.registration_slot_mapping[reg_no] for reg_no in self.color_registration_mapping[color]] if __name__ == "__main__": parking_lot = ParkingLot(6) print(parking_lot.available_parking_lots) car = Car("KA-01-HH-1234", "White") parking_lot.park_car(car) car = Car("KA-01-HH-9999", "White") parking_lot.park_car(car) car = Car("KA-01-BB-0001", "Black") parking_lot.park_car(car) car = Car("KA-01-HH-7777", "Red") parking_lot.park_car(car) car = Car("KA-01-HH-2701", "Blue") parking_lot.park_car(car) car = Car("KA-01-HH-3141", "Black") parking_lot.park_car(car) # When no slots are available then slot_no = parking_lot.get_nearest_slot() print(slot_no) slot_no = parking_lot.get_nearest_slot() print(slot_no) # Leave slot no 4 slot_no_to_be_freed = 4 parking_lot.free_slot(slot_no_to_be_freed) heapq.heappush(parking_lot.available_parking_lots, 4) car = Car("KA-01-P-333", "White") parking_lot.park_car(car) car = Car("DL-12-AA-9999", "White") parking_lot.park_car(car) parking_lot.status() print(parking_lot.available_parking_lots) print(parking_lot.registration_slot_mapping) print(parking_lot.color_registration_mapping) registration_numbers = parking_lot.get_registration_nos_by_color('White') print("White : {}".format(registration_numbers)) registration_numbers = parking_lot.get_registration_nos_by_color('Red') print("Red : {}".format(registration_numbers)) registration_numbers = parking_lot.get_registration_nos_by_color('Black') print("Black : {}".format(registration_numbers)) slot_nos = parking_lot.get_slot_numbers_by_color('White') print("White : {}".format(slot_nos)) slot_nos = parking_lot.get_slot_numbers_by_color('Red') print("Red : {}".format(slot_nos)) slot_nos = parking_lot.get_slot_numbers_by_color('Black') print("Black : {}".format(slot_nos)) parking_lot.status() parking_lot.free_slot(1) parking_lot.free_slot(2) parking_lot.free_slot(3) parking_lot.status() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T17:55:35.483", "Id": "437597", "Score": "3", "body": "I quite like this. It is straightforward and meets the requirements. One particularly nice thing about your code is how you index your data at the point of insertion (e.g. mapping registration numbers and colours). Too many designs nowadays use the brute force approach whereby they bunch all the data together then rely on expensive queries to get to the information; in your design, the information is readily available, and it does not even cost much more to store it in this way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T05:23:52.370", "Id": "437734", "Score": "1", "body": "I find changing ```parking_lot.park_car(car)``` to ```parking_lot.park(car)``` to be nice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T06:35:10.363", "Id": "532529", "Score": "0", "body": "The code is **incorrect** because if someone just keeps on calling the method `get_nearest_slot` without actually parking any car, you will run out of ALL the slots without any car being parked..." } ]
[ { "body": "<p>This seems horribly overcomplex, and you don't provide a reason why.</p>\n\n<p>A data structure that associates an increasing integer value (starting at 1) with an object of some type would be a <code>list</code> (an <code>array</code> in other languages). Normally they start at zero, but you can fix that pretty quickly by stuffing a dummy value in the <code>l[0]</code> slot.</p>\n\n<p>Making that change would touch just about every part of your <code>ParkingLot</code> class, so I'll ignore the rest of it.</p>\n\n<p>Given how simple the <code>Car</code> class is, I suggest you replace it with a <a href=\"https://docs.python.org/3/library/collections.html?highlight=namedtuple#collections.namedtuple\" rel=\"nofollow noreferrer\"><code>collections.namedtuple</code></a> instead.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T04:23:29.403", "Id": "437635", "Score": "0", "body": "Actually this was requirement from some client. and they wanted parking slots to be human readable like staring from 1. If I start from 0 then I have make changes at all retrieval levels." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T17:58:12.373", "Id": "225374", "ParentId": "225354", "Score": "3" } }, { "body": "<p>I have divided this program into multiple files as per below:</p>\n\n<pre><code>|____ __init__.py\n|____ parking_lot.py\n|____ test.py\n|____ process_input.py\n|____ commands.txt\n</code></pre>\n\n<p>parking_lot.py is my main module.</p>\n\n<pre><code>#parking_lot.py\nimport heapq\nfrom collections import defaultdict, OrderedDict\n\n\nclass Car:\n def __init__(self, registration_number, color):\n self.registration_number = registration_number\n self.color = color\n\n def __str__(self):\n return \"Car [registration_number=\" + self.registration_number + \", color=\" + self.color + \"]\"\n\n\nclass ParkingLot:\n def __init__(self):\n self.registration_slot_mapping = dict()\n self.color_registration_mapping = defaultdict(list)\n # we need to maintain the orders of cars while showing 'status'\n self.slot_car_mapping = OrderedDict()\n # initialize all slots as free\n self.available_parking_lots = []\n\n def create_parking_lot(self, total_slots):\n # Using min heap as this will always give minimum slot number in O(1) time\n print(\"Created a parking lot with {} slots\".format(total_slots))\n for i in range(1, total_slots + 1):\n heapq.heappush(self.available_parking_lots, i)\n return True\n\n def status(self):\n print(\"Slot No. Registration No Colour\")\n for slot, car in self.slot_car_mapping.items():\n print(\"{} {} {}\".format(slot, car.registration_number, car.color))\n return True\n\n def get_nearest_slot(self):\n return heapq.heappop(self.available_parking_lots) if self.available_parking_lots else None\n\n def leave(self, slot_to_be_freed):\n found = None\n for registration_no, slot in self.registration_slot_mapping.items():\n if slot == slot_to_be_freed:\n found = registration_no\n\n # Cleanup from all cache\n if found:\n heapq.heappush(self.available_parking_lots, slot_to_be_freed)\n del self.registration_slot_mapping[found]\n car_to_leave = self.slot_car_mapping[slot_to_be_freed]\n self.color_registration_mapping[car_to_leave.color].remove(found)\n del self.slot_car_mapping[slot_to_be_freed]\n print(\"Slot number {} is free\".format(slot_to_be_freed))\n return True\n\n else:\n print(\"slot is not in use\")\n return False\n\n def park(self, car):\n slot_no = self.get_nearest_slot()\n if slot_no is None:\n print(\"Sorry, parking lot is full\")\n return\n print(\"Allocated slot number: {}\".format(slot_no))\n self.slot_car_mapping[slot_no] = car\n self.registration_slot_mapping[car.registration_number] = slot_no\n self.color_registration_mapping[car.color].append(car.registration_number)\n return slot_no\n\n # Registration numbers of all cars of a particular colour\n def registration_numbers_for_cars_with_colour(self, color):\n registration_numbers = self.color_registration_mapping[color]\n print(\", \".join(registration_numbers))\n return self.color_registration_mapping[color]\n\n # Slot numbers of all slots where a car of a particular colour is parked\n def slot_numbers_for_cars_with_colour(self, color):\n registration_numbers = self.color_registration_mapping[color]\n slots = [self.registration_slot_mapping[reg_no] for reg_no in registration_numbers]\n print(\", \".join(map(str, slots)))\n return slots\n\n def slot_number_for_registration_number(self, registration_number):\n slot_number = None\n if registration_number in self.registration_slot_mapping:\n slot_number = self.registration_slot_mapping[registration_number]\n print(slot_number)\n return slot_number\n else:\n print(\"Not found\")\n return slot_number\n</code></pre>\n\n<p>this test.py covers different test scenarios.</p>\n\n<pre><code>from parking_lot import ParkingLot, Car\n\nparking_lot = ParkingLot()\n\ncars = [\n Car('KA-01-HH-1234', 'White'),\n Car('KA-01-HH-9999', 'White'),\n Car('KA-01-BB-0001', 'Black'),\n Car('KA-01-HH-7777', 'Red'),\n Car('KA-01-HH-2701', 'Blue'),\n Car('KA-01-HH-3141', 'Black'),\n]\n\nassert parking_lot.create_parking_lot(6) is True\n\nfor i in range(0, len(cars)):\n assert parking_lot.park(cars[i]) == i + 1\n\nassert parking_lot.leave(4) is True\nassert parking_lot.status() is True\n\nassert len(parking_lot.available_parking_lots) == 1\nassert parking_lot.park(Car('KA-01-P-333', 'White')) == 4\n\nassert parking_lot.registration_numbers_for_cars_with_colour('White') == ['KA-01-HH-1234', 'KA-01-HH-9999',\n 'KA-01-P-333']\nassert parking_lot.slot_numbers_for_cars_with_colour('White') == [1, 2, 4]\nassert parking_lot.slot_number_for_registration_number('KA-01-HH-3141') == 6\nassert parking_lot.slot_number_for_registration_number('MH-04-AY-1111') is None\n</code></pre>\n\n<p>How to run test cases:</p>\n\n<pre><code>python3.6 test.py\n</code></pre>\n\n<p>I also have added interactive command line utils where user can either pass a file as input or individual commands.</p>\n\n<pre><code>#process_input.py\n#!/usr/bin/env python\nimport fileinput\nimport sys\n\nfrom parking_lot import ParkingLot, Car\n\nparking_lot = ParkingLot()\n\n\ndef process(command_params):\n command_with_params = command_params.strip().split(' ')\n # print(command_with_params)\n command = command_with_params[0]\n\n if command == 'create_parking_lot':\n assert len(command_with_params) == 2, \"create_parking_lot needs no of slots as well\"\n assert command_with_params[1].isdigit() is True, \"param should be 'integer type'\"\n parking_lot.create_parking_lot(int(command_with_params[1]))\n\n elif command == 'park':\n assert len(command_with_params) == 3, \"park needs registration number and color as well\"\n car = Car(command_with_params[1], command_with_params[2])\n parking_lot.park(car)\n\n elif command == 'leave':\n assert len(command_with_params) == 2, \"leave needs slot number as well\"\n assert command_with_params[1].isdigit() is True, \"slot number should be 'integer type'\"\n\n parking_lot.leave(int(command_with_params[1]))\n elif command == 'status':\n parking_lot.status()\n\n elif command == 'registration_numbers_for_cars_with_colour':\n assert len(command_with_params) == 2, \"registration_numbers_for_cars_with_colour needs color as well\"\n parking_lot.registration_numbers_for_cars_with_colour(command_with_params[1])\n\n elif command == 'slot_numbers_for_cars_with_colour':\n assert len(command_with_params) == 2, \"slot_numbers_for_cars_with_colour needs color as well\"\n parking_lot.slot_numbers_for_cars_with_colour(command_with_params[1])\n\n elif command == 'slot_number_for_registration_number':\n assert len(command_with_params) == 2, \"slot_number_for_registration_number needs registration_number as well\"\n parking_lot.slot_number_for_registration_number(command_with_params[1])\n\n elif command == 'exit':\n exit(0)\n else:\n raise Exception(\"Wrong command\")\n\n\nif len(sys.argv) == 1:\n while True:\n line = input()\n process(line)\n\nelse:\n for line in fileinput.input():\n process(line)\n</code></pre>\n\n<p>this commands.txt:</p>\n\n<pre><code>create_parking_lot 6\npark KA-01-HH-1234 White\npark KA-01-HH-9999 White\npark KA-01-BB-0001 Black\npark KA-01-HH-7777 Red\npark KA-01-HH-2701 Blue\npark KA-01-HH-3141 Black\nleave 4\nstatus\npark KA-01-P-333 White\npark DL-12-AA-9999 White\nregistration_numbers_for_cars_with_colour White\nslot_numbers_for_cars_with_colour White\nslot_number_for_registration_number KA-01-HH-3141\nslot_number_for_registration_number MH-04-AY-1111\n</code></pre>\n\n<p>how to run through commands.txt as input file:</p>\n\n<pre><code>python3.6 process_input.py commands.txt\n</code></pre>\n\n<p>output:</p>\n\n<pre><code>Created a parking lot with 6 slots\nAllocated slot number: 1\nAllocated slot number: 2\nAllocated slot number: 3\nAllocated slot number: 4\nAllocated slot number: 5\nAllocated slot number: 6\nSlot number 4 is free\nSlot No. Registration No Colour\n1 KA-01-HH-1234 White\n2 KA-01-HH-9999 White\n3 KA-01-BB-0001 Black\n5 KA-01-HH-2701 Blue\n6 KA-01-HH-3141 Black\nAllocated slot number: 4\nSorry, parking lot is full\nKA-01-HH-1234, KA-01-HH-9999, KA-01-P-333\n1, 2, 4\n6\nNot found\n</code></pre>\n\n<p>Similarly you can run individual commands as :</p>\n\n<pre><code>python3.6 process_input.py \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-06T07:34:36.963", "Id": "225638", "ParentId": "225354", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T13:56:51.427", "Id": "225354", "Score": "5", "Tags": [ "python", "python-3.x", "object-oriented" ], "Title": "Parking Lot Object Oriented Design Python" }
225354
<p>This is my first serious post on any stackexchange so any criticism is welcome.</p> <p>Github link to the code in this question: <a href="https://github.com/yevsev/tagged_tuple" rel="nofollow noreferrer">https://github.com/yevsev/tagged_tuple</a></p> <h2>Problem statement</h2> <p>For a computation pipeline it is quite common to have a sequence of functions where each function transforms the data type to a new type. Example of a small pipeline:</p> <pre class="lang-cpp prettyprint-override"><code>ResultType Pipeline(InputType input) { FooOutput foo_output = Foo(input); BarOutput bar_output = Bar(foo_output); return ComputeResult(foo_output, bar_output); } </code></pre> <p>Now if we add one more step to the pipeline then this can affect everything else:</p> <pre><code>ResultType Pipeline(InputType input) { FooOutput foo_output = Foo(input); BarOutput bar_output = Bar(foo_output); StepOutput step_output = Step(bar_output); return ComputeResult(foo_output, bar_output, step_output); } </code></pre> <p>The new function <code>Step()</code> takes <code>BarOutput</code> as its argument but it could also have taken <code>FooOutput</code> or any combination of the types that are present in the function <code>Pipeline</code> (<code>InputType</code>, <code>FooOutput</code>, <code>BarOutput</code>, <code>ResultType</code>). This example illustrates that the problem gets worse with a longer pipeline. It will get even worse when the dependencies between processing steps is not only sequential as in a pipeline, but tree-like. Doing a small refactor on a computation tree can be a lot more difficult then it has to be because of the strict type-safety of function arguments.</p> <p>The <code>std::tuple</code> or variadic templates provide more flexibility but usually at the cost of (the clarity of) compiler errors.</p> <h2>Proposed solution</h2> <p>A compile-time associative array (tagged tuple) can provide all flexibility that is needed to reduce refactoring cost while maintaining clear compiler errors. The elements of the tagged tuple are gettable by Tag rather than be index which means that the ordering of the tuple becomes irrelevant since each element has its own unique identifier. The flexibility is improved further by allowing the compiler to convert seemingly incompatible collections of types (tuples). Here follow some examples of tuples that are not convertible by default but would be convertible using a tagged tuple:</p> <ol> <li>Order of types is different: <code>std::tuple&lt;int, std::string&gt;</code> and <code>std::tuple&lt;std::string, int&gt;</code>. The compiler generates a different type for each tuple but the conversion is arbitrary if each element in the tuple has a unique Tag type since the data are only reordered.</li> <li>Subset of types: <code>std::tuple&lt;int, std::string&gt;</code> is a subset of <code>std::tuple&lt;std::string, float, int&gt;</code>. Here are two possible conversions: converting <code>std::tuple&lt;int, std::string&gt;</code> to <code>std::tuple&lt;std::string, float, int&gt;</code> which would leave the <code>float</code> untouched and vice versa which would not copy the <code>float</code>.</li> <li>Intersection of types: <code>std::tuple&lt;int, std::string, std::vector&lt;bool&gt;&gt;</code> and <code>std::tuple&lt;std::string, float, int&gt;</code> have two types in common. Converting <code>std::tuple&lt;int, std::string, std::vector&lt;bool&gt;&gt;</code> to <code>std::tuple&lt;std::string, float, int&gt;</code> will leave <code>float</code> untouch and will not copy <code>std::vector&lt;bool&gt;</code> and for the opposite case it will leave <code>std::vector&lt;bool&gt;</code> untouched while not copying the <code>float</code>.</li> </ol> <p>A copying policy could be used to select what form of conversion is allowed for each instance of the tagged tuple.</p> <p>The tagged tuple will work exactly like the <code>std::tuple</code> but instead of getting elements by index they are gettable by a unique Tag type. In this way, a function <code>Foo()</code> that takes a tagged tuple as argument only cares about the existence of some specific types within the tagged tuple, the rest is irrelevant but still there and remains unaffected by whatever is done inside <code>Foo()</code>. </p> <p>This pattern could be useful as sort of a middleware that decouples different steps in a computation tree. It also becomes a lot easier to add data to the pipeline without affecting the steps of the pipeline.</p> <p>I would highly appreciate any feedback on the following:</p> <ul> <li>Anything related to metaprogramming.</li> <li>Possible impact on compilation time due to templates and how to improve.</li> <li>How to add a copying policy in a clean manner?</li> <li>My motivation for why the tagged tuple is useful.</li> </ul> <h2>Implementation</h2> <p>Only tested with GCC 8.3.0</p> <p>I created a working implementation of a tagged_tuple at the bottom of this post but first a toy example to show how different steps in a computation become decoupled:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; #include "tagged_tuple.hpp" struct Tag1; struct TagTimestamp; struct TagTemperature; struct TagPressure; struct TagCameraFrame; struct CameraFrame4K {int big_data;}; template&lt;typename... Ts&gt; tt::tagged_tuple&lt;Ts..., TagTemperature, unsigned int&gt; TemperatureSensor(tt::tagged_tuple&lt;Ts...&gt; const&amp; in, unsigned int temperature) { tt::tagged_tuple&lt;Ts..., TagTemperature, unsigned int&gt; out = in; tt::get&lt;TagTemperature&gt;(out) = temperature; tt::get&lt;TagTimestamp&gt;(out) += 1; return out; } template&lt;typename... Ts&gt; void TemperatureSensor(tt::tagged_tuple&lt;Ts...&gt; * data, unsigned int temperature) { tt::get&lt;TagTemperature&gt;(*data) = temperature; tt::get&lt;TagTimestamp&gt;(*data) += 1; } template&lt;typename... Ts&gt; tt::tagged_tuple&lt;Ts..., TagPressure, unsigned int&gt; PressureSensor(tt::tagged_tuple&lt;Ts...&gt; const&amp; in, unsigned int pressure) { tt::tagged_tuple&lt;Ts..., TagPressure, unsigned int&gt; out = in; tt::get&lt;TagPressure&gt;(out) = pressure; tt::get&lt;TagTimestamp&gt;(out) += 1; return out; } template&lt;typename... Ts&gt; tt::tagged_tuple&lt;Ts..., TagCameraFrame, CameraFrame4K&gt; CameraSensor(tt::tagged_tuple&lt;Ts...&gt; const&amp; in, CameraFrame4K frame) { tt::tagged_tuple&lt;Ts..., TagCameraFrame, CameraFrame4K&gt; out = in; tt::get&lt;TagCameraFrame&gt;(out) = frame; tt::get&lt;TagTimestamp&gt;(out) += 1; return out; } template&lt;typename... Ts&gt; bool Actuator(tt::tagged_tuple&lt;Ts...&gt;&amp; in) { unsigned int pressure = tt::get&lt;TagPressure&gt;(in); unsigned int temperature = tt::get&lt;TagTemperature&gt;(in); // Do some processing based on data if (pressure &gt;= 228 &amp;&amp; temperature &lt;= 5) { std::cout &lt;&lt; "Supercritical Helium\n"; return true; } else { unsigned int temperature = tt::get&lt;TagTemperature&gt;(in); TemperatureSensor(&amp;in, temperature-1); std::cout &lt;&lt; "Lowering temperature: " &lt;&lt; temperature &lt;&lt; "K\n"; return false; } } template&lt;typename... Ts&gt; void Plant(tt::tagged_tuple&lt;Ts...&gt;&amp; in) { while(!Actuator(in)) { } } template&lt;typename T&gt; void ExpectEq(T const&amp; a,T const&amp; b) { if (a != b) { std::cerr &lt;&lt; "Values not equal" &lt;&lt; "\n"; } } int main() { // t1 contains TagTimestamp and Tag1 tt::tagged_tuple&lt;TagTimestamp, int, Tag1, float&gt; t1; // t2 contains the same types as t1 but TagTemperature was added by the sensor auto t2 = TemperatureSensor(t1, 25); ExpectEq(t1.get&lt;TagTimestamp&gt;()+1, t2.get&lt;TagTimestamp&gt;()); // t3 contains the same types as t1 and t2 but TagPressure was added by the sensor auto t3 = PressureSensor(t2, 567); ExpectEq(t2.get&lt;TagTimestamp&gt;()+1, t3.get&lt;TagTimestamp&gt;()); // Function Actuator will take any tagged_tuple that contains TagPressure and TagTemperature Actuator(t3); // Fancy new machine with camera auto t4 = CameraSensor(t3, {12345}); ExpectEq(t3.get&lt;TagTimestamp&gt;()+1, t4.get&lt;TagTimestamp&gt;()); // Actuator interface remains completely unchanged. // The function still works as expected so long as the correct Tags are present in the tagged_tuple Actuator(t4); Plant(t4); } </code></pre> <p>Working implementation of the tagged tuple.</p> <pre class="lang-cpp prettyprint-override"><code>#ifndef TAGGED_TUPLE_HPP #define TAGGED_TUPLE_HPP #include &lt;tuple&gt; namespace tt { // TODO: profile compilation with templight /////////////////////////////////////////////////////////////////////////////// /// /// traits /// /////////////////////////////////////////////////////////////////////////////// // // // List of type, more light-weight than std::tuple template&lt;typename... Ts&gt; struct pack { template&lt;typename T&gt; using push_front = pack&lt;T, Ts...&gt;; }; // // // Check if all bools provided are true template&lt;bool...&gt; struct bool_pack; template &lt;bool... Bools&gt; using all_true = std::is_same&lt;bool_pack&lt;Bools..., true&gt;, bool_pack&lt;true, Bools...&gt;&gt;; // // // Check if type T is present in Ts... template&lt;typename...&gt; struct is_one_of; template&lt;typename T&gt; struct is_one_of&lt;T&gt; : std::false_type {}; template&lt;typename T, typename... Ts&gt; struct is_one_of&lt;T, T, Ts...&gt; : std::true_type {}; template&lt;typename T, typename S, typename... Ts&gt; struct is_one_of&lt;T, S, Ts...&gt; : is_one_of&lt;T, Ts...&gt; {}; // Check if type T is present in pack&lt;Ts...&gt; template&lt;typename T, typename Pack&gt; struct is_in_pack; template&lt;typename T, typename... Ts&gt; struct is_in_pack&lt;T, pack&lt;Ts...&gt;&gt; : is_one_of&lt;T, Ts...&gt; {}; // // // Get type in Ts... at Idx template&lt;std::size_t Idx, typename... Ts&gt; struct at; template&lt;typename T, typename... Ts&gt; struct at&lt;0, T, Ts...&gt; { using type = T; }; template&lt;std::size_t Idx, typename T, typename... Ts&gt; struct at&lt;Idx, T, Ts...&gt; : at&lt;Idx-1, Ts...&gt; {}; template&lt;std::size_t Idx, typename... Ts&gt; using at_t = typename at&lt;Idx, Ts...&gt;::type; // // // Get the index of first occurence of type T in Ts... template&lt;typename T, typename... Ts&gt; struct find; template&lt;typename T, typename... Ts&gt; struct find&lt;T, T, Ts...&gt; : std::integral_constant&lt;std::size_t, 0&gt; {}; template&lt;typename T, typename S, typename... Ts&gt; struct find&lt;T, S, Ts...&gt; : std::integral_constant&lt;std::size_t, find&lt;T, Ts...&gt;::value+1&gt; {}; // // // Get type by tag template&lt;typename Tag, typename Tags, typename Vals&gt; struct find_by_tag; template&lt;typename Tag, typename... Tags, typename... Vals&gt; struct find_by_tag&lt;Tag, pack&lt;Tags...&gt;, pack&lt;Vals...&gt;&gt; : at&lt;find&lt;Tag, Tags...&gt;::value, Vals...&gt; {}; template&lt;typename Tag, typename Tags, typename Vals&gt; using find_by_tag_t = typename find_by_tag&lt;Tag, Tags, Vals&gt;::type; // // // Check if all types in Ts... are also present in Us... template&lt;typename Ts, typename Us&gt; struct is_subset_of; template&lt;typename T, typename... Ts, typename... Us&gt; struct is_subset_of&lt;pack&lt;T, Ts...&gt;, pack&lt;Us...&gt;&gt; : all_true&lt; is_one_of&lt;T, Us...&gt;::value, is_subset_of&lt;pack&lt;Ts...&gt;, pack&lt;Us...&gt;&gt;::value &gt; {}; template&lt;typename... Us&gt; struct is_subset_of&lt;pack&lt;&gt;, pack&lt;Us...&gt;&gt; : std::true_type {}; // // // Check if each type in Ts... occurs only once // If Ts... is empty will yield true template&lt;typename... Ts&gt; struct is_unique; template&lt;&gt; struct is_unique&lt;&gt; : std::true_type {}; template&lt;typename T&gt; struct is_unique&lt;T&gt; : std::true_type {}; template&lt;typename T&gt; struct is_unique&lt;T, T&gt; : std::false_type {}; template&lt;typename T, typename... Ts&gt; struct is_unique&lt;T, Ts...&gt; : all_true&lt;!is_one_of&lt;T, Ts...&gt;::value, is_unique&lt;Ts...&gt;::value&gt; {}; // // // Starting at Offset, pick every other Stride type and place in pack template&lt;std::size_t Offset, std::size_t Stride, typename... Ts&gt; struct pick; template&lt;std::size_t Offset, std::size_t Stride&gt; struct pick&lt;Offset, Stride&gt; { using types = pack&lt;&gt;; }; template&lt;std::size_t Offset, std::size_t Stride, typename T, typename... Ts&gt; struct pick&lt;Offset, Stride, T, Ts...&gt; : pick&lt;Offset - 1, Stride, Ts...&gt; {}; template&lt;std::size_t Stride, typename T, typename... Ts&gt; struct pick&lt;0, Stride, T, Ts...&gt; { using types = typename pick&lt;Stride - 1, Stride, Ts...&gt;::types::template push_front&lt;T&gt;; }; template&lt;std::size_t Offset, std::size_t Stride, typename... Ts&gt; using pick_t = typename pick&lt;Offset, Stride, Ts...&gt;::types; // template&lt;std::size_t Offset, std::size_t Stride, typename Pack&gt; struct pick_pack; template&lt;std::size_t Offset, std::size_t Stride, typename... Ts&gt; struct pick_pack&lt;Offset, Stride, pack&lt;Ts...&gt;&gt; : pick&lt;Offset, Stride, Ts...&gt; {}; template&lt;std::size_t Offset, std::size_t Stride, typename Pack&gt; using pick_pack_t = typename pick_pack&lt;Offset, Stride, Pack&gt;::types; // // // Get all types that inherit from S template&lt;typename S, typename... Ts&gt; struct extract_subtypes; template&lt;typename S&gt; struct extract_subtypes&lt;S&gt; { using types = pack&lt;&gt;; }; template&lt;typename S, typename T, typename... Ts&gt; struct extract_subtypes&lt;S, T, Ts...&gt; { using types = std::conditional_t&lt; std::is_base_of&lt;S, T&gt;::value, // TODO: This cannot handle undefined structs typename extract_subtypes&lt;S, Ts...&gt;::types::template push_front&lt;T&gt;, typename extract_subtypes&lt;S, Ts...&gt;::types &gt;; }; template&lt;typename S, typename... Ts&gt; using extract_subtypes_t = typename extract_subtypes&lt;S, Ts...&gt;::types; // // // Get set difference of pack&lt;Ss...&gt; and pack&lt;Ts...&gt; // All types in Ss... that are not in Ts... template&lt;typename Ss, typename Ts&gt; struct diff; template&lt;typename... Ts&gt; struct diff&lt;pack&lt;&gt;, pack&lt;Ts...&gt;&gt; { using types = pack&lt;&gt;; }; template&lt;typename S, typename... Ss, typename... Ts&gt; struct diff&lt;pack&lt;S, Ss...&gt;, pack&lt;Ts...&gt;&gt; { using types = std::conditional_t&lt; is_one_of&lt;S, Ts...&gt;::value, typename diff&lt;pack&lt;Ss...&gt;, pack&lt;Ts...&gt;&gt;::types, typename diff&lt;pack&lt;Ss...&gt;, pack&lt;Ts...&gt;&gt;::types::template push_front&lt;S&gt; &gt;; }; template&lt;typename Ss, typename Ts&gt; using diff_t = typename diff&lt;Ss, Ts&gt;::types; // // // Check if tagged type is in (Tags.../Vals...) template&lt;typename Tag1, typename Val1, typename Tags, typename Vals&gt; struct is_in_tagged_pack; template&lt;typename Tag_, typename Val_, typename... Tags, typename... Vals&gt; struct is_in_tagged_pack&lt;Tag_, Val_, pack&lt;Tags...&gt;, pack&lt;Vals...&gt;&gt; : std::conditional_t&lt; all_true&lt; is_one_of&lt;Tag_, Tags...&gt;::value, is_one_of&lt;Val_, Vals...&gt;::value &gt;::value, std::is_same&lt;Val_, find_by_tag_t&lt;Tag_, pack&lt;Tags...&gt;, pack&lt;Vals...&gt;&gt;&gt;, // std::is_same&lt;Val, at_t&lt;find&lt;Tag, Tags...&gt;::value, Vals...&gt;&gt;, std::false_type &gt; {}; template&lt;typename Tag_, typename Val_, typename Tag2_, typename Val2_&gt; struct is_in_tagged_pack&lt;Tag_, Val_, pack&lt;Tag2_&gt;, pack&lt;Val2_&gt;&gt; : std::false_type {}; template&lt;typename Tag_, typename Val_&gt; struct is_in_tagged_pack&lt;Tag_, Val_, pack&lt;&gt;, pack&lt;&gt;&gt; : std::false_type {}; template&lt;typename Tag_, typename Val_&gt; struct is_in_tagged_pack&lt;Tag_, Val_, pack&lt;Tag_&gt;, pack&lt;Val_&gt;&gt; : std::true_type {}; // // // Check if tagged types (Tags1.../Vals1...) is a subset of tagged types (Tags2.../Vals2...) template&lt;typename Tags1, typename Vals1, typename Tags2, typename Vals2&gt; struct is_subset_of_tagged_impl; template&lt;typename Tag1_, typename... Tags1, typename Val1_, typename... Vals1, typename... Tags2, typename... Vals2&gt; struct is_subset_of_tagged_impl&lt;pack&lt;Tag1_, Tags1...&gt;, pack&lt;Val1_, Vals1...&gt;, pack&lt;Tags2...&gt;, pack&lt;Vals2...&gt;&gt; : std::conditional_t&lt; // is_one_of&lt;Tag1_, Tags2...&gt;::value, is_in_tagged_pack&lt;Tag1_, Val1_, pack&lt;Tags2...&gt;, pack&lt;Vals2...&gt;&gt;::value, all_true&lt; std::is_same&lt;Val1_, at_t&lt;find&lt;Tag1_, Tags2...&gt;::value, Vals2...&gt;&gt;::value, is_subset_of_tagged_impl&lt;pack&lt;Tags1...&gt;, pack&lt;Vals1...&gt;, pack&lt;Tags2...&gt;, pack&lt;Vals2...&gt;&gt;::value &gt;, std::false_type &gt; {}; template&lt;typename Tag1_, typename Val1_, typename Tag2_, typename Val2_&gt; struct is_subset_of_tagged_impl&lt;pack&lt;Tag1_&gt;, pack&lt;Val1_&gt;, pack&lt;Tag2_&gt;, pack&lt;Val2_&gt;&gt; : all_true&lt; std::is_same&lt;Tag1_, Tag2_&gt;::value, std::is_same&lt;Val1_, Val2_&gt;::value &gt; {}; template&lt;typename... Tags2, typename... Vals2&gt; struct is_subset_of_tagged_impl&lt;pack&lt;&gt;, pack&lt;&gt;, pack&lt;Tags2...&gt;, pack&lt;Vals2...&gt;&gt; : std::true_type{}; template&lt;typename Tags1, typename Vals1, typename Tags2, typename Vals2&gt; struct is_subset_of_tagged; template&lt;typename... Tags1, typename... Vals1, typename... Tags2, typename... Vals2&gt; struct is_subset_of_tagged&lt;pack&lt;Tags1...&gt;, pack&lt;Vals1...&gt;, pack&lt;Tags2...&gt;, pack&lt;Vals2...&gt;&gt; : std::conditional_t&lt; all_true&lt; is_subset_of&lt;pack&lt;Tags1...&gt;, pack&lt;Tags2...&gt;&gt;::value, is_subset_of&lt;pack&lt;Vals1...&gt;, pack&lt;Vals2...&gt;&gt;::value &gt;::value, is_subset_of_tagged_impl&lt;pack&lt;Tags1...&gt;, pack&lt;Vals1...&gt;, pack&lt;Tags2...&gt;, pack&lt;Vals2...&gt;&gt;, std::false_type &gt; {}; /////////////////////////////////////////////////////////////////////////////// /// /// tagged_tuple /// /////////////////////////////////////////////////////////////////////////////// namespace detail { // // // Each typename T provided to serve as Tag is wrapped in tt::Tag&lt;T&gt; template&lt;typename T&gt; struct Tag; // // // Types that can be provided as options must inherit from tt::Option struct Option {}; //template&lt;typename... Ts&gt; using extract_options_t = extract_subtypes_t&lt;Option, Ts...&gt;; //template&lt;typename... Ts&gt; using extract_tags_values_t = diff_t&lt;pack&lt;Ts...&gt;, extract_options_t&lt;Ts...&gt;&gt;; //template&lt;typename... Ts&gt; using extract_tags_t = pick_pack_t&lt;0, 2, extract_tags_values_t&lt;Ts...&gt;&gt;; //template&lt;typename... Ts&gt; using extract_vals_t = pick_pack_t&lt;1, 2, extract_tags_values_t&lt;Ts...&gt;&gt;; template&lt;typename... Ts&gt; using extract_tags_t = pick_t&lt;0, 2, Ts...&gt;; template&lt;typename... Ts&gt; using extract_vals_t = pick_t&lt;1, 2, Ts...&gt;; // // // template&lt;typename Tags, typename Vals&gt; struct tagged_tuple_impl; // // // Policy structs for deciding what copies are allowed struct copying_policy_flexible { template &lt;typename TagsSrc, typename ValsSrc, typename TagsDst, typename ValsDst&gt; struct is_copyable_t; template &lt;typename... TagsSrc, typename... ValsSrc, typename... TagsDst, typename... ValsDst&gt; struct is_copyable_t&lt;pack&lt;TagsSrc...&gt;, pack&lt;ValsSrc...&gt;, pack&lt;TagsDst...&gt;, pack&lt;ValsDst...&gt;&gt; : all_true&lt; is_subset_of_tagged&lt;pack&lt;TagsSrc...&gt;, pack&lt;ValsSrc...&gt;, pack&lt;TagsDst...&gt;, pack&lt;ValsDst...&gt;&gt;::value || is_subset_of_tagged&lt;pack&lt;TagsDst...&gt;, pack&lt;ValsDst...&gt;, pack&lt;TagsSrc...&gt;, pack&lt;ValsSrc...&gt;&gt;::value &gt; {}; template &lt;template&lt;class,class&gt; class TaggedTuple, typename... TagsSrc, typename... ValsSrc, typename... TagsDst, typename... ValsDst&gt; constexpr static bool is_copyable( TaggedTuple&lt;pack&lt;TagsSrc...&gt;, pack&lt;ValsSrc...&gt;&gt; /*src*/, TaggedTuple&lt;pack&lt;TagsDst...&gt;, pack&lt;ValsDst...&gt;&gt; /*dst*/) { return is_copyable_t&lt;pack&lt;TagsSrc...&gt;, pack&lt;ValsSrc...&gt;, pack&lt;TagsDst...&gt;, pack&lt;ValsDst...&gt;&gt;::value; } }; /** * @brief copy_from copy all elements of @param{src} to @param{dst} * Copy in case src is subset of dst * is_subset_of_tagged&lt;pack&lt;TagsSrc...&gt;, pack&lt;ValsSrc...&gt;, pack&lt;TagsDst...&gt;, pack&lt;ValsDst...&gt;&gt;::value == true */ template&lt;std::size_t Idx = 0, typename... TagsSrc, typename... ValsSrc, typename... TagsDst, typename... ValsDst&gt; constexpr std::enable_if_t&lt;Idx &lt; sizeof...(TagsSrc), void&gt; copy_from( tagged_tuple_impl&lt;pack&lt;TagsSrc...&gt;, pack&lt;ValsSrc...&gt;&gt; const&amp; src, tagged_tuple_impl&lt;pack&lt;TagsDst...&gt;, pack&lt;ValsDst...&gt;&gt;&amp; dst) { using Tag = at_t&lt;Idx, TagsSrc...&gt;; dst.template get&lt;Tag&gt;() = src.template get&lt;Tag&gt;(); copy_from&lt;Idx + 1&gt;(src, dst); } template&lt;std::size_t Idx = 0, typename... TagsSrc, typename... ValsSrc, typename... TagsDst, typename... ValsDst&gt; constexpr std::enable_if_t&lt;Idx == sizeof...(TagsSrc), void&gt; copy_from( tagged_tuple_impl&lt;pack&lt;TagsSrc...&gt;, pack&lt;ValsSrc...&gt;&gt; const&amp; /*src*/, tagged_tuple_impl&lt;pack&lt;TagsDst...&gt;, pack&lt;ValsDst...&gt;&gt;&amp; /*dst*/) { // Nothing left to do } /** * @brief copy_to for each type in @param{dst} copy the corresponding element from @param{src} * Copy in case src is subset of dst * is_subset_of_tagged&lt;pack&lt;TagsSrc...&gt;, pack&lt;ValsSrc...&gt;, pack&lt;TagsDst...&gt;, pack&lt;ValsDst...&gt;&gt;::value == true */ template&lt;std::size_t Idx = 0, typename... TagsSrc, typename... ValsSrc, typename... TagsDst, typename... ValsDst&gt; constexpr std::enable_if_t&lt;Idx &lt; sizeof...(TagsDst), void&gt; copy_to( tagged_tuple_impl&lt;pack&lt;TagsSrc...&gt;, pack&lt;ValsSrc...&gt;&gt; const&amp; src, tagged_tuple_impl&lt;pack&lt;TagsDst...&gt;, pack&lt;ValsDst...&gt;&gt;&amp; dst) { using Tag = at_t&lt;Idx, TagsDst...&gt;; dst.template get&lt;Tag&gt;() = src.template get&lt;Tag&gt;(); copy_to&lt;Idx + 1&gt;(src, dst); } template&lt;std::size_t Idx = 0, typename... TagsSrc, typename... ValsSrc, typename... TagsDst, typename... ValsDst&gt; constexpr std::enable_if_t&lt;Idx == sizeof...(TagsDst), void&gt; copy_to( tagged_tuple_impl&lt;pack&lt;TagsSrc...&gt;, pack&lt;ValsSrc...&gt;&gt; const&amp; /*src*/, tagged_tuple_impl&lt;pack&lt;TagsDst...&gt;, pack&lt;ValsDst...&gt;&gt;&amp; /*dst*/) { // Nothing left to do } /** * TagsSrc... is subset of TagsDst... so use copy_from */ template&lt;typename... TagsSrc, typename... ValsSrc, typename... TagsDst, typename... ValsDst&gt; constexpr std::enable_if_t&lt; all_true&lt; is_subset_of&lt;pack&lt;TagsSrc...&gt;, pack&lt;TagsDst...&gt;&gt;::value, !is_subset_of&lt;pack&lt;TagsDst...&gt;, pack&lt;TagsSrc...&gt;&gt;::value // need this to handle reorder case &gt;::value,void&gt; copy_impl( tagged_tuple_impl&lt;pack&lt;TagsSrc...&gt;, pack&lt;ValsSrc...&gt;&gt; const&amp; src, tagged_tuple_impl&lt;pack&lt;TagsDst...&gt;, pack&lt;ValsDst...&gt;&gt;&amp; dst) { copy_from(src, dst); } /** * TagsSrc... is subset of TagsDst... so use copy_to */ template&lt;typename... TagsSrc, typename... ValsSrc, typename... TagsDst, typename... ValsDst&gt; constexpr std::enable_if_t&lt;is_subset_of&lt;pack&lt;TagsDst...&gt;, pack&lt;TagsSrc...&gt;&gt;::value, void&gt; copy_impl( tagged_tuple_impl&lt;pack&lt;TagsSrc...&gt;, pack&lt;ValsSrc...&gt;&gt; const&amp; src, tagged_tuple_impl&lt;pack&lt;TagsDst...&gt;, pack&lt;ValsDst...&gt;&gt;&amp; dst) { copy_to(src, dst); } /** * Check if copying is allowed by CopyingPolicy. */ template&lt;class CopyingPolicy = detail::copying_policy_flexible, typename... TagsSrc, typename... ValsSrc, typename... TagsDst, typename... ValsDst&gt; constexpr void copy( tagged_tuple_impl&lt;pack&lt;TagsSrc...&gt;, pack&lt;ValsSrc...&gt;&gt; const&amp; src, tagged_tuple_impl&lt;pack&lt;TagsDst...&gt;, pack&lt;ValsDst...&gt;&gt;&amp; dst) { // static_assert(CopyingPolicy::is_copyable(src, dst), "Copying tagged_tuple not possible."); static_assert( CopyingPolicy::template is_copyable_t&lt; pack&lt;TagsSrc...&gt;, pack&lt;ValsSrc...&gt;, pack&lt;TagsDst...&gt;, pack&lt;ValsDst...&gt; &gt;::value, "Copying tagged_tuple not possible."); copy_impl(src, dst); } template&lt;typename... Tags, typename... Vals&gt; struct tagged_tuple_impl&lt;pack&lt;Tags...&gt;, pack&lt;Vals...&gt;&gt; : std::tuple&lt;Vals...&gt; { template &lt;typename... Args&gt; constexpr tagged_tuple_impl(Args&amp;&amp;... args) : std::tuple&lt;Vals...&gt;(std::forward&lt;Args&gt;(args)...) { // check if all tags are unique static_assert(is_unique&lt;Tags...&gt;::value, "All Tags in tagged_tuple must be unique."); } template&lt;typename Tag&gt; constexpr at_t&lt;find&lt;Tag, Tags...&gt;::value, Vals...&gt; const&amp; get() const { return std::get&lt;find&lt;Tag, Tags...&gt;::value&gt;(*this); } template&lt;typename Tag&gt; constexpr at_t&lt;find&lt;Tag, Tags...&gt;::value, Vals...&gt;&amp; get() { return std::get&lt;find&lt;Tag, Tags...&gt;::value&gt;(*this); } }; } // end namespace detail template&lt;typename... Ts&gt; struct tagged_tuple : detail::tagged_tuple_impl&lt; detail::extract_tags_t&lt;Ts...&gt;, detail::extract_vals_t&lt;Ts...&gt; &gt; { // typedefs for convenience using Tags = detail::extract_tags_t&lt;Ts...&gt;; using Vals = detail::extract_vals_t&lt;Ts...&gt;; using Impl = detail::tagged_tuple_impl&lt;Tags, Vals&gt;; using Self = tagged_tuple&lt;Ts...&gt;; using CopyingPolicy = detail::copying_policy_flexible; // template&lt;typename... Args, std::enable_if_t&lt;std::is_same&lt;pack&lt;std::decay_t&lt;Args&gt;...&gt;, Vals&gt;::value || sizeof...(Args) == 0&gt;* = nullptr&gt; constexpr tagged_tuple(Args... args) : Impl(std::forward&lt;Args&gt;(args)...) {} template&lt;typename... TagsOther, typename... ValsOther&gt; constexpr tagged_tuple(detail::tagged_tuple_impl&lt;pack&lt;TagsOther...&gt;, pack&lt;ValsOther...&gt;&gt; const&amp; other) { detail::copy&lt;CopyingPolicy&gt;(other, *this); } template&lt;typename... TagsOther, typename... ValsOther&gt; constexpr Self&amp; operator=(detail::tagged_tuple_impl&lt;pack&lt;TagsOther...&gt;, pack&lt;ValsOther...&gt;&gt; const&amp; other) { detail::copy&lt;CopyingPolicy&gt;(other, *this); return *this; } }; template&lt;typename Tag, typename... Tags, typename... Vals&gt; constexpr at_t&lt;find&lt;Tag, Tags...&gt;::value, Vals...&gt;&amp; get(detail::tagged_tuple_impl&lt;pack&lt;Tags...&gt;,pack&lt;Vals...&gt;&gt;&amp; t) { return t.template get&lt;Tag&gt;(); } template&lt;typename Tag, typename... Tags, typename... Vals&gt; constexpr at_t&lt;find&lt;Tag, Tags...&gt;::value, Vals...&gt; const&amp; get(detail::tagged_tuple_impl&lt;pack&lt;Tags...&gt;,pack&lt;Vals...&gt;&gt; const&amp; t) { return t.template get&lt;Tag&gt;(); } } // end namespace tt #endif // TAGGED_TUPLE_HPP </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-22T01:24:31.380", "Id": "446287", "Score": "0", "body": "Which standard are you targeting? Your `all_true` seems to suggest that you are in the pre-C++17 era." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-23T17:16:11.900", "Id": "446465", "Score": "0", "body": "@L.F. Thanks for your reply, I was not aware of any build-in trait to check for truth of a pack of bools. Could you please tell me more about this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-24T09:53:15.280", "Id": "446538", "Score": "0", "body": "Oh, we have [fold expressions](https://en.cppreference.com/w/cpp/language/fold) in C++17 `(Bools && ...)` and also [`std::conjunction`](https://en.cppreference.com/w/cpp/types/conjunction)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-24T17:38:57.457", "Id": "446637", "Score": "0", "body": "@L.F. Yes of course! My mind was stuck in c++14, thanks for the tip :)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T19:19:41.883", "Id": "225378", "Score": "3", "Tags": [ "c++", "template-meta-programming" ], "Title": "Tagged Tuple with \"special\" copying" }
225378
<p>For an iOS app which helps me rolling back <a href="https://meta.stackexchange.com/questions/tagged/vandalism">vandalism</a> on Stack Exchange, I have a piece of Swift code which downloads a revision page (<a href="https://codereview.stackexchange.com/posts/189958/revisions">example</a>) and tries to find the 'spacer' <a href="https://en.wikipedia.org/wiki/Fragment_identifier" rel="nofollow noreferrer">fragment</a> just above a certain revision. It might not be clear what I'm talking about, so here's a picture from Firefox + developer tools:</p> <p><a href="https://i.stack.imgur.com/FbNzT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FbNzT.png" alt="enter image description here"></a></p> <p>I have the HTML content of this page, and the GUID of the revision (<code>8f9ab85f-1401-41e9-8f75-8a07b10bad32</code>) from the <a href="https://api.stackexchange.com/">Stack Exchange API</a>. I'm looking for that element just above the revision header, since those are the only HTML elements with IDs on the page. I need that <code>spacer-9617187a-fe48-4212-9a1a-f3a366e62736</code> so I can link directly to <a href="https://codereview.stackexchange.com/posts/189958/revisions#spacer-9617187a-fe48-4212-9a1a-f3a366e62736">https://codereview.stackexchange.com/posts/189958/revisions#spacer-9617187a-fe48-4212-9a1a-f3a366e62736</a></p> <p>For that, I've written a few lines of Swift code. The problem is that string handling in Swift confuses the **** out of me. Most of the language feels rather good, but I'd rather do string manipulation in SQL than in Swift...</p> <p>Here is what I have so far. It works, but I was wondering if it could break in cases I haven't foreseen, or if it can be made more understandable/manageable by a future me. You see, even Stack Exchange's syntax highlighter has problems understanding it...</p> <p>The input parameters for this piece of code are <code>html</code> (a String containing the content of the revisions page, e.g. <a href="https://codereview.stackexchange.com/posts/189958/revisions">https://codereview.stackexchange.com/posts/189958/revisions</a>) and <code>revisionGUID</code> (<code>8F9AB85F-1401-41E9-8F75-8A07B10BAD32</code> in the example above - the API returns them in upper case). <code>fragment</code> is eventually used as output parameter. The <code>43</code> is the length of <code>spacer-</code> plus a GUID.</p> <pre><code>// Find fragment just above selected revision let range = html.range(of: #"onclick="StackExchange.revisions.toggle('"# + revisionGUID.lowercased() + #"')""#)! let index = html.range(of: #"&lt;tr id=""#, options: .backwards, range: html.startIndex..&lt;range.lowerBound)!.upperBound let fragment = String(html[index..&lt;html.index(index, offsetBy: 43)]) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T19:44:22.830", "Id": "437614", "Score": "0", "body": "Could you include an appendix with an example of a full html page you are parsing like this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T19:47:10.520", "Id": "437615", "Score": "1", "body": "I've added the link at a more appropriate place, I'm not sure if including the full 20 pages of HTML would be beneficial. It's a Stack Exchange link and not likely to break :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T19:55:22.533", "Id": "437616", "Score": "1", "body": "not enough for an answer, but I would prefer _let offset = \"spacer-${guid_format}\".characters.count_ over a magic number _43_ with _${guid_format}_ being a default guid." } ]
[ { "body": "<p>I don't know how stable the precise HTML structure of those pages is, could that change in the future? Using a HTML parsing library might be a more robust approach.</p>\n\n<p>Some remarks concerning the Swift implementation:</p>\n\n<ul>\n<li>Don't force-unwrap optionals. If one of the searched strings is not found, your program will terminate with a runtime error. Use optional binding with <code>if let</code> or <code>guard let</code> instead, and handle the failure case properly.</li>\n<li>Instead of converting <code>revisionGUID</code> to lowercase you can do a case-insensitive search. </li>\n<li><p>The first search string can be created with string interpolation instead of concatenation, that makes the expression slightly shorter:</p>\n\n<pre><code>#\"onclick=\"StackExchange.revisions.toggle('\\#(revisionGUID)')\"\"#\n</code></pre></li>\n<li><p>Use a regular expression with positive look-ahead and look-behind for the second search. That allows to find the precise range of the spacer, without relying on a particular length.</p></li>\n<li>Put the code in a function, and add documentation.</li>\n</ul>\n\n<p>Putting it together, the function could look like this:</p>\n\n<pre><code>/// Find spacer fragment for GUID on revisions page\n/// - Parameter html: HTML of a revisions page\n/// - Parameter revisionGUID: A revision GUID from the StackExchange API\n/// - Returns: The spacer fragment, or `nil` if not found\n\nfunc findFragment(html: String, revisionGUID: String) -&gt; String? {\n let pattern1 = #\"onclick=\"StackExchange.revisions.toggle('\\#(revisionGUID)')\"\"#\n guard let range1 = html.range(of: pattern1, options: .caseInsensitive) else {\n return nil\n }\n let pattern2 = #\"(?&lt;=&lt;tr id=\")[^\"]+(?=\")\"#\n guard let range2 = html.range(of: pattern2,\n options: [.backwards, .regularExpression],\n range: html.startIndex..&lt;range1.lowerBound) else {\n return nil\n }\n\n return(String(html[range2]))\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T20:44:50.947", "Id": "225382", "ParentId": "225380", "Score": "1" } } ]
{ "AcceptedAnswerId": "225382", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T19:39:14.100", "Id": "225380", "Score": "3", "Tags": [ "strings", "html", "swift", "stackexchange" ], "Title": "Determine fragment identifier from HTML page in Swift" }
225380
<p>I've found a little task to create a block memory pool allocator. This allocator is required to allocate memory in single fixed-sized blocks from the pool in static memory. Sizes of block and pool are fixed at compile-time, but should be tweakable during the build. This allocator should work on various embedded multithreaded platforms (RTOS). It also should contain several tests.</p> <p>This is the solution I've come up with, I'd really love to hear some feedback.</p> <pre><code>#include &lt;array&gt; #include &lt;bitset&gt; #include &lt;cassert&gt; #include &lt;condition_variable&gt; #include &lt;cstddef&gt; #include &lt;mutex&gt; #include &lt;stdexcept&gt; namespace block_allocator { namespace detail { enum class ExhaustedBehaviour { throw_exception = 0, // If the pool is exhausted (empty) throw the std::bad_alloc{} wait_for_release // If the pool is exhausted wait for other thread to release an object }; } template &lt;std::size_t block_size = 8, std::size_t blocks = 32, detail::ExhaustedBehaviour behaviour = detail::ExhaustedBehaviour::throw_exception&gt; class Pool final { public: using pointer = void *; // Thread-safe static singleton initialization ([stmt.dcl]) // Singleton prevents the static initialization order fiasco static auto&amp; get_instance() { static Pool&lt;block_size, blocks&gt; pool; return pool; } // Thread-safe (not interrupt-safe!) allocator [[nodiscard]] pointer allocate() { auto lock = std::unique_lock(mutex); if constexpr (behaviour == detail::ExhaustedBehaviour::wait_for_release) { if (occupation_flags.all()) condition_variable.wait(lock); } // Find index of the vacant chunk to be returned auto vacant = FindVacant(); occupation_flags[vacant] = 1; return &amp;internal_pool[vacant]; } // Thread-safe deallocation and pool inclusion check void deallocate(pointer pointer) { auto lock = std::unique_lock(mutex); auto delta = GetPoolIndex(pointer); // Memory doesn't belong to the pool. // In any other code I would've thrown an exception, but deallocations often occur in destructors. if (delta &gt;= blocks) return; const bool is_exhausted = occupation_flags.all(); occupation_flags[delta] = 0; if constexpr (behaviour == detail::ExhaustedBehaviour::wait_for_release) { if (is_exhausted) condition_variable.notify_one(); } } private: // Type alias for an array of block_size bytes using Block = std::array&lt;std::byte, block_size&gt;; // Singleton helper Pool() = default; // Linear memory-efficient search time. // For big PoolSizes one could prefer a linked list for a O(1) search time on account of dynamic memory allocation. auto FindVacant() { for (std::size_t i = 0; i &lt; blocks; ++i) if (occupation_flags[i] == 0) return i; if constexpr (behaviour == detail::ExhaustedBehaviour::throw_exception) throw std::bad_alloc{}; else throw std::runtime_error("Unexpected end of pool (check the correct usage of the is_exhausted flag)"); } // O(1) chunk offset calculation auto GetPoolIndex(pointer pointer) { auto delta = static_cast&lt;std::size_t&gt;(reinterpret_cast&lt;Block*&gt;(pointer) - reinterpret_cast&lt;Block*&gt;(&amp;internal_pool[0])); return delta; } // Uninitialized storage for block_size * blocks bytes // Note the lack of alignment requirements. This may become a problem on ARM-alike architectures with placement new std::array&lt;Block, blocks&gt; internal_pool; // Occupation flags. Every bit represents the corresponding internal_pool element. 0 stands for vacant, 1 — occupied std::bitset&lt;blocks&gt; occupation_flags; // Condition variable for notifying other threads when the detail::ExhaustedBehaviour::wait_for_release is selected static inline std::condition_variable condition_variable; std::mutex mutex; }; template &lt;std::size_t block_size = 8, std::size_t blocks = 32&gt; class PoolTest { public: // Should be GTest, simplified for the sake of density static bool test() { auto dst = test_double_deallocation(); dst &amp;= test_block_size(); dst &amp;= test_exhaust(); dst &amp;= test_threads(); return dst; } private: // Simple (incomplete) RAII for internal test use. // One should also delete the copy constructor and copy assignment operator template &lt;typename T, typename pool&gt; class AutoDeallocator { public: AutoDeallocator() { pointer = reinterpret_cast&lt;T*&gt;(pool::get_instance().allocate()); } ~AutoDeallocator() { pool::get_instance().deallocate(pointer); } operator T*() const { return pointer; } private: T* pointer = nullptr; }; using current_pool = Pool &lt;block_size, blocks&gt;; using pool_wrapper = AutoDeallocator&lt;std::byte, current_pool&gt;; // Test the accidental double deallocation static bool test_double_deallocation() { try { auto&amp; pool = current_pool::get_instance(); auto ptr = pool.allocate(); pool.deallocate(ptr); pool.deallocate(ptr); } catch (...) { return false; } return true; } // Verify the block size via the pointer arithmetic static bool test_block_size() { auto first = pool_wrapper(); auto second = pool_wrapper(); auto delta = second - first; return delta == block_size; } // Request all the blocks and catch the std::bad_alloc exception when requesting the extra one static bool test_exhaust() { std::array&lt;pool_wrapper, blocks&gt; arr{}; try { pool_wrapper exhaust; } catch (std::bad_alloc&amp;) { return true; } catch(...) { return false; } return false; } static bool test_threads() { auto func = [](std::exception_ptr&amp; e) { try { auto allocated = pool_wrapper(); } catch(...) { e = std::current_exception(); } }; std::array&lt;std::thread, blocks&gt; array_of_threads; std::array&lt;std::exception_ptr, blocks&gt; array_of_exceptions; for(std::size_t i = 0; i &lt; array_of_threads.size(); ++i) { array_of_threads[i] = std::thread([&amp;]() { func(array_of_exceptions[i]); }); } std::for_each(array_of_threads.begin(), array_of_threads.end(), [](auto&amp;current_thread) { current_thread.join(); }); return std::all_of(array_of_exceptions.begin(), array_of_exceptions.end(), [](auto&amp; val) {return val == nullptr; }); } }; } static bool pool_test = block_allocator::PoolTest&lt;9, 4&gt;::test(); int main() { assert(pool_test); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T14:06:28.033", "Id": "440366", "Score": "0", "body": "You don't need 90% of this code. It's as simple as allocating a static array of bytes and keep track of the used size. If you for some reason would need to free blocks, you should be using stack (RAII) allocation instead." } ]
[ { "body": "<p>from reading through your code I've collected following remarks:</p>\n\n<ul>\n<li>Why do you only allow one instance of your allocator?</li>\n<li>Note: the <code>pointer</code> typedef in <code>std::allocator</code> is deprecated in C++17. </li>\n<li>In <code>Pool::allocate</code>, you are waiting using <code>condition_variable.wait()</code>. This function may return without being notified because of a <em>spurious wakeup</em>. The usual solution is to wait for the condition in a loop and check a boolean flag (here: <code>occupation_flags.all()</code>). C++ offers a second interface for <code>wait()</code> allowing you to pass a predicate that is checked in a loop:</li>\n</ul>\n\n<pre><code> if (occupation_flags.all())\n condition_variable.wait(lock, []{ return occupation_flags.all(); });\n</code></pre>\n\n<ul>\n<li>In <code>Pool::deallocate</code> you are only notifying the condition if the pool is exhausted. What if two threads are waiting for a newly released block? You may leave the second thread waiting forever. There is no need to only notify if someone is listening, just send the signal.</li>\n<li>In <code>Pool::deallocate</code> you are checking if the pointer belongs to the pool and silently throw this error away. C++ philosophy was always to not prevent the developer from shooting himself in the foot. You should fail as loud as possible, that is, make it an assert. Freeing memory that is not managed by the pool suggests there is a serious bug in the application and the user should know about it.</li>\n<li><code>In Pool::FindVacant</code> use <code>auto</code> and <code>0u</code>:</li>\n</ul>\n\n<pre><code>for (auto i = 0u; i &lt; blocks; ++i)\n if (occupation_flags[i] == 0)\n return i;\n</code></pre>\n\n<p>Some general comments:</p>\n\n<ul>\n<li>I think offering two types of error handling for the allocator complicates the whole class. You may be better off implementing two different allocators (<code>BlockingAllocator</code> and <code>ThrowingAllocator</code>) than handling this inside of the class. </li>\n<li>I would replace the block_size parameter by a type parameter. The allocator can then allocate elements of that type (the size can be derived from it using <code>sizeof</code>) and you don't need to <code>reinterpret_cast</code> your pointers in the class and outside of the class. </li>\n</ul>\n\n<p><em>EDIT</em></p>\n\n<p>Just went over the test cases. </p>\n\n<ol>\n<li><code>static bool test_double_deallocation()</code> usually double-free is an error. I would expect the application to either raise an error or walk into undefined behavior. With this test case you're documenting that your interface supports double-free, which is at least uncommon.</li>\n<li>Just a small one:</li>\n</ol>\n\n<pre><code>catch (std::bad_alloc&amp;)\n</code></pre>\n\n<p>Better catch by const-ref.</p>\n\n<ol start=\"3\">\n<li><code>static bool test_threads()</code>\nWhats the purpose of this test? You're not looking for exceptions, you're only allocating once per thread. IMO a test case should document a certain feature of the API. Here you're only checking that no exception was raised. You can achieve this easier and more readable by simply flipping an atomic flag in your <code>catch</code>.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T12:28:55.580", "Id": "437665", "Score": "0", "body": "Thanks for the time you've taken to review the code. Now about the remarks:\n\n\n1. Only one instance is allowed because it was required by the task to store the internal pool in the static memory.\n\n2. You are correct, however, this allocator is not compatible with the `std::allocator` and `std::allocator_traits<>` due to the lack of rebinding.\n\n\n4. In `Pool::deallocate` it is only possible (by interface) to return one memory block to the allocator. Therefore, only one thread gets notified. The other thread will get notified when one more block will become available." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T12:29:01.897", "Id": "437666", "Score": "0", "body": "5. I don't quite like the error suppression in the `Pool::deallocate` myself. Yes, there should be an assert.\n6. It's not correct on x86_64 systems (https://godbolt.org/z/uew9KQ). `auto i = 0u` resolves to the `std::uint32_t`, while on 64-bit systems sizes are stored in 64 bits.\n\nAbout the comments:\n1. Splitting this allocator into two will lead to the massive code duplication.\n2. Again, the task was to develop a memory block allocator. Of course, it'd be more convenient to make an object allocator and a placement new inside the `construct` function" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T13:06:16.283", "Id": "437672", "Score": "1", "body": "4. Imagine the following situation: the pool is exhausted and two threads try to get a block. Both threads will wait until the condition variable is notified. Now two threads that already have allocated a block start deallocating it. The first thread will issue a notification, as the pool is exhausted. When the second thread releases it's block, the pool is not exhausted anymore, hence no notification takes place. In this situation you'll have only one of the two waiting threads awakened." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T13:16:04.340", "Id": "437674", "Score": "0", "body": "Regarding the splitting: I would argue that code duplication is not necessarly a bad thing ;-) Here you have a trade-off between data structure complexity and having a similar copy of the allocator class (but with fewer code)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T13:27:05.153", "Id": "437676", "Score": "0", "body": "4. Now I get it, thanks. You're totally correct" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T13:47:57.240", "Id": "437678", "Score": "0", "body": "6. Frankly I'm a bit surprised. I see the compiler output, but I'd have expected that `auto` for integers would default to the platform alignment. In this case, I'd go for your initial version, though I'm interested in the rationale why compiler chooses 32bit." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T11:44:56.567", "Id": "225408", "ParentId": "225381", "Score": "2" } } ]
{ "AcceptedAnswerId": "225408", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T19:50:52.417", "Id": "225381", "Score": "10", "Tags": [ "c++", "memory-management", "c++17", "embedded" ], "Title": "Static block memory allocator" }
225381
<p>This is the code for a basic endpoint in my express app routes folder. This firstly renders a page, and then on a continuous loop, renders information about some random "Breaking Bad" character. </p> <p>The idea is to have the page load, and then every two seconds, the page updates automatically with the new character info. Then two seconds later, a new character replaces the one on the screen, and so on. </p> <p>To do this, I'm making use of a convenient Breaking Bad REST-ful API</p> <pre><code>const express = require("express"); const app = require("../app"); const router = express.Router(); const axios = require("axios"); const socket = require("../socketioAPI"); router.get("/", function(req, res, next) { runCharacterUpdateInterval(); res.render("index", { title: "Breaking Bad Page" }); }); const runCharacterUpdateInterval = () =&gt; { const updateTime = 2000; setInterval(() =&gt; { updatePageWithRandomCharacter(); }, updateTime); }; const updatePageWithRandomCharacter = () =&gt; { createCharacter().then(profile =&gt; { socket.push("breaking bad", profile); }); }; const createCharacter = async () =&gt; { const characterId = getRandomCharacterId(); const bio = await queryAPI("characters/" + characterId); const { quote } = await queryAPI("quote/random?author=" + encode(bio.name)); const { deathCount } = await queryAPI("death-count?name=" + encode(bio.name)); return await { bio, quote, deathCount }; }; const encode = name =&gt; { return name.replace(/ /g, "+"); }; const getRandomCharacterId = () =&gt; { const totalChar = 54; const initalChar = 1; return Math.floor(Math.random() * Math.floor(totalChar)) + initalChar; }; const queryAPI = async endpoint =&gt; { const api = await axios.get(`https://www.breakingbadapi.com/api/${endpoint}`); if (await api.data[0]) return await api.data[0]; else return { name: [], quote: [], deathCount: [] }; }; module.exports = router; </code></pre> <p>In the past, my code has been reviewed as "spaghetti-like", and not clean. I've been trying to fix this, and so any pointers on the style, readability, or anything code related would be greatly appreciated. </p>
[]
[ { "body": "<h3>Linting</h3>\n\n<p>The code reads well. </p>\n\n<p>There is one convention you missed: use <code>\\s</code> to indicate whitespace.</p>\n\n<blockquote>\n<pre><code>const encode = name =&gt; {\n return name.replace(/ /g, \"+\");\n};\n</code></pre>\n</blockquote>\n\n<pre><code>const encode = name =&gt; {\n return name.replace(/\\s/g, \"+\");\n};\n</code></pre>\n\n<p>And the <code>else</code> below is redundant.</p>\n\n<blockquote>\n<pre><code>if (await api.data[0]) return await api.data[0];\nelse return { name: [], quote: [], deathCount: [] };\n</code></pre>\n</blockquote>\n\n<pre><code>if (await api.data[0]) return await api.data[0];\nreturn { name: [], quote: [], deathCount: [] };\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T04:36:42.430", "Id": "225394", "ParentId": "225384", "Score": "2" } }, { "body": "<h3>Conditional line not in brackets</h3>\n\n<p>There is an <code>if</code> statement in <code>queryAPI()</code> without brackets. This impacts readability greatly- especially if the code to be conditionally executed gets moved to the line below. It is best to always include brackets. </p>\n\n<p>I haven’t tested this with your code but you could simplify the <code>if</code>/<code>else</code> to a statement that uses <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_OR_()\" rel=\"nofollow noreferrer\">short-circuit evaluation</a> with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_OR_()\" rel=\"nofollow noreferrer\">logical OR</a>:</p>\n\n<pre><code>return api.data[0] || { name: [], quote: [], deathCount: [] };\n</code></pre>\n\n<h3>Variable names</h3>\n\n<p>Some variables are misleading e.g.:</p>\n\n<blockquote>\n<pre><code>const api = await axios.get(`https://www.breakingbadapi.com/api/${endpoint}`);\n</code></pre>\n</blockquote>\n\n<p>The return value should be an API response - not an API. Thus a name like <code>apiResponse</code> or <code>response</code> would be more descriptive. </p>\n\n<h3>Constants in all capitals</h3>\n\n<p>For constants that shouldn’t change, most style guides for JavaScript (as well as similar languages) call for constant names to be all uppercase.</p>\n\n<p>E.g. </p>\n\n<pre><code>const UPDATE_TIME = 2000;\nconst TOTAL_CHAR = 54;\nconst INITIAL_CHAR = 1;\n</code></pre>\n\n<p>I am presuming there was a typo in the name <code>initalChar</code>.</p>\n\n<p>It might also be wise to define URLs in constants.</p>\n\n<p>Those variables could be moved out of the functions and put near the top of the code or in an included module. That way if any of them need to be updated you wouldn’t have to hunt through the code. </p>\n\n<h3>Simplify interval function</h3>\n\n<p>The callback can just be a reference. So anonymous function in the block:</p>\n\n<blockquote>\n<pre><code>setInterval(() =&gt; {\n updatePageWithRandomCharacter();\n }, updateTime);\n</code></pre>\n</blockquote>\n\n<p>Can be shortened to:</p>\n\n<pre><code>setInterval(updatePageWithRandomCharacter, UPDATE_TIME);\n</code></pre>\n\n<p>That line could replace the call to <code>runCharacterUpdateInterval()</code> and then that function wouldn’t be needed anymore. </p>\n\n<h3>Excess <code>await</code> keywords</h3>\n\n<p>Unless I am missing something, there are more <code>await</code> keywords than are necessary. For example:</p>\n\n<blockquote>\n<pre><code>return await { bio, quote, deathCount };\n</code></pre>\n</blockquote>\n\n<p>Should not need the <code>await</code> keyword because it is just a plain object. </p>\n\n<p>The same applies to this line:</p>\n\n<blockquote>\n<pre><code>if (await api.data[0]) return await api.data[0];\n</code></pre>\n</blockquote>\n\n<h3>Useless call to <code>Math.floor()</code></h3>\n\n<p>The return line of <code>getRandomCharacterId()</code> is:</p>\n\n<blockquote>\n<pre><code>return Math.floor(Math.random() * Math.floor(totalChar)) + initalChar;\n</code></pre>\n</blockquote>\n\n<p>And <code>totalChar</code> is assigned the value <code>54</code> which is an integer and this equivalent to the floor of <code>54</code> so that call to <code>Math.floor()</code> can be removed. </p>\n\n<h3>Arrow functions could be a single line</h3>\n\n<p>It is not mandatory but simple functions don’t need brackets or a <code>return</code>- for example:</p>\n\n<blockquote>\n<pre><code>const encode = name =&gt; {\n return name.replace(/ /g, \"+\");\n};\n</code></pre>\n</blockquote>\n\n<p>Could be simplified to:</p>\n\n<pre><code>const encode = name =&gt; name.replace(/ /g, \"+\");\n</code></pre>\n\n<p>The same is true for this promise callback:</p>\n\n<blockquote>\n<pre><code>createCharacter().then(profile =&gt; {\n socket.push(\"breaking bad\", profile);\n});\n</code></pre>\n</blockquote>\n\n<p>Though if the brackets were removed then the return value from the call to <code>socket.push()</code> would then be returned from the callback. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T06:19:41.377", "Id": "225400", "ParentId": "225384", "Score": "2" } } ]
{ "AcceptedAnswerId": "225400", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T21:35:28.980", "Id": "225384", "Score": "4", "Tags": [ "javascript", "node.js", "ecmascript-6", "express.js", "socket.io" ], "Title": "An Express route, which renders a page, and makes use of socket.io" }
225384
<p>I want to make a booking entry. I want to ask whether the code that i wrote below is rightly format or not?</p> <p>I haven't tried it, because there's still more code that needs to be written. I just want to ask this before I continue to write.</p> <pre><code>&lt;?php require 'Connection.php'; //Check Connection if ($conn-&gt;connect_error){ die("Connection Failed: ". $conn-&gt;connect_error); } //Create Variable Submitted Booking $MarketingName = $_POST["Marketing"]; $CustomerName = $_POST["CustName"]; $CustomerEmail = $_POST["CustEmail"]; $HouseID = $_POST["IDHouse"]; $UnitNo = $_POST["UnitNo"]; $Remarks = $_POST["Remarks"]; //Select All Data in Database $sql = $conn-&gt;prepare ("SELECT Property_No FROM cust_bookedfr WHERE Property_No = '" . $UnitNo . "' "); $result = mysqli_query($conn, $sql); if ($result-&gt;num_rows &gt; 0) { //Validate Username echo "Property Unit is already taken."; } else { echo "Creating a Booking."; if (filter_var($Marketing, FILTER_SANITIZE_STRING)) { if (filter_var($CustName, FILTER_SANITIZE_STRING)) { if (filter_var($Cust_Email, FILTER_SANITIZE_EMAIL)) { if (filter_var($HouseID, FILTER_VALIDATE_INT)) { if (filter_var($UnitNo, FILTER_SANITIZE_STRING)) { if (filter_var($Remarks, FILTER_SANITIZE_STRING)) { //Insert the Username and Password into Database $sql2 = $conn-&gt;prepare ("INSERT INTO cust_bookedfr (NULL, Marketing_Name, Cust_Name, Cust_Email, Property_Name, Property_ID, Property_No, Property_Qty, Property_Price, Remarks, DateAccess) VALUES ('" . $MarketingName . "', '" . $CustomerName . "', '" . $CustomerEmail . "', 'Fajri Residential', '" . $HouseID . "', '" . $UnitNo . "', '', '', '" . $Remarks . "', NOW())"); if ($conn-&gt;query($sql2) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql2 . "&lt;br&gt;" . $conn-&gt;error; } } } } } } } } $sql-&gt;close(); $sql2-&gt;close(); $conn-&gt;close(); ?&gt; </code></pre>
[]
[ { "body": "<ul>\n<li><p>If you are going to use a prepared statement (please do) then go the extra step of using placeholders and bound parameters. Your queries are not currently stable/secure.</p></li>\n<li><p>If you don't truly need <code>Property_No</code> for anything, just return <code>COUNT</code> from your first query, and evaluate that value as a boolean (loose truthy comparison). This is cleaner and more deliberate, I reckon.</p></li>\n<li><p>Your code is suffering from excessive tabbing (aka \"arrowhead\" code). This increases the likelihood that you or future devs will need to tediously scroll horizontally to review/manage the code.</p></li>\n<li><p>If all of the conditions must be true to reach the INSERT query, then just use one condition statement with the expressions separated by <code>&amp;&amp;</code>.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T12:50:58.707", "Id": "225411", "ParentId": "225388", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T00:58:35.767", "Id": "225388", "Score": "3", "Tags": [ "php", "mysqli" ], "Title": "Creating a booking based on a POST request" }
225388
<p>I wrote this code to show that my <a href="https://www.reddit.com/r/mathematics/comments/cihfeu/this_euler_series_for_%CF%80_is_beautiful_and/?utm_source=share&amp;utm_medium=web2x" rel="nofollow noreferrer">reddit post</a> is correct.</p> <blockquote> <p>After the first two terms, the signs are determined as follows: If the denominator is a prime of the form 4m − 1, the sign is positive; if the denominator is a prime of the form 4m + 1, the sign is negative; for composite numbers, the sign is equal the product of the signs of its factors.</p> <p>Basically it's the harmonic series minus the non-Gaussian prime reciprocals and reciprocals which factors are an odd multiple of the non-Gaussian primes- beautifully embodying <a href="https://en.m.wikipedia.org/wiki/Quadratic_reciprocity" rel="nofollow noreferrer">quadratic reciprocity</a>.</p> </blockquote> <p>This is a very, very inefficient way to calculate π. However, I believe it's the most beautiful. Which is a hard sell, because π algorithms are pretty much the most harmonious things.</p> <p>This formula for π is my favorite because it clearly shows how a circle is related to the harmonic series, and how that series is related to the prime number theorem and quadratic reciprocity. I love all algorithms for π, this is for its 'insight' it provides in relating π, primes, and quadratics.</p> <p>Something to note is that swapping the logic here from n%4==1 to n%4==3 results in the sum = π/2 , and converges a bit faster.</p> <pre><code>import decimal iters = int(input('Number of Iterations: ')) D = decimal.Decimal decimal.getcontext().prec = 100 def prime_factors(n): i = 2 factors = [] while i * i &lt;= n: if n % i: i += 1 else: n //= i factors.append(i) if n &gt; 1: factors.append(n) return factors s = D(0) for x in range(1, iters): clist = [int(i) for i in prime_factors(x)] plist = [n for n in clist if n%4==1] if len(plist)%2!=0: s-=1/D(x) else: s += 1/D(x) print(s) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T05:42:21.743", "Id": "437641", "Score": "0", "body": "Minor mistake, but it will hurt you sooner or later if you are not cautious: you ask the number of iterations, then loop on `range(1, iters)`, which has length iters-1 (`range(a, b)` contains values from a to be **excluding b**. So, the loop should be on `range(1, iters + 1)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T05:52:28.273", "Id": "437643", "Score": "0", "body": "Nice catch! Merci!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T16:37:29.780", "Id": "437694", "Score": "0", "body": "I could be wrong, but I thought the series for PI alternated signs with each term." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T16:59:44.860", "Id": "437697", "Score": "0", "body": "You're thinking of the Leibniz series my friend :) There are alot of series for pi." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T18:29:27.973", "Id": "437699", "Score": "1", "body": "@ThomasMatthews: if you alternate signs on each term, the sum is log 2." } ]
[ { "body": "<h3>Blank lines</h3>\n\n<p>You require 2 blank lines before <code>def</code> statements to be <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> compliant.</p>\n\n<pre><code>decimal.getcontext().prec = 100\n\n\ndef prime_factors(n):\n</code></pre>\n\n<h3>Whitespace</h3>\n\n<p>You have your operators written as follows:</p>\n\n<blockquote>\n<pre><code>len(plist)%2!=0\n</code></pre>\n</blockquote>\n\n<p>You should use whitespace around operators instead:</p>\n\n<pre><code> if len(plist) % 2 != 0:\n</code></pre>\n\n<h3>Refactored</h3>\n\n<pre><code>import decimal\niters = int(input('Number of Iterations: '))\nD = decimal.Decimal\ndecimal.getcontext().prec = 100\n\n\ndef prime_factors(n):\n i = 2\n factors = []\n while i * i &lt;= n:\n if n % i:\n i += 1\n else:\n n //= i\n factors.append(i)\n if n &gt; 1:\n factors.append(n)\n return factors\n\n\ns = D(0)\nfor x in range(1, iters):\n clist = [int(i) for i in prime_factors(x)]\n plist = [n for n in clist if n % 4 == 1]\n if len(plist) % 2 != 0:\n s -= 1 / D(x)\n else:\n s += 1 / D(x)\n print (s)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T07:30:59.553", "Id": "437651", "Score": "3", "body": "Sorry, your review is not useful at all." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T07:41:34.200", "Id": "437652", "Score": "15", "body": "@stefan apology accepted" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T14:45:01.307", "Id": "437682", "Score": "1", "body": "I would also put a blank line between import and the rest of the code. Not sure if it is somewhere in PEP 8 or no, though. Also, you introduced a space on the last line which shouldn't be there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T21:54:56.260", "Id": "437716", "Score": "5", "body": "@stefan - How is this not useful? There are code standards for a reason. In any case, +1." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-23T06:42:12.260", "Id": "440603", "Score": "1", "body": "I almost thought you speak python but seeing the first comment... you probably thought the same :-P" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-23T06:52:21.467", "Id": "440605", "Score": "1", "body": "@t3chb0t Well, I do try from time to time o_O https://codereview.stackexchange.com/search?q=user%3A200620+%5Bpython%5D+OR+%5Bcython%5D" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T05:28:31.953", "Id": "225396", "ParentId": "225391", "Score": "6" } }, { "body": "<p>You don't need plist, only its length. Likewise, you don't really need to build clist, its values would be enough, making <code>prime_factors</code> a generator. You may also remove the <code>if</code>.\nNote that given the extremely slow convergence, it's really not useful to compute with 100 decimals, so you could use floats instead.</p>\n\n<pre><code>import decimal\n\niters = int(input('Number of Iterations: '))\nD = decimal.Decimal\ndecimal.getcontext().prec = 100\n\n\ndef prime_factors(n):\n i = 2\n while i * i &lt;= n:\n if n % i:\n i += 1\n else:\n n //= i\n yield i\n if n &gt; 1:\n yield n\n\ns = D(0)\nfor n in range(1, iters + 1):\n k = sum(1 for p in prime_factors(n) if p % 4 == 1)\n s += (-1)**k / D(n)\n print(s)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T06:06:12.420", "Id": "437645", "Score": "1", "body": "Good point about the convergence, I shall simplify when I share this algorithm. I had been comparing 6 different Pi algorithms when writing this one and needed the precision there :) I shall share that project here too." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T05:56:42.967", "Id": "225397", "ParentId": "225391", "Score": "5" } }, { "body": "<p>What you are approximating is\n<span class=\"math-container\">$$ \\pi =\\sum_{m=1}^{\\infty}\\frac{(-1)^{s(m)}}{m},$$</span>\nwhere <span class=\"math-container\">\\$s(m)\\$</span> counts the number of appearances of primes of the form <span class=\"math-container\">\\$4k+1\\$</span> in the prime decomposition of <span class=\"math-container\">\\$m\\$</span>, compare </p>\n\n<ul>\n<li><a href=\"https://math.stackexchange.com/q/434313/42969\">How can we prove <span class=\"math-container\">\\$\\pi =1+\\frac{1}{2}+\\frac{1}{3}+\\frac{1}{4}-\\frac{1}{5}+\\frac{1}{6}+\\frac{1}{7}+\\cdots\\,\\$</span>?</a></li>\n</ul>\n\n<p>on Mathematics Stack Exchange.</p>\n\n<p>The computation of the factor <span class=\"math-container\">\\$ (-1)^{s(m)} \\$</span> can be done more efficiently: Instead of creating a list of all prime factors of <span class=\"math-container\">\\$m \\$</span>, then filtering the list for prime factors of the form <span class=\"math-container\">\\$4k+1\\$</span>, and finally counting the filtered list, you can compute the sign while factoring the number:</p>\n\n<pre><code>def sign_for_pi_series(n):\n \"\"\" Returns sign for 1/n in the pi series.\n\n The sign is -1 if n has an odd number of prime factors of the form 4k+1,\n and +1 otherwise.\n \"\"\"\n s = 1\n i = 2\n while i * i &lt;= n:\n if n % i:\n i += 1\n else:\n n //= i\n if i % 4 == 1:\n s = -s\n if n &gt; 1 and n % 4 == 1:\n s = -s\n return s\n</code></pre>\n\n<p>The summation then simplifies to</p>\n\n<pre><code>sum_pi = sum(D(sign_for_pi_series(x))/D(x) for x in range(1, iters + 1))\nprint(sum_pi)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T06:08:13.077", "Id": "225399", "ParentId": "225391", "Score": "13" } } ]
{ "AcceptedAnswerId": "225399", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T02:43:33.657", "Id": "225391", "Score": "12", "Tags": [ "python", "algorithm", "python-3.x", "primes", "numerical-methods" ], "Title": "Python π = 1 + (1/2) + (1/3) + (1/4) - (1/5) + (1/6) + (1/7) + (1/8) + (1/9) - (1/10) ...1748 Euler" }
225391
<p>I have created an XLAM file called "MyCustomAddIn" from an XLSB file called "Call Tracker" which contains all my Subroutines, Functions and UserForms. I have referenced "MyCustomAddIn" inside of "Call Tracker" workbook. </p> <p>Below are a few scenarios when calling Subs, Functions or UserForms from "MyCustomAddIn" reference. All macros are being called from my WorkBook, "Call Tracker" My ultimate goal is to not have to reference the ActiveWorkbook for each Sub, Function, and UserForm.</p> <p>I have noticed that without referencing "Call Tracker" as the ActiveWorkbook, the user form values will go to a sheet inside "MyCustomAddIn" XLAM file, same goes for UDF, it gets the values from a sheet inside of "MyCustomAddIn"</p> <p>Is there a better way to create and deploy an Add-In that contains all my VBA Code without containing any sheets as an XLAM file does?</p> <p><strong>Scenario1: Calling a UserForm from a Sub assigned to shape within "Call Tracker"</strong> The following Sub returns a <code>Runtime Error 424 Object Required</code></p> <pre><code>Sub RectangleRoundedCorners1_Click() UserForm1.Show 'highlights this line on the error, XLAM reference houses UserForm1 End Sub </code></pre> <p><strong>Scenario2: Calling a Sub Procedure from a shape that calls the UserForm</strong> This method doesn't return an error, why? Can we not reference UserForm Objects from a referenced Add-In? </p> <pre><code>'assign the sub to a shape in "Call Tracker" Workbook Sub RectangleRoundedCorners1_Click() showUserForm End Sub 'call the user form Sub showUserForm() UserForm1.Show End Sub </code></pre> <p><strong>Scenario 3: Using UserForms to input values into Worksheet Cells</strong></p> <p><em>Would I have to reference the <code>ActiveWorkbook</code> in each of my UserForms?</em></p> <pre><code>Private Sub CommandButton1_Click() Set wb = ActiveWorkbook Set ws = wb.Sheets("clientmenu") forceLogOut 'clear filter so that we don't mix new customers up If ActiveSheet.FilterMode Then ActiveSheet.ShowAllData With ws.Shapes("priorities") .Fill.ForeColor.RGB = RGB(64, 64, 64) End With End If If contact.value &lt;&gt; "" And result.value = vbNullString Then MsgBox "Please enter a result" result.BorderColor = vbRed result.BackColor = vbYellow result.DropDown Exit Sub ElseIf contact.value = vbNullString And result.value &lt;&gt; "" Then MsgBox "Please enter a date" contact.BorderColor = vbRed contact.BackColor = vbYellow Exit Sub Else: With ws callDate callResult End With End If With ws lastrow = .Range("A" &amp; Rows.Count).End(xlUp).Row + 1 If Me.priority_ = vbNullString Then ws.Range("A" &amp; lastrow).Interior.Color = vbWhite ws.Range("A" &amp; lastrow).Font.Color = RGB(0, 0, 0) ElseIf Me.priority_ = "None" Then ws.Range("A" &amp; lastrow).Interior.Color = vbWhite ws.Range("A" &amp; lastrow).Font.Color = RGB(0, 0, 0) ws.Range("B" &amp; lastrow).value = vbNullString ElseIf Me.priority_ = "High" Then '.Cells(x, 1).Interior.Color = RGB(0, 176, 80) ws.Range("A" &amp; lastrow).Font.Color = RGB(0, 176, 80) ws.Range("B" &amp; lastrow).value = addnewClient.priority_.Text ElseIf Me.priority_ = "Medium" Then '.Cells(x, 1).Interior.Color = RGB(255, 207, 55) ws.Range("A" &amp; lastrow).Font.Color = RGB(255, 207, 55) ws.Range("B" &amp; lastrow).value = addnewClient.priority_.Text ElseIf Me.priority_ = "Low" Then '.Cells(x, 1).Interior.Color = RGB(241, 59, 59) ws.Range("A" &amp; lastrow).Font.Color = RGB(241, 59, 59) ws.Range("B" &amp; lastrow).value = addnewClient.priority_.Text End If If Me.client = vbNullString Then MsgBox "Must enter Clients name in order to proceed" Exit Sub ElseIf Me.client &lt;&gt; vbNullString Then ws.Range("L" &amp; lastrow).value = Format(Now(), "mm/dd/yyyy") ws.Range("A" &amp; lastrow).value = addnewClient.client.Text ws.Range("A" &amp; lastrow).Font.Name = "Arial" ws.Range("A" &amp; lastrow).Font.Size = 18 ws.Range("A" &amp; lastrow).Font.Bold = True ws.Range("B" &amp; lastrow).Font.Name = "Arial" ws.Range("B" &amp; lastrow).Font.Size = 14 ws.Range("B" &amp; lastrow).HorizontalAlignment = xlCenter ws.Range("C" &amp; lastrow).value = addnewClient.priority.Text ws.Range("C" &amp; lastrow).Font.Name = "Arial" ws.Range("C" &amp; lastrow).Font.Size = 14 ws.Range("C" &amp; lastrow).HorizontalAlignment = xlCenter ws.Range("E" &amp; lastrow).value = addnewClient.contact.value ws.Range("E" &amp; lastrow).Font.Name = "Arial" ws.Range("E" &amp; lastrow).Font.Size = 14 ws.Range("E" &amp; lastrow).HorizontalAlignment = xlCenter ws.Range("G" &amp; lastrow).value = addnewClient.result.Text ws.Range("G" &amp; lastrow).Font.Name = "Arial" ws.Range("G" &amp; lastrow).Font.Size = 14 ws.Range("G" &amp; lastrow).HorizontalAlignment = xlCenter ws.Range("I" &amp; lastrow).value = addnewClient.segmentType.Text ws.Range("I" &amp; lastrow).Font.Name = "Arial" ws.Range("I" &amp; lastrow).Font.Size = 14 ws.Range("I" &amp; lastrow).HorizontalAlignment = xlCenter ws.Range("K" &amp; lastrow).value = addnewClient.notes.Text If Me.contact = vbNullString Then ElseIf Me.contact &lt;&gt; vbNullString Then ws.Range("J" &amp; lastrow) = Sheet3.Range("J" &amp; lastrow).value + 1 ws.Range("J" &amp; lastrow).Font.Name = "Arial" ws.Range("J" &amp; lastrow).Font.Size = 14 ws.Range("J" &amp; lastrow).Font.Bold = True ws.Range("J" &amp; lastrow).HorizontalAlignment = xlCenter End If End If End With 'With Sheet3 'Sheet3.Range("A" &amp; lastrow &amp; ":K" &amp; lastrow).Interior.Color = vbWhite Application.GoTo Range("A" &amp; lastrow), True 'End With wb.Sheets(2).Range("C4") = Format(Now, "mm/dd/yyyy") Unload Me End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T06:18:26.627", "Id": "437646", "Score": "1", "body": "Not sure I understand. If you want to reference the workbook that has the running code, it's ThisWorkbook instead of ActiveWorkbook. But you may also declare a variable of class Worksheet, as you do here with `ws` (I think it's safer: as long as you know the name, you don't have to be in the worksheet for the macro to work). If you want to distribute your code, you could export as a .bas file, but I would not recommend it unless it's going to be used by people who know VBA fairly well (they would have to import the basic code into a workbook to run it). What's wrong with an XLAM?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T06:23:08.927", "Id": "437647", "Score": "0", "body": "@Jean Claude Arbaut basically my code thinks it's still running in the XLAM file when calling it from another workbook. I would like to avoid having to write 'Set WB = ActiveWorkbook` for every subroutine, function, and userform" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T06:26:26.700", "Id": "437648", "Score": "1", "body": "Well, it **is** still running from the XLAM, since it's where it is stored. It's up to you to make sure the macro acts on the correct sheet: if the macro has to act on ActiveWorkbook, you have to tell it to, one way or another. A single `set wb = ActiveWorkkbook` is not really a problem, even if it's in every function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T06:34:23.400", "Id": "437649", "Score": "0", "body": "@jean Claude Arbaut I'm starting to follow. I need to rewrite the code inside the XLAM to reflect ActiveWorkbook, without doing that all the code will run through `ThisWorkbook`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T07:25:49.753", "Id": "437650", "Score": "0", "body": "That's right. ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-05T15:43:07.223", "Id": "438056", "Score": "0", "body": "You could also define a public `activeWS` variable in one of your modules, set it once, and then refer to it from all your other subs. Not quite an elegant solution (and there are certainly problematic cases), but if you _really_ want to avoid calling `Set WB = ActiveWorkbook` over and over..." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T06:07:20.943", "Id": "225398", "Score": "0", "Tags": [ "vba", "excel" ], "Title": "Can Excel Vba code be updated via an Excel Add In for multiple users" }
225398
<p>Is it possible to write this using the stream element? I can get the most of it with stream but it is the add adding string to list which is in the map that I am caught on.</p> <pre class="lang-java prettyprint-override"><code>/** * Given a list of strings, returns a map where the keys are the unique strings lengths found in the list and the values are the strings matching each length * [hello,world,cat,ambulance] would return {5 -&gt; [hello, world], 3 -&gt; [cat] -&gt; 3, 9 -&gt; [ambulance]} * @param strings * @return */ public Map&lt;Integer,List&lt;String&gt;&gt; mapLengthToMatchingStrings(List&lt;String&gt; strings){ Map&lt;Integer,List&lt;String&gt;&gt; mapILS = new HashMap&lt;Integer, List&lt;String&gt;&gt;(); for (String str : strings) { int length = str.length(); if (mapILS.containsKey(length)) { // Add str to list at key //Get list at key List&lt;String&gt; rs = mapILS.get(length); //Add str to list rs.add(str); //Update key in map mapILS.put(length, rs); }else { // Add new key list to map //Create list List&lt;String&gt; rs = new ArrayList&lt;String&gt;(); //Add string rs.add(str); //Add key and list to map mapILS.put(length, rs); } } return mapILS; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-09T09:39:59.660", "Id": "438591", "Score": "1", "body": "For anyone voting to close this question: yes, it could be worded better. But the code seems to work and there's a description in the title & comments. The specific request is usually off-topic, but it would've been the likely outcome in a review anyway. John, for your next question, please read [our FAQ on asking questions](https://codereview.meta.stackexchange.com/q/2436/52915)." } ]
[ { "body": "<p>It's not only possible but also a great example of how functional programming can make code much simpler and readable:</p>\n\n<pre><code> public Map&lt;Integer,List&lt;String&gt;&gt; mapLengthToMatchingStrings(List&lt;String&gt; strings){\n return strings.stream().distinct().collect(Collectors.groupingBy(String::length));\n }\n</code></pre>\n\n<p>(The <code>distinct</code> part is optional, regarding whether you want duplicates in the lists)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T10:43:56.483", "Id": "437658", "Score": "0", "body": "Wow, that is great. So to the point." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T09:50:16.853", "Id": "225405", "ParentId": "225402", "Score": "2" } } ]
{ "AcceptedAnswerId": "225405", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T09:00:48.117", "Id": "225402", "Score": "2", "Tags": [ "java", "stream" ], "Title": "Group a list of strings by length" }
225402
<p>I wrote a code which is creating a Session and write in the Session Arrays diffrent things like: Username and Rank.</p> <p>I wrote then a function which is checking the Visited Profile Name and Rank and the Own Name and Rank to be sure that you have enough power to Promote/Demote.</p> <p>I want to know if there is a smarter version or if this is the best version I can wrote.</p> <p>I want to say that I am a newbie in PHP.</p> <p>The code workes fine btw. I just want ideas and suggestions for improve my code.</p> <p>Demote/Promote Button Script:</p> <pre><code>&lt;?php if (isset($_SESSION['besucht']) &amp;&amp; $_SESSION['besucht'] == 1) { if (!empty($own_username) &amp;&amp; $_SESSION['user-permissions']-1 == 6 || $_SESSION['user-permissions']-1 == 7) { if ($_SESSION['visit_user-permissions']-1 &lt; 6 &amp;&amp; $_SESSION['visit_user-permissions']-1 != $_SESSION['user-permissions']-1) { echo(' &lt;form action="./tools/php/demoter_promoter/index.php" method="POST"&gt; &lt;table style="width: 100%;"&gt; &lt;tr style="width: 100%;"&gt; &lt;td style="width: 50%;"&gt; '); if($visit_permissions-1 &gt; 0) { echo(' &lt;button style="float: left;" title="Den Rank um 1 Degradieren" id="demoter" name="demoter" value="'.$visit_username.'"&gt; Demote &lt;/button&gt; '); } echo(' &lt;/td&gt; &lt;td style="width: 50%;"&gt; '); if($visit_permissions-1 &lt; 5) { echo(' &lt;button style="float: right;" title="Den Rank um 1 Befördern" id="promoter" name="promoter" value="'.$visit_username.'"&gt; Promote &lt;/button&gt; '); } echo(' &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/form&gt; '); } } } ?&gt; </code></pre> <p>Promote Function:</p> <pre><code>&lt;?php FUNCTION promote($user) { require('../connector/connector.php'); $query = "SELECT * FROM `members` WHERE `username` = ?"; $stmt = $db-&gt;prepare($query); $stmt-&gt;bind_param('s', $user); $stmt-&gt;execute(); $result = $stmt-&gt;get_result(); $stmt-&gt;close(); $obj = $result-&gt;fetch_array(); $permissions = $obj['permissions']; if ($permissions &lt; 5) { $query = "UPDATE `members` SET `permissions` = ? WHERE `username` = '".$user."';"; $stmt = $db-&gt;prepare($query); $permissions = $permissions + 1; $stmt-&gt;bind_param('s', $permissions); $stmt-&gt;execute(); $stmt-&gt;close(); back_to_home($db); } else { back_to_home($db); } } ?&gt; </code></pre> <p>The <code>$user</code> variable is seted by the <code>$_SESSION['visit_user-username']</code></p> <p>Demote Function:</p> <pre><code>&lt;?php FUNCTION demote($user) { require('../connector/connector.php'); $query = "SELECT * FROM `members` WHERE `username` = ?"; $stmt = $db-&gt;prepare($query); $stmt-&gt;bind_param('s', $user); $stmt-&gt;execute(); $result = $stmt-&gt;get_result(); $stmt-&gt;close(); $obj = $result-&gt;fetch_array(); $permissions = $obj['permissions']; if ($permissions != 0 &amp;&amp; $permissions &lt; 6) { $query = "UPDATE `members` SET `permissions` = ? WHERE `username` = '".$user."';"; $stmt = $db-&gt;prepare($query); $permissions = $permissions - 1; $stmt-&gt;bind_param('s', $permissions); $stmt-&gt;execute(); $stmt-&gt;close(); back_to_home($db); } else { back_to_home($db); } } ?&gt; </code></pre> <p>The <code>back_to_home</code>function is a simple function which is unset all <code>$_SESSION['visit_user-*']</code> and send back to the stard page.</p> <p>This is the function caller I wrote:</p> <pre><code>&lt;?php session_start(); if(isset($_POST['promoter'])) { $user = ""; $user = $_POST['promoter']; promote($user); } else { if(isset($_POST['demoter'])) { $user = ""; $user = $_POST['demoter']; demote($user); } else { header('Location: ../../../'); exit; } } ?&gt; </code></pre> <p>This is the User Page Loader Function I wrote:</p> <pre><code>&lt;?php $value = ""; $value = basename($_SERVER['REQUEST_URI']); if(isset($_SESSION['user-username']) &amp;&amp; $value == "?logout") { require('./tools/php/pageloader/pages/logout.php'); } else { $search = '?'; $replace = ''; $subject = basename($_SERVER['REQUEST_URI']); $new_value = str_replace($search, $replace, $subject); $query = "SELECT * FROM `members` WHERE `username` = ?"; $stmt = $db-&gt;prepare($query); $stmt-&gt;bind_param('s', $new_value); $stmt-&gt;execute(); $result = $stmt-&gt;get_result(); $stmt-&gt;close(); $obj = $result-&gt;fetch_array(); if ($obj['username'] != null &amp;&amp; $obj['username'] == $new_value) { $_SESSION['visit_user-username'] = $obj['username']; $_SESSION['visit_user-e_mail'] = $obj['e_mail']; $_SESSION['visit_user-register_date'] = $obj['register_date']; $_SESSION['visit_user-last_login_date'] = $obj['last_login_date']; $_SESSION['visit_user-steam_id'] = $obj['steam_id']; $_SESSION['visit_user-permissions'] = $obj['permissions'] + 1; $_SESSION['visit_user-ban_status'] = $obj['banned'] + 1; require('./tools/php/pageloader/pages/usercheck.php'); } else { //echo("&lt;meta http-equiv='refresh' content='0; url=./'&gt;"); } } ?&gt; </code></pre> <p>My permissions stats with <code>0</code> so I needed to write them with <code>+ 1</code> in to the Array and check them with <code>- 1</code> other wise the MySQL code wouldn't give me the result xD</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T10:27:46.420", "Id": "437655", "Score": "0", "body": "I would use a framework, even if just a micro one like Slim or Lumen." } ]
[ { "body": "<p>I don't completely understand your code, which can be a problem when reviewing it, but I think I can get quite far. </p>\n\n<p>Let me start with the two functions, <code>promote()</code> and <code>demote()</code>, that are at the center of your code. There are several things I notice straight away:</p>\n\n<ul>\n<li><p>Both functions are, apart from an <code>+</code> or <code>-</code> sign, identical. There's a well known principle in programming that says: <strong>Don't repeat yourself</strong> or <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a>. Your code is not dry, it is wet. You would only need one function where you use two.</p></li>\n<li><p>There is a <code>require()</code> inside these functions. That is highly unusual in PHP. It means you drag everything that is in that script into the local scope of the function. That is a bad idea because when you're working on the script you might not be aware of the variables in the function, and visa versa.</p></li>\n<li><p>You are preparing the queries, which is good for security, but then you insert the <code>$user</code> variable directly into the query string of the second query, and this variable is user input. That's a big security hole. You did it right in the first query. See: <a href=\"https://www.php.net/manual/en/security.database.sql-injection.php\" rel=\"nofollow noreferrer\">SQL_injection</a></p></li>\n<li><p>You don't check the result of database operations. It could be that <code>prepare()</code> or <code>execute()</code> return <code>false</code>, in that case you cannot proceed.</p></li>\n<li><p>The change of permission can be done with one simple query, see code below.</p></li>\n</ul>\n\n<p>From what I can understand of your code we would need two functions: One to read the value of <code>permissions</code> from the database, and the other to update the value <code>permissions</code>. I'm not even looking at the <code>back_to_home()</code> function now, because it should not be part of what we're doing here. So, let's code the two functions we need.</p>\n\n<pre><code>&lt;?php\n\nfunction getUserPermissions($link, $username)\n{\n $query = \"SELECT `permissions` FROM `members` WHERE `username` = ?\";\n if ($stmt = $link-&gt;prepare($query)) {\n $stmt-&gt;execute();\n $stmt-&gt;bind_result($permissions);\n $stmt-&gt;fetch();\n $stmt-&gt;close();\n return $permissions;\n } \n return false;\n}\n\nfunction setUserPermissions($link, $username, $permissions)\n{\n $query = \"UPDATE `members` SET `permissions` = ? WHERE `username` = ?\";\n if ($stmt = $link-&gt;prepare($query)) {\n $stmt-&gt;bind_param('si', $username, $permissions);\n $success = $stmt-&gt;execute();\n $stmt-&gt;close();\n return $success;\n } \n return false;\n}\n</code></pre>\n\n<p>Now let's go one step up in the chain and write the script that accepts the form submission. You located this at <code>\"./tools/php/demoter_promoter/index.php\"</code>.</p>\n\n<pre><code>&lt;?php\n\nsession_start();\n\n$input_change = filter_input(INPUT_POST, 'change', FILTER_SANITIZE_NUMBER_INT);\n\nif (isset($_SESSION['user-username'])) {\n\n require('../connector/connector.php');\n\n $username = $_SESSION['user-username'];\n $permissions = getUserPermissions($db, $username);\n\n switch($input_change) { \n case +1 : if ($permissions &lt;= 6) {\n setUserPermissions($db, $username, $permissions + 1);\n }\n break;\n case -1 : if ($permissions &gt;= 1) {\n setUserPermissions($db, $username, $permissions - 1);\n }\n break;\n }\n}\n</code></pre>\n\n<p>First of all, for obvious reasons of security I do not post the user name in the form. This would allow any hacker to try other user names. I retrieve the user name from the session, as it was set when the user logged in. This has the added advantage that it checks whether the user is actually logged in.</p>\n\n<p>Instead of using the posted field name, as a way to distinguish between promotion and demotion of the permission, I chose one integer field with the name <code>change</code>. Simply because this is easier. The script only reacts to the values <code>+1</code> and <code>-1</code>. </p>\n\n<p>I always use <a href=\"https://www.php.net/manual/en/ref.filter.php\" rel=\"nofollow noreferrer\">the filter functions</a> to do the first filtering of user input at the top of the script. This gives me clear control over the input into the script. These functions do not completely clean user input, but it is a first step. To make clear to myself that something is user input I prefix it with <code>input_</code>, that way I know I have to treat these variables with care.</p>\n\n<p>As you can see I put the <code>require()</code> here, in the global scope.</p>\n\n<p>Now finally the form, where it all starts, the demote and promote button script:</p>\n\n<pre><code>&lt;?php\n\nsession_start();\n\nif (isset($_SESSION['user-username'])) {\n\n require('../connector/connector.php');\n\n $permissions = getUserPermissions($db, $_SESSION['user-username']);\n}\n\n?&gt;\n&lt;form action=\"./tools/php/demoter_promoter/index.php\" method=\"POST\"&gt;\n &lt;table class=\"permissionsTable\"&gt;\n &lt;tr&gt;\n &lt;td&gt;&lt;?php \n\nif (isset($permissions) &amp;&amp; ($permissions &lt; 6)) {\n echo '&lt;button id=\"promoteButton\" title=\"Den Rank um 1 Befördern\" ' . \n 'value=\"+1\" name=\"change\"&gt;Promote&lt;/button&gt;';\n} \n\n ?&gt;&lt;/td&gt;&lt;td&gt;&lt;?php\n\nif (isset($permissions) &amp;&amp; ($permissions &gt; 1)) {\n echo '&lt;button id=\"demoteButton\" title=\"Den Rank um 1 Degradieren\" ' .\n ' value=\"-1\" name=\"change\"&gt;Demote&lt;/button&gt;';\n} \n\n ?&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;/table&gt;\n&lt;/form&gt; \n</code></pre>\n\n<p>I've tried to keep this script simple. Also, I don't understand all the <code>if ()</code> conditions your script starts with. You should not use local styles in your HTML, instead use a stylesheet. I'm sure you're familiar with these. A comparable sheet for your local styles would be:</p>\n\n<pre><code>&lt;styles&gt; \n\n.permissionsTable {\n width: 100%;\n}\n\n.permissionsTable td {\n width: 50%;\n}\n\n#promoteButton {\n float: right;\n}\n\n#demoteButton {\n float: left;\n}\n\n&lt;/styles&gt;\n</code></pre>\n\n<p>I hope this answer contains some useful hints for you. Finally a warning: All the code was written without thorough testing. There might be bugs.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T20:13:57.133", "Id": "225434", "ParentId": "225403", "Score": "3" } } ]
{ "AcceptedAnswerId": "225434", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T09:12:16.623", "Id": "225403", "Score": "4", "Tags": [ "php", "html", "sql", "mysqli" ], "Title": "Demotion/Promotion Script" }
225403
<p>I wrote a little Shoutbox System which is working fine, but I want to know if there is something I can improve about this code.</p> <p>Here is my Shoutbox Overlay:</p> <pre><code>&lt;div class="article_body" id="article_body" name="article_body"&gt; &lt;?php require('./tools/php/connector/connector.php'); $query = "SELECT * FROM `shoutbox` ORDER BY entryid DESC LIMIT 5"; $stmt = $db-&gt;prepare($query); $stmt-&gt;execute(); $result = $stmt-&gt;get_result(); $stmt-&gt;close(); while($obj = $result-&gt;fetch_object()) { if ($obj != null || !empty($obj)) { echo(" &lt;p style='font-size: 14px;'&gt; $obj-&gt;text &lt;/p&gt; &lt;table style='width: 100%; font-size: 11px;'&gt; &lt;tr&gt; &lt;td style='text-align: start;'&gt; Von: &lt;a style='font-size: 11px'; href='?".$obj-&gt;user."'&gt;".$obj-&gt;user." &lt;/td&gt; &lt;td style='text-align: end;'&gt; Am: ".$obj-&gt;date_time." &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;hr&gt; "); } else { echo("&lt;center&gt;Shout-Box is empty&lt;/center&gt;"); } } if ($_SESSION['besucht'] == 1 &amp;&amp; $_SESSION['user-ban-status'] - 1 == 0) { echo("&lt;form action='./tools/php/shoutbox/shoutbox.php' method='POST'&gt; &lt;input type='text' name='shout' maxlength='500' style='width: 186px;'&gt;&lt;button&gt;Senden&lt;/button&gt; &lt;/fomr"); } if ($_SESSION['besucht'] == 1 &amp;&amp; $_SESSION['user-ban-status'] - 1 == 1) { echo("&lt;h5 style='color: red;'&gt;You Are Banned. This Function Isn't Allowed For Banned Members.&lt;/h5&gt;"); } mysqli_close($db); ?&gt; &lt;/div&gt; </code></pre> <p>The $_SESSION['besucht'] is for the Visited and logged in check. The $_SESSION['user-ban-status'] is to check if the user is banned and if that is <code>true</code> the post function is disabled. I limited the View per to the latest 5 entrys in my database so only the newest thing would be shown.</p> <p>Here is my Backend Script for the input of the Shoutbox:</p> <pre><code>&lt;?php if (!empty($_POST['shout']) || $_POST['shout'] != null) { session_start(); if (!empty($_SESSION['user-username']) || $_SESSION['user-username'] != null) { require('../connector/connector.php'); $text = $_POST['shout']; $user = $_SESSION['user-username']; date_default_timezone_set("Europe/Berlin"); $timestamp = time(); $datum = date("Y-m-d H:i:s",$timestamp); echo($text."&lt;br&gt;"); echo($user."&lt;br&gt;"); echo($datum."&lt;br&gt;"); $stmt = $db-&gt;prepare("INSERT INTO `shoutbox`(`text`, `user`, `date_time`) VALUES (?,?,?)"); $stmt-&gt;bind_param('sss', $text, $user, $datum); $stmt-&gt;execute(); mysqli_close($db); header("Location: ../"); exit; } else { header("Location: ../"); exit; } } else { header("Location: ../"); exit; } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T12:16:03.927", "Id": "437661", "Score": "2", "body": "Hey, welcome to Code Review! Here we review working code and try to make it better. What we cannot do is solve your problem for you or make your code do new things. Have a look at our [help/dont-ask] for more information." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T12:20:51.363", "Id": "437662", "Score": "0", "body": "My code works. I'm just asking for a suggestion for a hint or a recommendation for this code. If you do something like that you can also ask if someone has an idea for their own idea xD I don't think that will be a shame or against the \"rules\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T12:22:48.477", "Id": "437663", "Score": "1", "body": "From your question it sounds like what you are asking is for us to implement a new feature: \"So I mean how can I add numbers for Pages for the useres to swipe forward and backward to the discussions in the Shoutbox?\" If your code cannot currently do this, it is off-topic to ask about here. What you can ask about instead is, describe what your code *does* do and how that could be done in a better way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T12:26:30.940", "Id": "437664", "Score": "0", "body": "Is taht better? xD" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T21:01:35.143", "Id": "437863", "Score": "0", "body": "I believe this question has been edited to be on-topic, so I have voted to reopen." } ]
[ { "body": "<ul>\n<li><p>I recommend writing <code>session_start();</code> first and unconditionally.</p></li>\n<li><p><code>!empty()</code> performs two checks: if the variable <code>isset()</code> AND contains a non-falsey value. This means <code>$obj != null</code> is not necessary. That said, your <code>while()</code> loop will halt if <code>$obj</code> is falsey.</p></li>\n<li><p>There's nothing wrong with using prepared statements, but for the record your first query will be just as stable/secure without it.</p></li>\n<li><p>I noticed <code>mysqli_close($db);</code>. You should keep all of your query syntax object-oriented.</p></li>\n<li><p>Rather than declaring new variables to feed to <code>$stmt-&gt;bind_param()</code> (single-use variables), just write the original variables as parameters. There isn't much benefit in adding more variables to global scope.</p></li>\n<li><p>It looks like all roads lead to: </p>\n\n<pre><code>header(\"Location: ../\");\n</code></pre>\n\n<p>If this is true for you actual project script, write a single <code>if</code> block, then whether its contents are executed or not, after the condition block execute your redirect.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T06:13:26.860", "Id": "225445", "ParentId": "225407", "Score": "2" } }, { "body": "<ul>\n<li>Don't mix database logic and display logic (HTML). Prepare the data first and then display it in HTML when you have everything ready.</li>\n<li>Try to avoid mysqli in new projects. Use PDO whenever possible. If you must use mysqli then stick to the object-oriented style.</li>\n<li>Don't close connection object or the statement. PHP will do that for you and you avoid mistakes by not doing it manually.</li>\n<li>Don't use <code>date()</code> and <code>time()</code> functions. Use <code>DateTime</code> class.</li>\n<li>Don't put parentheses after <code>echo</code>. It's not a function and these parentheses are extremely confusing. Same applies to <code>require</code></li>\n<li>Reduce cyclomatic complexity by performing inverse checks. <code>exit</code> will kill the script so you can use that to finish early without wrapping whole code blocks in braces.</li>\n<li>Use strict comparison (<code>===</code>).</li>\n<li>Use <code>htmlspecialchars()</code> to avoid XSS.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T14:56:52.127", "Id": "269135", "ParentId": "225407", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T10:39:26.567", "Id": "225407", "Score": "2", "Tags": [ "php", "mysql", "mysqli" ], "Title": "Shoutbox system" }
225407
<p>I created my own <a href="https://en.wikipedia.org/wiki/Approximate_Bayesian_computation" rel="nofollow noreferrer">Approximate Bayesian computation</a> algorithm in Python 3 and I try to find the best hyper-parameters for it but it is really slow. <em>This question is not about the math involved in it. For that, you can read <a href="https://stats.stackexchange.com/questions/419831/how-to-use-approximate-bayesian-computation-to-estimate-the-parameters-of-a-func">my other question on Cross Validated</a>.</em></p> <p>The objective of the ABC algorithm is to find the best distribution for the parameters of a model by using a Bayesian approach. To do that, I create a dataset with the <em>real</em> parameters of my model and I try to find all the values of <span class="math-container">\$a\$</span> and <span class="math-container">\$b\$</span> that produce the same outcome. Then, I use those new values of <span class="math-container">\$a\$</span> and <span class="math-container">\$b\$</span> to create my posterior distribution.</p> <p>The purpose of my piece of code is to find the hyper-parameters <span class="math-container">\$k\$</span> and <span class="math-container">\$n\$</span> who give me the best compromise between precision and time of execution. The <span class="math-container">\$k\$</span> parameter corresponds to the size of the dataset I generate at each step and the <span class="math-container">\$n\$</span> parameter corresponds to the number of points I generate from my prior distribution.</p> <p>For those two hyper-parameters, the higher the better but I want to check if increasing one of them has a big enough impact on the standard deviation of the parameter of my model.</p> <p>So, here is my question: what can I do to improve the speed of my algorithm?</p> <pre><code>import numpy as np from scipy.stats import norm from scipy.stats import uniform from scipy.stats import lognorm from scipy.stats import gaussian_kde import matplotlib.pyplot as plt # Because I want to find the best hyper-parameters for my model, # I will create a dataset with fixed parameters real_a = 0.9 real_b = -0.02 # Make m steps for each set of hyper-parameters m = 100 # Return the probability that a Bernoulli trial will success def gen_model(a, b, odd): prob = a / odd + b prob = 0.0 if prob &lt; 0.0 else prob prob = 1.0 if prob &gt; 1.0 else prob return prob def bernoulli_trial(p): return np.random.rand() &lt;= p # Return the outcome of a Bernoulli trial with the fixed parameters def real_exp(odd): return bernoulli_trial(gen_model(real_a, real_b, odd)) # k is one of my hyper-parameters. It represents the number of rows of my dataset for k in range(5,11): # n = 10 ** p is the second hyper-parameter. It represents the number of tuples (a,b) I generate for each run for p in range(5,8): n = 10 ** p # Three results for each hyper-parameters tuple for l in range(3): # The first time, I pick the parameters from a normal distribution first = True posterior = None last_a_mean = 1.0 last_a_std = 0.0 last_b_mean = 0.0 last_b_std = 0.0 for run in range(m): selected_parameters = [[], []] # Accept the parameters only if at least 100 are non-rejected while(len(selected_parameters[0]) &lt; 100): current_loop_odd = [] current_loop_result = [] for idx in range(k): # Creation of my dataset current_loop_odd.append(1 / uniform.rvs(0.01, 0.99)) current_loop_result.append(real_exp(current_loop_odd[idx])) for loop in range(n): add_selected_parameters = True if first: # My prior is a and b are independent and follow a normal distribution (mean of 1 for a and mean of 0 for b) a = norm.rvs(1.0,0.1) b = norm.rvs(0.0,0.1) else: # For the next steps, I use datapoints generated from my posterior distribution a = points[0][loop] b = points[1][loop] for idx in range(k): if bernoulli_trial(gen_model(a, b, current_loop_odd[idx])) != current_loop_result[idx]: add_selected_parameters = False # The tuple is rejected because it doesn't correspond to my dataset if add_selected_parameters: selected_parameters[0].append(a) selected_parameters[1].append(b) posterior = gaussian_kde(selected_parameters) # I generate a new posterior distribution from my non-rejected tuples points = posterior.resample(n) # And I create new datapoints for the next step first = False last_a_mean = np.mean(selected_parameters[0]) last_a_std = np.std(selected_parameters[0]) last_b_mean = np.mean(selected_parameters[1]) last_b_std = np.std(selected_parameters[1]) # Print the result print(str(k) + " - " + str(n) + " : (" + str(l) + ") -&gt; " + str(last_a_mean) + " , " + str(last_a_std) + " / " + str(last_a_mean) + " , " + str(last_a_std)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T12:54:19.600", "Id": "437669", "Score": "0", "body": "Explain at the top, specific requests at the top, code at the bottom." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T12:56:10.093", "Id": "437670", "Score": "0", "body": "A style note: Comments in code are generally incomplete - you could stick a noun in front of them, and it would work: `# make m steps for each set of hyper-parameters` however this suggestion does not qualify for an answer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T13:52:22.753", "Id": "437679", "Score": "0", "body": "@FreezePhoenix I put the code at the end of the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T13:36:49.580", "Id": "437799", "Score": "0", "body": "A general code-review.se rule: When someone suggests a change specific to the code, such as I did in my second comment, you don't edit your question. And when someone answers a question, you still don't edit it. This is to keep answers from having to change as comments are added to the post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-04T08:11:56.747", "Id": "437882", "Score": "0", "body": "@FreezePhoenix I'm OK with what you say about changing the question after an answer but I didn't have any answer to my question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-04T13:04:47.840", "Id": "437903", "Score": "0", "body": "You edited it after I suggested a change to your code. That is discouraged here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-04T13:32:44.393", "Id": "437907", "Score": "0", "body": "@FreezePhoenix Okay, sorry, I didn't see that in the FAQ. What should I have done after reading your comment, so?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-05T13:39:40.507", "Id": "438038", "Score": "0", "body": "> \"A style note\" You should just note it, and if you write a second question with your improved code, or once you apply answers to your code, take into consideration the notes people have left." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T12:31:57.200", "Id": "225409", "Score": "1", "Tags": [ "python", "performance", "beginner", "python-3.x", "reinventing-the-wheel" ], "Title": "Determine the hyper-parameters of an Approximate Bayesian computation" }
225409
<p>I just picked up Rust recently and this is my first program (longer than 10 lines at least) so I'm looking for constructs that are more native and natural to Rust. I come from a c++/ python background. If there are some more compile-time optimizations that would also be nice since I am interested in zero overhead abstractions.</p> <pre class="lang-rust prettyprint-override"><code>use std::fs::File; use std::io::Write; use std::cmp; const SCALING_FACTOR: f64 = 1.4 as f64; #[derive(Clone)] struct RGB { red: u8, green: u8, blue: u8 } fn serialize_rgb(pixels: &amp;Vec&lt;RGB&gt;, size: usize) -&gt; Vec&lt;u8&gt; { // for saving to a file. Is there any way we could do this // without constructing a new array? Would be much faster let mut output: Vec&lt;u8&gt; = Vec::with_capacity(size * 3); for pix in pixels { output.push(pix.red); output.push(pix.green); output.push(pix.blue); } output } struct Canvas { // Using 1D array so the bytes are together in memory, should be more efficient than Vec&lt;Vec&gt; // since that would store pointers to vectors? pixels: Vec&lt;RGB&gt;, width: i32, height: i32 } impl Canvas { fn set_colour(&amp;mut self, x: i32, y: i32, colour: &amp;RGB) { // make this more natural? In C++ you can overload () to get a functor if x &gt; 0 &amp;&amp; y &gt; 0 &amp;&amp; x &lt; self.width &amp;&amp; y &lt; self.height { self.pixels[(self.width * y + x) as usize] = colour.clone(); } } fn write_to_file(&amp;mut self, filename: &amp;str) { let mut file = init_ppm(filename, self.width, self.height); file.write_all(&amp;serialize_rgb(&amp;self.pixels, (self.width * self.height) as usize)).expect("error"); /* slow for pixel in &amp;self.pixels { file.write_all(&amp;[pixel.red, pixel.green, pixel.blue]).expect("error writing to a file"); }*/ } fn new(width: i32, height: i32) -&gt; Canvas { Canvas { width, height, pixels: vec![RGB{red:0, green:0, blue:0}; (width * height) as usize] } } fn draw_square(&amp;mut self, center: &amp;Point, width: i32, colour: &amp;RGB) { for y in cmp::max(0, center.y - width) .. cmp::min(self.height, center.y + width) { for x in cmp::max(0, center.x - width) .. cmp::min(self.width, center.x + width) { self.set_colour(x ,y, &amp;colour); } } } fn draw_line(&amp;mut self, from: &amp;Point, to: &amp;Point, width: i32, colour: &amp;RGB) { // function that connects two points on the grid with a line if from.x == to.x { // vertical lines let startx = cmp::max(from.x - width, 0); let endx = cmp::min(from.x + width, self.width); let endy = cmp::max(from.y, to.y) + 1; let starty = cmp::min(from.y, to.y); for y in starty .. endy { for x in startx .. endx { self.set_colour(x, y, colour); } } } else { let k = (to.y - from.y) as f64 / (to.x - from.x) as f64; let n = to.y as f64 - k * to.x as f64; let lower = cmp::min(from.x, to.x); let upper = cmp::max(from.x, to.x) + 1; for x in lower .. upper { // We colour y's as a function of x's self.draw_square( &amp;Point {x: x, y: (k * x as f64 + n) as i32}, width, colour ); } if k.abs() &gt; 1.0 { // for steep lines, we also have to consider x as a function of y to get good results let lower = cmp::min(from.y, to.y); let upper = cmp::max(from.y, to.y) + 1; for y in lower .. upper { self.draw_square( &amp;Point {x: ((y as f64 - n) / k) as i32, y: y}, width, colour ); } } } } } fn rotate_point(center: &amp;Point, point: &amp;Point, angle: f64) -&gt; Point { // also scales down a bit let (sin, cos) = angle.sin_cos(); let translated = Point {x: ((point.x - center.x) as f64 / SCALING_FACTOR) as i32, y: ((point.y - center.y) as f64 / SCALING_FACTOR) as i32}; let rotated = Point {x: (translated.x as f64 * cos - translated.y as f64 * sin) as i32, y: (translated.x as f64 * sin + translated.y as f64 * cos) as i32 }; Point {x: rotated.x + center.x, y: rotated.y + center.y} } fn init_ppm(filename: &amp;str, width: i32, height: i32) -&gt; File { let mut file = File::create(format!("{}.ppm",filename)).expect("couldn't create"); file.write_all(format!("P6 {} {} 255 ", width, height).as_bytes()).expect("error writing to a file"); file } struct Point { x: i32, y: i32 } fn main() { const WIDTH: i32 = 1500; const HEIGHT: i32 = 1500; let mut picture = Canvas::new(WIDTH, HEIGHT); draw_tree(&amp;mut picture, &amp;Point {x: WIDTH/2, y: HEIGHT}, &amp;Point {x: WIDTH/2, y: 3*HEIGHT/4}, 15, &amp;RGB {red: 255, blue: 255, green: 255}, 0.6, 2); picture.write_to_file("test"); } fn draw_tree(mut canvas: &amp;mut Canvas, prev: &amp;Point, next: &amp;Point, iter: i32, colour: &amp;RGB, angle: f64, branches: i32) { // recursively generates branches. if iter == 0 { return; } canvas.draw_line(prev, next, 1, colour); let prev = Point {x: 2 * next.x - prev.x, y: 2 * next.y - prev.y}; if branches % 2 == 1 { draw_tree(&amp;mut canvas, &amp;next, &amp;rotate_point(next, &amp;prev, 0.0), iter - 1, colour, angle, branches); } for i in 1 .. branches / 2 + 1 { // colours are hardcoded currently but that's not really important let rot_left = rotate_point(next, &amp;prev, i as f64 * angle); draw_tree(&amp;mut canvas, &amp;next, &amp;rot_left, iter - 1, &amp;RGB{red: 247, green: 97, blue: 74}, angle, branches); let rot_right = rotate_point(next, &amp;prev, - i as f64 * angle); draw_tree(&amp;mut canvas, &amp;next, &amp;rot_right, iter - 1, &amp;RGB{red: 26, green: 121, blue: 244}, angle, branches); } } </code></pre> <p>End result of the code is a .ppm image file <code>test.ppm</code> that looks <a href="https://i.stack.imgur.com/BhAwr.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BhAwr.jpg" alt="binary tree image"></a> like this (depending on how you set the settings in main and SCALING_FACTOR)</p>
[]
[ { "body": "<p>This was great work, especially for a first project. \nI made a bunch of changes and tried to comment my reasoning where things stood out. Here's a few things to note:</p>\n\n<ul>\n<li>Your code was at the size where you could go either way, but I decided to split it up into modules.</li>\n<li>I made <code>Point</code> and <code>Rgb</code> implement <code>Copy</code> since they are just very small collections of numbers. Now you can have functions take those by value, rather than reference.</li>\n<li>I store the color data as bytes rather than <code>Rgb</code>s, which lets you write that data directly to the ppm. Another possible way to do it is to use <code>unsafe</code> to change a <code>&amp;[Rgb]</code> into a <code>&amp;[u8]</code>, but it's trickier and you have to be very careful.</li>\n<li>You should generally try to use <code>usize</code> when describing the size of something.</li>\n<li>Make it a goal to have doc comments on at least everything public. You can add <code>#![warn(missing_docs)]</code> to the top of <code>main.rs</code> to help you with this.</li>\n<li>Check out the tools <code>rustfmt</code> and <code>clippy</code>.</li>\n</ul>\n\n<p><code>main.rs</code></p>\n\n<pre><code>mod canvas;\nmod point;\nmod rgb;\n\npub use canvas::Canvas;\npub use point::Point;\npub use rgb::Rgb;\n\nfn main() {\n const WIDTH: usize = 1500;\n const HEIGHT: usize = 1500;\n\n let mut picture = Canvas::new(WIDTH, HEIGHT);\n\n draw_tree(\n &amp;mut picture,\n Point {\n x: WIDTH as i32 / 2,\n y: HEIGHT as i32,\n },\n Point {\n x: WIDTH as i32 / 2,\n y: 3 * HEIGHT as i32 / 4,\n },\n 15,\n Rgb::WHITE,\n 0.6,\n 2,\n );\n\n if let Err(e) = picture.save(\"test\".as_ref()) {\n eprintln!(\"Error saving image: {}\", e);\n // Lets the caller know that our program failed.\n std::process::exit(1);\n }\n}\n\nfn draw_tree(\n canvas: &amp;mut Canvas,\n prev: Point,\n next: Point,\n iter: i32,\n colour: Rgb,\n angle: f64,\n branches: usize,\n) {\n if iter == 0 {\n return;\n }\n canvas.draw_line(prev, next, 1, colour);\n let prev = Point {\n x: 2 * next.x - prev.x,\n y: 2 * next.y - prev.y,\n };\n\n if branches % 2 == 1 {\n let straight = next.rotate_and_scale(prev, 0.0);\n draw_tree(canvas, next, straight, iter - 1, colour, angle, branches);\n }\n\n for i in 1..=branches / 2 {\n let left = next.rotate_and_scale(prev, i as f64 * angle);\n draw_tree(canvas, next, left, iter - 1, Rgb::LEFT, angle, branches);\n\n let right = next.rotate_and_scale(prev, -(i as f64) * angle);\n draw_tree(canvas, next, right, iter - 1, Rgb::RIGHT, angle, branches);\n }\n}\n</code></pre>\n\n<p><code>canvas.rs</code></p>\n\n<pre><code>use std::{cmp, fs::File, io::Write, path::Path};\n\nuse crate::{Point, Rgb};\n\n#[derive(Clone, Debug)]\npub struct Canvas {\n // Since we don't need to resize data, we can store a boxed slice, which will prevent us from\n // accidently pushing, poping, resizing, etc since those are Vec methods.\n // We can store the bytes rather than the colors, which makes writing it easier.\n data: Box&lt;[u8]&gt;,\n // Use usize or at least an unsigned type whereever it makes sense to do so, such as a size or\n // count. I would've changed more things to unsigned, but some of your logic depends on signed.\n width: usize,\n height: usize,\n}\n\nimpl Canvas {\n pub fn set_colour(&amp;mut self, x: usize, y: usize, colour: Rgb) {\n // Using usize for parameters, we don't have to check against negative.\n if x &lt; self.width &amp;&amp; y &lt; self.height {\n // Make sure to multiply by 3 here to account for directly storing the bytes...\n let offset = (self.width * y + x) * std::mem::size_of::&lt;Rgb&gt;();\n self.data[offset] = colour.red;\n self.data[offset + 1] = colour.green;\n self.data[offset + 2] = colour.blue;\n }\n }\n\n // Rather than panicing, we should return a Result, especially since it is easy because all\n // operations return io::Result.\n // Using a Path for the filename is more precise.\n pub fn save(&amp;mut self, filename: &amp;Path) -&gt; std::io::Result&lt;()&gt; {\n let mut file = File::create(filename.with_extension(\"ppm\"))?;\n\n write!(file, \"P6 {} {} 255 \", self.width, self.height)?;\n file.write_all(&amp;self.data)?;\n\n Ok(())\n }\n\n pub fn new(width: usize, height: usize) -&gt; Canvas {\n Canvas {\n width,\n height,\n data: vec![0; width * height * std::mem::size_of::&lt;Rgb&gt;()].into_boxed_slice(),\n }\n }\n\n // I didn't look much at draw_square or draw_line...\n pub fn draw_square(&amp;mut self, center: Point, width: i32, colour: Rgb) {\n for y in cmp::max(0, center.y - width)..cmp::min(self.height as i32, center.y + width) {\n for x in cmp::max(0, center.x - width)..cmp::min(self.width as i32, center.x + width) {\n self.set_colour(x as usize, y as usize, colour);\n }\n }\n }\n\n pub fn draw_line(&amp;mut self, from: Point, to: Point, width: i32, colour: Rgb) {\n if from.x == to.x {\n let startx = cmp::max(from.x - width, 0);\n let endx = cmp::min(from.x + width, self.width as i32);\n let endy = cmp::max(from.y, to.y) + 1;\n let starty = cmp::min(from.y, to.y);\n for y in starty..endy {\n for x in startx..endx {\n self.set_colour(x as usize, y as usize, colour);\n }\n }\n } else {\n let k = f64::from(to.y - from.y) / f64::from(to.x - from.x);\n let n = f64::from(to.y) - k * f64::from(to.x);\n let lower = cmp::min(from.x, to.x);\n let upper = cmp::max(from.x, to.x) + 1;\n for x in lower..upper {\n self.draw_square(\n Point {\n x,\n y: (k * f64::from(x) + n) as i32,\n },\n width,\n colour,\n );\n }\n if k.abs() &gt; 1.0 {\n let lower = cmp::min(from.y, to.y);\n let upper = cmp::max(from.y, to.y) + 1;\n for y in lower..upper {\n self.draw_square(\n Point {\n x: ((f64::from(y) - n) / k) as i32,\n y,\n },\n width,\n colour,\n );\n }\n }\n }\n }\n}\n</code></pre>\n\n<p><code>point.rs</code></p>\n\n<pre><code>const SCALING_FACTOR: f64 = 1.4 as f64;\n\n#[derive(Copy, Clone, Debug)]\npub struct Point {\n pub x: i32,\n pub y: i32,\n}\n\nimpl Point {\n /// Rotates a point around self by the given angle, and scales it down.\n pub fn rotate_and_scale(self, point: Point, angle: f64) -&gt; Point {\n // also scales down a bit\n let (sin, cos) = angle.sin_cos();\n let translated = Point {\n x: ((point.x - self.x) as f64 / SCALING_FACTOR) as i32,\n y: ((point.y - self.y) as f64 / SCALING_FACTOR) as i32,\n };\n let rotated = Point {\n x: (translated.x as f64 * cos - translated.y as f64 * sin) as i32,\n y: (translated.x as f64 * sin + translated.y as f64 * cos) as i32,\n };\n Point {\n x: rotated.x + self.x,\n y: rotated.y + self.y,\n }\n }\n}\n</code></pre>\n\n<p><code>rgb.rs</code></p>\n\n<pre><code>#[derive(Copy, Clone, Debug)]\npub struct Rgb {\n pub red: u8,\n pub green: u8,\n pub blue: u8,\n}\n\nimpl Rgb {\n // Makes it a little nicer to create colors, IMO.\n pub const fn new(red: u8, green: u8, blue: u8) -&gt; Self {\n Self { red, green, blue }\n }\n\n pub const WHITE: Self = Self::new(255, 255, 255);\n pub const LEFT: Self = Self::new(247, 97, 74);\n pub const RIGHT: Self = Self::new(26, 121, 244);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-05T20:22:23.913", "Id": "225607", "ParentId": "225410", "Score": "1" } } ]
{ "AcceptedAnswerId": "225607", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T12:32:12.583", "Id": "225410", "Score": "5", "Tags": [ "beginner", "image", "rust", "graphics", "fractals" ], "Title": "Rust code of a tree fractal" }
225410
<p>A few days ago I began to work on my first project that's bigger than any others that I've attempted before. The purpose of this was to learn how to better code using OOP techniques. The code is all in one Main class (<a href="https://github.com/ViceroyFaust/JavaEnigma/" rel="nofollow noreferrer">https://github.com/ViceroyFaust/JavaEnigma/</a>):</p> <pre class="lang-java prettyprint-override"><code>package owl; import java.io.BufferedReader; import java.io.FileReader; import java.net.URL; public class Main { // Rotors I II III of the Enigma I model and Reflector B private static final String ABC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private static final String I = "EKMFLGDQVZNTOWYHXUSPAIBRCJ"; private static final String II = "AJDKSIRUXBLHWTMCQGZNPYFVOE"; private static final String III = "BDFHJLCPRTXVZNYEIWGAKMUSQO"; private static final String ReflectorB = "YRUHQSLDPXNGOKMIEBFZCWVJAT"; private static int leftPosition = 0; private static int midPosition = 0; private static int rightPosition = 0; private static int ringL = 0; private static int ringM = 0; private static int ringR = 0; private static URL url = Main.class.getResource("Message.txt"); public static void main(String[] args) { try { FileReader fr = new FileReader(url.getPath()); BufferedReader reader = new BufferedReader(fr); String ringstellung = reader.readLine(); String position = reader.readLine(); String message = reader.readLine(); setRing(ringstellung); setPosition(position); System.out.println(encrypt(message)); reader.close(); } catch (Exception e) { e.printStackTrace(); } } private static void setRing(String ringstellung) { ringL = ringstellung.charAt(0) - 65; ringM = ringstellung.charAt(1) - 65; ringR = ringstellung.charAt(2) - 65; } private static void setPosition(String position) { leftPosition = position.charAt(0) - 65; midPosition = position.charAt(1) - 65; rightPosition = position.charAt(2) - 65; } private static StringBuilder encrypt(String message) { StringBuilder output = new StringBuilder(); for (int messageIndex = 0; messageIndex &lt; message.length(); messageIndex++) { char c = message.charAt(messageIndex); if (c == ' ') { output.append(' '); continue; } int indexABC = 0; rightPosition++; // right most rotor turns if (rightPosition == 22) { // if V turns, rotor II turns midPosition++; if (midPosition == 5) { // if E turns, rotor I is turned leftPosition++; } } if (rightPosition &gt; 26) { rightPosition -= 26; } if (midPosition &gt; 26) { midPosition -= 26; } if (leftPosition &gt; 26) { leftPosition -= 26; } // System.out.printf("%c %c %c%n", ABC.charAt(leftPosition), // ABC.charAt(midPosition), ABC.charAt(rightPosition)); // System.out.printf("%c %c %c%n%n", ABC.charAt(ringL), ABC.charAt(ringM), // ABC.charAt(ringR)); // right rotor encryption for (int foo = 0; foo &lt; 26; foo++) { if (ABC.charAt(foo) == c) { indexABC = foo + rightPosition - ringR; if (indexABC &gt; 25) { indexABC -= 26; } if (indexABC &lt; 0) { indexABC += 26; } break; } } c = III.charAt(indexABC); for (int foo = 0; foo &lt; 26; foo++) { if (ABC.charAt(foo) == c) { indexABC = foo - rightPosition + ringR; if (indexABC &gt; 25) { indexABC -= 26; } if (indexABC &lt; 0) { indexABC += 26; } break; } } c = ABC.charAt(indexABC); // System.out.println(c); // middle rotor encryption for (int foo = 0; foo &lt; 26; foo++) { if (ABC.charAt(foo) == c) { indexABC = foo + midPosition - ringM; if (indexABC &gt; 25) { indexABC -= 26; } if (indexABC &lt; 0) { indexABC += 26; } break; } } c = II.charAt(indexABC); for (int foo = 0; foo &lt; 26; foo++) { if (ABC.charAt(foo) == c) { indexABC = foo - midPosition + ringM; if (indexABC &gt; 25) { indexABC -= 26; } if (indexABC &lt; 0) { indexABC += 26; } break; } } c = ABC.charAt(indexABC); // System.out.println(c); // left rotor encryption for (int foo = 0; foo &lt; 26; foo++) { if (ABC.charAt(foo) == c) { indexABC = foo + leftPosition - ringL; if (indexABC &gt; 25) { indexABC -= 26; } if (indexABC &lt; 0) { indexABC += 26; } break; } } c = I.charAt(indexABC); for (int foo = 0; foo &lt; 26; foo++) { if (ABC.charAt(foo) == c) { indexABC = foo - leftPosition + ringL; if (indexABC &gt; 25) { indexABC -= 26; } if (indexABC &lt; 0) { indexABC += 26; } break; } } c = ABC.charAt(indexABC); // System.out.println(c + "\n"); // reflector c = ReflectorB.charAt(indexABC); // System.out.println(c + "\n"); // Reflected Left Rotor for (int foo = 0; foo &lt; 26; foo++) { if (ABC.charAt(foo) == c) { indexABC = foo + leftPosition - ringL; if (indexABC &gt; 25) { indexABC -= 26; } if (indexABC &lt; 0) { indexABC += 26; } break; } } c = ABC.charAt(indexABC); for (int foo = 0; foo &lt; 26; foo++) { if (I.charAt(foo) == c) { indexABC = foo - leftPosition + ringL; if (indexABC &gt; 25) { indexABC -= 26; } if (indexABC &lt; 0) { indexABC += 26; } break; } } c = ABC.charAt(indexABC); // System.out.println(c); // Reflected Middle Rotor for (int foo = 0; foo &lt; 26; foo++) { if (ABC.charAt(foo) == c) { indexABC = foo + midPosition - ringM; if (indexABC &gt; 25) { indexABC -= 26; } if (indexABC &lt; 0) { indexABC += 26; } break; } } c = ABC.charAt(indexABC); for (int foo = 0; foo &lt; 26; foo++) { if (II.charAt(foo) == c) { indexABC = foo - midPosition + ringM; if (indexABC &gt; 25) { indexABC -= 26; } if (indexABC &lt; 0) { indexABC += 26; } break; } } c = ABC.charAt(indexABC); // System.out.println(c); // Reflected Right Rotor for (int foo = 0; foo &lt; 26; foo++) { if (ABC.charAt(foo) == c) { indexABC = foo + rightPosition - ringR; if (indexABC &gt; 25) { indexABC -= 26; } if (indexABC &lt; 0) { indexABC += 26; } break; } } c = ABC.charAt(indexABC); for (int foo = 0; foo &lt; 26; foo++) { if (III.charAt(foo) == c) { indexABC = foo - rightPosition + ringR; if (indexABC &gt; 25) { indexABC -= 26; } if (indexABC &lt; 0) { indexABC += 26; } break; } } c = ABC.charAt(indexABC); output.append(c); // System.out.println(c); } return output; } } </code></pre> <p>And the input is the following:</p> <pre><code>ABC XYZ ALPHA DELTA CHARLIE </code></pre> <p>The code works and all of the output is correct. You can set any of the settings on the rotors, such as the Ring Settings and the Initial Position. I have not yet added the feature of the Plugboard, because I want to organise my code before I add any big features.</p> <p>So, the question is, how can I reorgise the code in order to make it follow the OOP structure better, and whate are some general things which will help me to program better in the future?</p>
[]
[ { "body": "<p>This won't be a complete answer, but without getting into OOP you should see that there's A LOT of duplicated code. You can rewrite your for cycles in a method operating on just the changing parts. </p>\n\n<pre><code>private static int rotate(final char c, int indexABCShift, final String characters){\n int indexABC = 0;\n for (int foo = 0; foo &lt; 26; foo++) {\n if (characters.charAt(foo) == c) {\n indexABC = foo + indexABCShift;\n if (indexABC &gt; 25) {\n indexABC -= 26;\n }\n if (indexABC &lt; 0) {\n indexABC += 26;\n }\n break;\n }\n }\n return indexABC;\n}\n\nprivate static StringBuilder encrypt(String message) {\n StringBuilder output = new StringBuilder();\n for (int messageIndex = 0; messageIndex &lt; message.length(); messageIndex++) {\n char c = message.charAt(messageIndex);\n if (c == ' ') {\n output.append(' ');\n continue;\n }\n int indexABC = 0;\n rightPosition++; // right most rotor turns\n if (rightPosition == 22) { // if V turns, rotor II turns\n midPosition++;\n if (midPosition == 5) { // if E turns, rotor I is turned\n leftPosition++;\n }\n }\n if (rightPosition &gt; 26) {\n rightPosition -= 26;\n }\n if (midPosition &gt; 26) {\n midPosition -= 26;\n }\n if (leftPosition &gt; 26) {\n leftPosition -= 26;\n }\n\n indexABC = rotate(c, rightPosition - ringR, ABC);\n c = III.charAt(indexABC);\n indexABC = rotate(c, - rightPosition + ringR, ABC);\n c = ABC.charAt(indexABC);\n indexABC = rotate(c, + midPosition - ringM, ABC);\n c = II.charAt(indexABC);\n indexABC = rotate(c, - midPosition + ringM, ABC);\n c = ABC.charAt(indexABC);\n indexABC = rotate(c, + leftPosition - ringL, ABC);\n c = I.charAt(indexABC);\n indexABC = rotate(c, - leftPosition + ringL, ABC);\n // reflector\n c = ReflectorB.charAt(indexABC);\n indexABC = rotate(c, + leftPosition - ringL, ABC);\n c = ABC.charAt(indexABC);\n indexABC = rotate(c, - leftPosition + ringL, I);\n c = ABC.charAt(indexABC);\n // Reflected Middle Rotor\n indexABC = rotate(c, + midPosition - ringM, ABC);\n c = ABC.charAt(indexABC);\n indexABC = rotate(c, - midPosition + ringM, II);\n c = ABC.charAt(indexABC);\n indexABC = rotate(c, + rightPosition - ringR, ABC);\n c = ABC.charAt(indexABC);\n indexABC = rotate(c, - rightPosition + ringR, III);\n c = ABC.charAt(indexABC);\n output.append(c);\n }\n return output;\n}\n</code></pre>\n\n<p>This alone will save you 150 lines. That's one of the main programming good habits - Don't Repeat Yourself. I cannot offer some OOP solution to the problem without really understanding the enigma, but you should start with splitting the code into smaller methods and keep the variables local inside the methods as much as possible. For example the ring positions don't need to be static variables - you can compute them in the main and pass them to the encrypt function. Also you can split the encrypt by separating iteration over the input string and encrypting single letter.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T01:07:36.887", "Id": "437724", "Score": "0", "body": "The line calling the rotate method right before the reflector throws the code off, which messes up the entire encryption. For some reason, the reflector relies on that one specific loop within the encrypt();." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T01:17:03.457", "Id": "437725", "Score": "0", "body": "Okay, I figured it out. The output for the last letter on the Rotor before the Reflector is useless, because the location of the letter is used for the reflector, and not the letter itself." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T14:57:37.830", "Id": "225416", "ParentId": "225412", "Score": "4" } } ]
{ "AcceptedAnswerId": "225416", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T13:05:23.253", "Id": "225412", "Score": "4", "Tags": [ "java", "beginner", "enigma-machine" ], "Title": "The Enigma Machine (CLI) in Java" }
225412
<p>In C++, currently we have few possibilities to work with strings:</p> <ol> <li><p>by using plain old C-strings - unfortunately, we have penalty for getting length of string each time, and we should manually control life time of array, which actually contains data...</p></li> <li><p>we can use <code>std::string</code>, but again, unfortunately this is not very efficient class: it's relatively large (32 bytes on 64-bit platform) and it always copies data;</p></li> <li><p>modern C++ gives new opportunity: <code>std::string_view</code> class, which is quite effective, but unfortunately it doesn't own strings, on which it references: again we should control life time of the containers in which strings really stored.</p></li> </ol> <p>In Java or C# we have more reasonable solution, when class implementing strings divided on two:</p> <ul> <li><p><code>StringBuilder</code> which behaves like <code>std::string</code> and can be used to construct and edit strings;</p></li> <li><p><code>String</code> which is lightweight and always read-only, and can be used to access previously created strings -- this class can be stored in arrays, passed in functions, etc...</p></li> </ul> <p>I think, same solution might be perfect for C++, but this requires lot of work...</p> <p>I want to present solution, which behaves like string in C# (in sense, that it is read-only and only can be created and reassigned). No counterpart, like <code>StringBuffer</code> was created, but my solution has very basic functions to create new strings.</p> <p>I want to see some comments about my solution and suggestions how can I improve it.</p> <p>Basic requirements when I design my own string-class implementation was following:</p> <ul> <li><p>it should be very lightweight;</p></li> <li><p>copying and passing by value should be almost free;</p></li> <li><p>multiple instances of same string should share its representation (and memory);</p></li> <li><p>strings cant be created from string literals and shouldn't require memory allocation or copying in that case;</p></li> <li><p>strings should be freely convertible to/from <code>std::string_view</code> class.</p></li> </ul> <p>You can see the code <a href="https://coliru.stacked-crooked.com/a/ba8b05b14dbfbc52" rel="nofollow noreferrer">on Coliru</a>.</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;new&gt; #include &lt;string_view&gt; #include &lt;atomic&gt; #include &lt;stdexcept&gt; #include &lt;stdarg.h&gt; // Some implementation of class similar to `string_view' should be available in global namespace // (CString class requires this) using std::string_view; // Class `CString' implements lightweight constant read-only string suitable // for storing in arrays, for passing by value, etc... // // Main essential properties of `CString' class are following: // // * it has extremelly small size (1 pointer); // // * copying (and passing by value) is almost free of cost; // // * multiple instances of CString can share internal representation; // // * if CString created from string literal it doesn't require // neither memory allocation, nor data copying (so constant strings // are really weightless). // // Some negative properties: // // * size of stored string limited to 65536 bytes; // // * nul-symbol can't be stored inside string; // // * program can crash in runtime when constructing CString from string literal, // if .rodata segment is larger than 8 MBytes (this is limit for 32-bit platform, // for 64-bit platform limit is hardly noticeable); // // * computing string size, when string was created from string literal and size // is larger than 128 bytes, isn't performed in constant time: for each next // 128 bytes small additional penalty added (so computing size of large string // created from string literals isn't free). // // This class can be modified, it represents only read-only strings, and can be // created in one of the following ways: // // 1) from literal string: CString text("some text..."); // // 2) from `string_view' and from const char* (implicitly, via string_view); // // 3) as result of calling static printf-like functions `printf' and `vprintf'; // // 4) as result of concatenation of any string-like objects convertible to string_view, // via static concat(...) function; // // 5) as result of calling constructor with specifying desired string size and // initializer function, which then creates string contents. // // CString class supports following operations: // // * strings can be reassigned (but not modified); // // * conversion to C-string or string_view (CString always stores zero-terminated // representation of the string, nul-symbol can't be stored in the string); // // * size of the string computed in constant time for most practical cases (see note above); // // * characters can be accessed by index (implemented operator[]). // class CString { public: typedef unsigned short size_type; // first major limit: string sizes private: // This structure contains shared representation of the string, when string // is stored in allocated memory. struct Shared { std::atomic&lt;unsigned short&gt; count; // second major limit: the number of shared copies const size_type size; // size of the string (not including terminating zero) char data[1]; Shared(size_type size) : count{1}, size{size} {} }; // This constant determines how many bits of variable `ptr' used for storing offset // from `Base' to string literal, and how many bits used for encoding string literal length. // Actually for string length ConstSizeBits-1 bits used (only lower bits of the length are // stored, upper bits restored in runtime). constexpr static const unsigned ConstSizeBits = 8; // Address of this variable used to compute offset in .rodata segment, for storing string literals. static const char Base[1]; // this variable might contain one of the three variants: // 1) nullptr -- when CString contains empty string; // 2) pointer to struct Shared -- when CString holds string in allocated memory; // 3) offset between `Base' and string literal (offset in .rodata segment) // combined with lowest 7 bits of string length. intptr_t ptr; // returns `true' if current instance of CString stores string literal. bool is_const() const noexcept { return ptr &amp; 1; } Shared *get_shared() const noexcept { return reinterpret_cast&lt;Shared*&gt;(ptr); } // returns string literal address from offset stored in `ptr' const char* const_data() const noexcept { intptr_t offset = ptr &gt;&gt; ConstSizeBits; return reinterpret_cast&lt;const char*&gt;(offset + Base); } // function called in case, when offset can't be encoded in `ptr' (when offset is too large) __attribute__((noreturn, noinline)) void runtime_error(const char *msg) const { throw std::runtime_error(msg); } public: // create empty string (no memory allocation) CString() noexcept : ptr{0} {} // create string with specified size and initialize it by given functior (memory allocated) template &lt;typename Initializer&gt; CString(size_t size, Initializer init) { if (!size) new (this) CString; else { if (size &gt; size_type(-1)) runtime_error("CString overflow"); Shared *shared = static_cast&lt;Shared*&gt;(operator new(size + sizeof(Shared))); new (shared) Shared(size_type(size)); init(shared-&gt;data); shared-&gt;data[size] = 0; ptr = intptr_t(shared); } } // create string from string_view class (memory allocated and string copy created) explicit CString(string_view str) { new (this) CString(str.size(), [&amp;str](char *data){ str.copy(data, str.size()); }); } // Note: constructor like CString(const char *str) and operator= with same argument // not implemented intentionally -- string should be created or assigned via intermediate // string_view class. Existence of constructor or assigne operator with "const char *" // argument prevents implementation of constructor or assign operators wich works with // string literals (see below). // create constant string from string literal (i.e. CString const_string("text")...) // memory will not be allocated, instead size and pointer will be saved (as offset from Base symbol) template &lt;size_t Size&gt; constexpr explicit CString(const char (&amp;literal)[Size]) { if (!Size) new (this) CString; else { // compute offset from `Base' const intptr_t offset = literal - Base; const intptr_t MaxOffset = uintptr_t(-1) &gt;&gt; (ConstSizeBits + 1); const intptr_t MinOffset = uintptr_t(-1) &lt;&lt; (sizeof(intptr_t)*8 - ConstSizeBits); if (offset &gt; MaxOffset || offset &lt; MinOffset) runtime_error("CString offset in too large"); // compute low bits of size constexpr size_t size = Size - 1; // don't count terminating zero constexpr uintptr_t short_size = size &amp; ((1&lt;&lt;(ConstSizeBits - 1)) - 1); // combine result ptr = offset &lt;&lt; ConstSizeBits | (short_size&lt;&lt;1) | 1; } } // create copy of the string (by increasing reference count) CString(const CString&amp; other) noexcept : ptr{other.ptr} { if (ptr) { if (! is_const()) get_shared()-&gt;count++; } } // move constructor just makes string empty CString(CString&amp;&amp; other) noexcept : ptr{other.ptr} { other.ptr = 0; } ~CString() { if (ptr &amp;&amp; !is_const()) { // free memory only in case if CString holds string in allocated memory Shared *shared = get_shared(); if (--shared-&gt;count == 0) operator delete(shared); } } // These functions used to create CString as result of calling printf-like function... static CString vprintf(const char *fmt, va_list args); static CString printf(const char *fmt, ...); // Create CString as result of concatenation of given arguments // (all shold be convertible to string_view). template &lt;typename... Args&gt; static CString concat(Args&amp;&amp;... args) { string_view parts[] = { args... }; size_t len = 0; for (const string_view&amp; s : parts) len += s.size(); return CString(len, [&amp;parts](char *data){ for(const string_view&amp; s : parts) data += s.copy(data, s.size()); }); } // Assign new value. CString&amp; operator=(const CString&amp; other) { this-&gt;~CString(); return *new (this) CString(other); } // This function also handles case, when assigning "const char*" to CString, // see comment in CString(string_view) above. CString operator=(string_view str) { this-&gt;~CString(); return *new (this) CString(str); } // Assign string literal. template &lt;size_t Size&gt; CString&amp; operator=(const char (&amp;literal)[Size]) { this-&gt;~CString(); return *new (this) CString(literal); } // Get zero-terminated C-string representation. const char *c_str() const noexcept { if (! ptr) // empty string (returns pointer to nul-symbol) { return reinterpret_cast&lt;const char*&gt;(&amp;ptr); } else if (! is_const()) // data in allocated memory { return get_shared()-&gt;data; } else { return const_data(); // return string literal } } // Return size of the stored string. size_t size() const noexcept { if (! ptr) // empty string { return 0; } else if (! is_const()) // data in allocated memory { return get_shared()-&gt;size; } else { // decode `ptr' to lowest bits of string size and offset const uintptr_t short_size = (ptr &amp; ((1&lt;&lt;ConstSizeBits) - 1)) &gt;&gt; 1; const char *start = const_data(); // start searching end of string const char *end = &amp;start[short_size]; while (*end) end += 1&lt;&lt;(ConstSizeBits - 1); // compute length return end - start; } } // return `true' if CString is empty bool empty() const noexcept { return !ptr; } // access particular character by index const char&amp; operator[](int i) const noexcept { return c_str()[i]; } // conversion to string_view operator string_view() const noexcept { return string_view(c_str(), size()); } }; // these functions allow CString comparison with string_view or string literals template &lt;typename T&gt; bool operator==(const CString&amp; s, T other) { return static_cast&lt;string_view&gt;(s) == static_cast&lt;string_view&gt;(other); } template &lt;typename T&gt; bool operator!=(const CString&amp; s, T other) { return static_cast&lt;string_view&gt;(s) != static_cast&lt;string_view&gt;(other); } template &lt;typename T&gt; bool operator&lt;(const CString&amp; s, T other) { return static_cast&lt;string_view&gt;(s) &lt; static_cast&lt;string_view&gt;(other); } template &lt;typename T&gt; bool operator&gt;(const CString&amp; s, T other) { return static_cast&lt;string_view&gt;(s) &gt; static_cast&lt;string_view&gt;(other); } template &lt;typename T&gt; bool operator&lt;=(const CString&amp; s, T other) { return static_cast&lt;string_view&gt;(s) &lt;= static_cast&lt;string_view&gt;(other); } template &lt;typename T&gt; bool operator&gt;=(const CString&amp; s, T other) { return static_cast&lt;string_view&gt;(s) &gt;= static_cast&lt;string_view&gt;(other); } template &lt;typename T&gt; bool operator==(T other, const CString&amp; s) { return static_cast&lt;string_view&gt;(other) == static_cast&lt;string_view&gt;(s); } template &lt;typename T&gt; bool operator!=(T other, const CString&amp; s) { return static_cast&lt;string_view&gt;(other) != static_cast&lt;string_view&gt;(s); } template &lt;typename T&gt; bool operator&lt;(T other, const CString&amp; s) { return static_cast&lt;string_view&gt;(other) &lt; static_cast&lt;string_view&gt;(s); } template &lt;typename T&gt; bool operator&gt;(T other, const CString&amp; s) { return static_cast&lt;string_view&gt;(other) &gt; static_cast&lt;string_view&gt;(s); } template &lt;typename T&gt; bool operator&lt;=(T other, const CString&amp; s) { return static_cast&lt;string_view&gt;(other) &lt;= static_cast&lt;string_view&gt;(s); } template &lt;typename T&gt; bool operator&gt;=(T other, const CString&amp; s) { return static_cast&lt;string_view&gt;(other) &gt;= static_cast&lt;string_view&gt;(s); } bool operator==(const CString&amp; s, const CString&amp; other) { return static_cast&lt;string_view&gt;(s) == static_cast&lt;string_view&gt;(other); } bool operator!=(const CString&amp; s, const CString&amp; other) { return static_cast&lt;string_view&gt;(s) != static_cast&lt;string_view&gt;(other); } bool operator&lt;(const CString&amp; s, const CString&amp; other) { return static_cast&lt;string_view&gt;(s) &lt; static_cast&lt;string_view&gt;(other); } bool operator&gt;(const CString&amp; s, const CString&amp; other) { return static_cast&lt;string_view&gt;(s) &gt; static_cast&lt;string_view&gt;(other); } bool operator&lt;=(const CString&amp; s, const CString&amp; other) { return static_cast&lt;string_view&gt;(s) &lt;= static_cast&lt;string_view&gt;(other); } bool operator&gt;=(const CString&amp; s, const CString&amp; other) { return static_cast&lt;string_view&gt;(s) &gt;= static_cast&lt;string_view&gt;(other); } ////////////////////////////// CString.cpp file ////////////////////////////////////// #include &lt;stdio.h&gt; const char CString::Base[1] = ""; CString CString::vprintf(const char *fmt, va_list args) { int len = vsnprintf(NULL, 0, fmt, args); if (len &lt;= 0) return CString(string_view()); return CString(len, [&amp;](char *data){ vsnprintf(data, len + 1, fmt, args); }); } CString CString::printf(const char *fmt, ...) { va_list args; va_start(args, fmt); CString result = CString::vprintf(fmt, args); va_end(args); return result; } /////////////////////// Usage examples //////////////////////////////////////////////// int main() { // create CString from literal CString lit("1234"); // create CString by contatenating multiple strings string_view sv = "ccc"; CString a = CString::concat("a", "bb", sv, lit); // create CString by using printf-function CString b = CString::printf("%d %s %d %s\n", int(lit.size()), lit.c_str(), a.size(), a.c_str()); // comparing CStrings a == b; a &lt; b; b &gt;= a; a == "xxx"; "yyy" != b; a == sv; sv != b; string_view(a).data(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T16:20:26.600", "Id": "437690", "Score": "1", "body": "What's wrong with simply using `const std::string&` or `const std::string_view&`, if you want to have read only characteristics?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T17:06:21.813", "Id": "437698", "Score": "0", "body": "std::string_view not own the string itself, so I should manually control ownership in some way. Obvious problem, I can't create string and return string_view from function: because nobody owns resulting string.\n\nWith passing/returning _reference_ (to any object) same problem. Owning reference doesn't guarantee owning the data.\n\nOf course, I can use const std::string as \"constant string\". No problems with ownership, but in better case (short string or using std::move) compiler will copy 32 bytes (4-8 pointers) every time. In worst case new memory will be allocated and data copied. Not good." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T20:16:16.890", "Id": "437711", "Score": "1", "body": "If you pass a `std::string const&` you are affectively passing a read only version of the string. Also the assertion `and it always copyes data` is not strictly true. It has to have the same affect as if copying the data but the compiler is allowed to optimize that out which C++03 compilers did very effectively. Now with move semantics built into the language this becomes even more redundant. Can you provide a unit test (one we can tempatize with std::string const& and your `CString` that would show a significant difference)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T04:12:37.137", "Id": "437729", "Score": "0", "body": "If I understand correct, you are trying to mix `const std::string&` and `std::string_view` together, thus obfuscating the ownership. I guess I am missing something." } ]
[ { "body": "<p>All assignment operators contain the same bug - not checking for self assignment. This bug will lead to undefined behavior, or a SEGFAULT.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T18:20:55.310", "Id": "439650", "Score": "3", "body": "Not checking for self-assignment is generally the right thing. Of course, self-assignment should still *work* (self-move-assignment may change the value, self-copy-assignment may be inefficient, but both must be safe)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-17T12:50:16.083", "Id": "445623", "Score": "0", "body": "Thanks, I also have found another bug: when CString constructed from array of (non-const) chars, the length of contained string computed incorrectly. For example, we can have same buffer `char buffer[256]` and some short string, which was constructed in this buffer. Currently CString class not distinguish between const and non-const arrays, and always assumes, that string length is same, as array size. This is right for const string literals, but for case with buffer this is wrong." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T17:16:27.407", "Id": "226276", "ParentId": "225414", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T14:09:50.600", "Id": "225414", "Score": "3", "Tags": [ "c++", "strings" ], "Title": "Lightweight read-only string implementation (C++)" }
225414
<p>R doesn't have classed errors, just (for the most part) <code>error</code> and <code>warning</code>, so determining if the error should be <em>caught</em> or <em>passed</em> is up to the programmer. From the python side, I've always appreciated the ability to catch specific errors and pass the rest on, as in an example from the py3 tutorial on <a href="https://docs.python.org/3/tutorial/errors.html#handling-exceptions" rel="noreferrer">Handling Exceptions</a>:</p> <pre class="lang-py prettyprint-override"><code>import sys try: f = open('myfile.txt') s = f.readline() i = int(s.strip()) except OSError as err: print("OS error: {0}".format(err)) except ValueError: print("Could not convert data to an integer.") except: print("Unexpected error:", sys.exc_info()[0]) raise </code></pre> <p>I'm familiar with <a href="http://adv-r.had.co.nz/" rel="noreferrer">Adv-R</a> and its discussions of <code>withCallingHandlers</code> and <code>tryCatch</code>, and below is an attempt to provide a single-point for selectively catching errors. Since R does not have classed errors as python does, I believe the "best" way to match specific errors is with regexps on the error message itself. While this is certainly imperfect, I think it's "good enough" (and perhaps the most flexible available).</p> <pre class="lang-r prettyprint-override"><code>#' Pattern-matching tryCatch #' #' Catch only specific types of errors at the appropriate level. #' Supports nested use, where errors not matched by inner calls will #' be passed to outer calls that may (or may not) catch them #' separately. If no matches found, the error is re-thrown. #' #' @param expr expression to be evaluated #' @param ... named functions, where the name is the regular #' expression to match the error against, and the function accepts a #' single argument, the error #' @param finally expression to be evaluated before returning or #' exiting #' @param perl logical, should Perl-compatible regexps be used? #' @param fixed logical, if 'TRUE', the pattern (name of each handler #' argument) is a string to be matched as is #' @return if no errors, the return value from 'expr'; if an error is #' matched by one of the handlers, the return value from that #' function; if no matches, the error is propogated up #' @export #' @examples #' #' tryCatchPatterns({ #' tryCatchPatterns({ #' stop("no-math-nearby, hello") #' 99 #' }, "^no-math" = function(e) { cat("in inner\n"); -1L }) #' }, "oops" = function(e) { cat("in outer\n"); -2L }) #' # in inner #' # [1] -1 #' #' tryCatchPatterns({ #' tryCatchPatterns({ #' stop("oops") #' 99 #' }, "^no-math" = function(e) { cat("in inner\n"); -1L }) #' }, "oops" = function(e) { cat("in outer\n"); -2L }) #' # in outer #' # [1] -2 #' #' tryCatchPatterns({ #' tryCatchPatterns({ #' stop("neither") #' 99 #' }, "^no-math" = function(e) { cat("in inner\n"); -1L }) #' }, "oops" = function(e) { cat("in outer\n"); -2L }, #' "." = function(e) { cat("in catch-all\n"); -3L }) #' # in catch-all #' # [1] -3 #' #' \dontrun{ #' tryCatchPatterns({ #' tryCatchPatterns({ #' stop("neither") #' 99 #' }, "^no-math" = function(e) { cat("in inner\n"); -1L }) #' }, "oops" = function(e) { cat("in outer\n"); -2L }) #' # Error in eval(expr, envir = parentenv) : neither #' } #' tryCatchPatterns &lt;- function(expr, ..., finally, perl = FALSE, fixed = FALSE) { parentenv &lt;- parent.frame() handlers &lt;- list(...) # --------------------------------- # check all handlers are correct if (length(handlers) &gt; 0L &amp;&amp; (is.null(names(handlers)) || any(!nzchar(names(handlers))))) stop("all error handlers must be named") if (!all(sapply(handlers, is.function))) stop("all error handlers must be functions") # --------------------------------- # custom error-handler that references 'handlers' myerror &lt;- function(e) { msg &lt;- conditionMessage(e) handled &lt;- FALSE for (hndlr in names(handlers)) { # can use ptn of "." for catch-all if (grepl(hndlr, msg, perl = perl, fixed = fixed)) { out &lt;- handlers[[hndlr]](e) handled &lt;- TRUE break } } if (handled) out else stop(e) } # --------------------------------- # quote some expressions to prevent too-early evaluation expr_q &lt;- quote(eval(expr, envir = parentenv)) finally_q &lt;- if (!missing(finally)) quote(finally) tc_args &lt;- list(error = myerror, finally = finally_q) # --------------------------------- # evaluate! do.call("tryCatch", c(list(expr_q), tc_args)) } </code></pre> <p>The intent is to be able to handle some errors perhaps differently (most likely in side-effect) but not necessarily catch <em>all</em> errors.</p> <p>I'm particularly interested in these questions:</p> <ul> <li><strong>context of evaluating <code>expr</code></strong>: I believe <code>quote(eval(expr, envir = parentenv))</code> is sufficient for ensuring no surprises with namespace and search path, am I missing something?</li> <li><strong>context of the <code>error</code></strong>: it would be ideal if <code>traceback()</code> of a not-caught error did not originate in <code>myerror</code>, is there a better way to re-throw the error with (or closer to) the original stack?</li> <li><p><strong>similarly handle <code>warning</code>s</strong>: I have another version of this that adds <code>warning</code>s in the same way, so it uses <code>withCallingHandlers</code> and conditional use of <code>invokeRestart("muffleWarning")</code>. The premise is that some warnings I don't care about (I might otherwise use <code>suppressWarnings</code>), some I want to log, and some indicate problems (that could also turn into errors with <code>options(warn=2)</code>). In developing shiny apps, I often use something like this (with a <code>logger::log_*</code> call instead of <code>cat</code>):</p> <pre class="lang-r prettyprint-override"><code>withCallingHandlers({ warning("foo") 99 }, warning = function(w) { cat("caught:", conditionMessage(w), "\n") invokeRestart("muffleWarning") }) # caught: foo # [1] 99 </code></pre> <p>where it might be nice to "muffle" some warnings and not others. <code>warning</code> typically includes <em>where</em> the warning originated. Similar to the previous bullet, is there a way with <code>warning</code> to preserve (re-use) the original context?</p></li> <li><strong>assumptions</strong>: am I making an egregious false assumption in the code?</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T17:38:34.957", "Id": "439443", "Score": "1", "body": "You say “R doesn't have classed errors” … I’m unsure what you mean by that since you can write virtually the same code as the Python code in R: https://gist.github.com/klmr/ca110f867c059616ae88d76ceee9d47e" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T17:39:55.473", "Id": "439444", "Score": "0", "body": "Great point (and big thanks for the demo code), but what errors in base R (and most packages, for that matter) class their exceptions like this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T17:42:03.420", "Id": "439445", "Score": "1", "body": "None, unfortunately. I have no idea why this phenomenal condition system was written and never used. For what it’s worth I *do* use subclassed conditions in my own code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T17:42:35.777", "Id": "439446", "Score": "0", "body": "Can you think of anything I'm mis-assuming or missing in the above function? I appreciate you looking at it!" } ]
[ { "body": "<ul>\n<li>I think your evaluation context is correct; and yes, it’s convoluted. In particular it impacts your second point; and …</li>\n<li>… unfortunately I’m not aware of a way to improve this. You <em>can</em> manually modify the stack trace by editing the <code>base::.Traceback</code> variable (!). However, this must happen <em>after</em> <code>stop</code> is called so I don’t think it’s helpful here.</li>\n<li>Same answer.</li>\n<li>I think your assumptions are sound.</li>\n</ul>\n\n<p>Two further points: you can slightly simplify your handler by using early exit:</p>\n\n<pre class=\"lang-r prettyprint-override\"><code>myerror &lt;- function(e) {\n msg &lt;- conditionMessage(e)\n for (hndlr in names(handlers)) {\n # can use ptn of \".\" for catch-all\n if (grepl(hndlr, msg, perl = perl, fixed = fixed)) {\n return(handlers[[hndlr]](e))\n }\n }\n stop(e)\n}\n</code></pre>\n\n<p>And as you probably know there’s no need to quote <code>tryCatch</code> in the <code>do.call</code> call.</p>\n\n<p>… an afterthought:</p>\n\n<p>Something that simplifies the call stack slightly <em>and</em> circumvents the complex quoting of the expression is the following:</p>\n\n<pre class=\"lang-r prettyprint-override\"><code>call &lt;- match.call(expand.dots = FALSE)\ntc_call &lt;- call(\"tryCatch\", expr = call$expr, error = myerror, finally = call$finally)\neval.parent(tc_call)\n</code></pre>\n\n<p>This seems to work.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T18:17:07.820", "Id": "439452", "Score": "0", "body": "I often quote the function in `do.call` in part due to https://rpubs.com/hadley/do-call, for better or worse. Your suggested `call <- ...` code looks simpler, I'll play with it some more. Many thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T18:06:29.630", "Id": "226198", "ParentId": "225419", "Score": "2" } } ]
{ "AcceptedAnswerId": "226198", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T15:07:59.747", "Id": "225419", "Score": "10", "Tags": [ "error-handling", "r" ], "Title": "error-specific tryCatch" }
225419
<p>The authors of <a href="http://www.cvlibs.net/publications/Geiger2010ACCV.pdf" rel="nofollow noreferrer">this paper</a> compute support_points of a 900×700 image in 118 ms. I have implemented their algorithm below in Halide. In my algorithm, the nested for loops over length and width iterate over <code>xi</code> and <code>yi</code>, which are points in <code>output_x</code> and <code>output_y</code>. Over each iteration of the nested for loops, a vector top_k is computed and pushed_back into support_points. Computing this pipeline even for <code>left_buffer.width() == 20</code> and <code>left_buffer.height() == 20</code> takes 500 ms. Thus this implementation is several orders of magnitude slower.</p> <pre><code>// To compile and run: // export LD_LIBRARY_PATH=../bin // g++ support.cpp -g -I ../include -I ../tools -L ../bin -lHalide `libpng-config --cflags --ldflags` -ljpeg -lpthread -ldl -o support -std=c++11 &amp;&amp; ./support #include&lt;stdio.h&gt; #include&lt;string&gt; #include "Halide.h" #include "halide_image_io.h" #include &lt;math.h&gt; #include "clock.h" #include &lt;vector&gt; using namespace std; using namespace Halide::Tools; using namespace Halide::ConciseCasts; using namespace Halide; int main(int argc, char **argv) { double t1 = current_time(); Var x("x"), y("y"); Buffer&lt;uint8_t&gt; left_buffer = load_image("images/stereo/bike_smallest.jpg"); Expr clamped_x = clamp(x, 0, left_buffer.width() - 1); Expr clamped_y = clamp(y, 0, left_buffer.height() - 1); Func left_original("left_original"); left_original(x, y) = f32(left_buffer(clamped_x, clamped_y)); left_original.compute_root(); // 3x3 sobel filter Buffer&lt;float_t&gt; sobel_1(3); sobel_1(0) = -1; sobel_1(1) = 0; sobel_1(2) = 1; Buffer&lt;float_t&gt; sobel_2(3); sobel_2(0) = 1; sobel_2(1) = 2; sobel_2(2) = 1; Func output_x_inter("output_x_inter"); output_x_inter(x, y) = f32(left_original(x + 1, y) * sobel_1(0) + left_original(x, y) * sobel_1(1) + left_original(x - 1, y) * sobel_1(2)); output_x_inter.compute_root(); Func sobel_x("sobel_x"); sobel_x(x, y) = f32(output_x_inter(x, y + 1) * sobel_2(0) + output_x_inter(x, y) * sobel_2(1) + output_x_inter(x, y - 1) * sobel_2(2)); // sobel_x.compute_root(); didn't work sobel_x.trace_stores(); Buffer&lt;float&gt; output_x = sobel_x.realize(left_buffer.width(), left_buffer.height()); output_x.set_name("output_x"); Func sobel_y_inter("sobel_y_inter"); sobel_y_inter(x, y) = f32(left_original(x + 1, y) * sobel_2(0) + left_original(x, y) * sobel_2(1) + left_original(x - 1, y) * sobel_2(2)); Func sobel_y("sobel_y"); sobel_y(x, y) = f32(sobel_y_inter(x, y + 1) * sobel_1(0) + sobel_y_inter(x, y) * sobel_1(1) + sobel_y_inter(x, y - 1) * sobel_1(2)); sobel_y.compute_root(); sobel_y.trace_stores(); Buffer&lt;float&gt; output_y = sobel_y.realize(left_buffer.width(), left_buffer.height()); output_y.set_name("output_y"); int k = 4; // # of support points vector&lt;pair&lt;Expr, Expr&gt;&gt; support_points(k * left_buffer.width() * left_buffer.height()); // Calculate support pixel for each Func support("support"); support(x, y) = Tuple(i32(0), i32(0), f32(0)); for (int yi = 0; yi &lt; left_buffer.height(); yi++) { for (int xi = 0; xi &lt; left_buffer.width() - 2; xi++) { bool left = xi &lt; left_buffer.width() / 4; bool center = (xi &gt;= left_buffer.width() / 4 &amp;&amp; xi &lt; left_buffer.width() * 3 / 4); bool right = xi &gt;= left_buffer.width() * 3 / 4; vector &lt;pair&lt;Expr, Expr&gt;&gt; scan_range; pair &lt;Expr, Expr&gt; scan_height(0, (Expr) left_buffer.height()); pair &lt;Expr, Expr&gt; scan_width; int which_pred = 0; if (left) { scan_width = make_pair((Expr) 0, (Expr) left_buffer.width() / 2); which_pred = 0; } else if (center) { scan_width = make_pair((Expr) xi - left_buffer.width() / 4, (Expr) left_buffer.width() / 2); which_pred = 1; } else if (right) { scan_width = make_pair((Expr) left_buffer.width() / 2, (Expr) left_buffer.width() / 2); which_pred = 2; } else { cout&lt;&lt;"Error"&lt;&lt;endl; } scan_range = {scan_width, scan_height}; // cout&lt;&lt;"xi "&lt;&lt;xi&lt;&lt;endl; // cout&lt;&lt;"yi "&lt;&lt;yi&lt;&lt;endl; // cout&lt;&lt;"scan_width= "&lt;&lt;scan_width.first&lt;&lt;" "&lt;&lt;scan_width.second&lt;&lt;endl; // cout&lt;&lt;"scan_height= "&lt;&lt;scan_height.first&lt;&lt;" "&lt;&lt;scan_height.second&lt;&lt;endl; RDom scanner(scan_range); Expr predicate[3] = {scanner.x != xi &amp;&amp; scanner.y != yi, scanner.x != 0 &amp;&amp; scanner.y != 0, scanner.x != xi &amp;&amp; scanner.y != yi}; scanner.where(predicate[which_pred]); std::vector&lt;Expr&gt; top_k(k * 3); for (int i = 0; i &lt; k; i++) { // say we want top 4 support points. top_k[3*i] = 10000.0f; top_k[3*i+1] = 0; top_k[3*i+2] = 0; } Func argmin("argmin"); argmin() = Tuple(top_k); Expr next_val = abs(output_x(xi, yi) - output_x(scanner.x, scanner.y)) + abs(output_y(xi, yi) - output_y(scanner.x, scanner.y)); Expr next_x = scanner.x; Expr next_y = scanner.y; top_k = Tuple(argmin()).as_vector(); // Insert a single element into a sorted list without actually branching top_k.push_back(next_val); top_k.push_back(next_x); top_k.push_back(next_y); for (int i = k; i &gt; 0; i--) { Expr prev_val = top_k[(i-1)*3]; Expr prev_x = top_k[(i-1)*3 + 1]; Expr prev_y = top_k[(i-1)*3 + 2]; Expr should_swap = top_k[i*3] &lt; prev_val; top_k[(i-1)*3] = select(should_swap, top_k[i*3], prev_val); top_k[(i-1)*3 + 1] = select(should_swap, top_k[i*3 + 1], prev_x); top_k[(i-1)*3 + 2] = select(should_swap, top_k[i*3 + 2], prev_y); top_k[i*3] = select(should_swap, prev_val, top_k[i*3]); top_k[i*3 + 1] = select(should_swap, prev_x, top_k[i*3 + 1]); top_k[i*3 + 2] = select(should_swap, prev_y, top_k[i*3 + 2]); } // Discard the k+1th element top_k.pop_back(); top_k.pop_back(); top_k.pop_back(); bool cond = xi == 10 &amp;&amp; yi == 10; cout &lt;&lt; xi &lt;&lt; " "&lt;&lt; yi &lt;&lt; " " &lt;&lt; cond &lt;&lt; endl; Expr e = argmin()[0]; e = print_when(cond, e, "&lt;- argmin() val"); argmin() = Tuple(top_k); argmin.compute_root(); // argmin.trace_stores(); argmin.compile_to_lowered_stmt("argmin.html", {}, HTML); Realization real = argmin.realize(); for (int i = 0; i &lt; k; i++) { pair&lt;Expr, Expr&gt; c(top_k[3*i+1], top_k[3*i+2]); support_points.push_back(c); } } } double t2 = current_time(); cout&lt;&lt;(t2-t1)/100&lt;&lt;" ms"&lt;&lt;endl; cout&lt;&lt;"executed"&lt;&lt;endl; } </code></pre> <p>How can I make it more efficient?</p> <p>----- EDIT -----</p> <p>As an answer suggested, I pulled out all the declarations out of the iterations, but this has had only a marginal effect, if any, on the performance. This is what my code looks like now:</p> <pre><code>#include&lt;stdio.h&gt; #include&lt;string&gt; #include "Halide.h" #include "halide_image_io.h" #include &lt;math.h&gt; #include "clock.h" #include &lt;vector&gt; #define R 0 #define G 1 #define B 2 using namespace std; using namespace Halide::Tools; using namespace Halide::ConciseCasts; using namespace Halide; int main(int argc, char **argv) { double t1 = current_time(); Var x("x"), y("y"); Buffer&lt;uint8_t&gt; left_buffer = load_image("images/stereo/bike_smallest.jpg"); Expr clamped_x = clamp(x, 0, left_buffer.width() - 1); Expr clamped_y = clamp(y, 0, left_buffer.height() - 1); Func left_original("left_original"); left_original(x, y) = f32(left_buffer(clamped_x, clamped_y)); left_original.compute_root(); // 3x3 sobel filter Buffer&lt;float_t&gt; sobel_1(3); sobel_1(0) = -1; sobel_1(1) = 0; sobel_1(2) = 1; Buffer&lt;float_t&gt; sobel_2(3); sobel_2(0) = 1; sobel_2(1) = 2; sobel_2(2) = 1; Func output_x_inter("output_x_inter"); output_x_inter(x, y) = f32(left_original(x + 1, y) * sobel_1(0) + left_original(x, y) * sobel_1(1) + left_original(x - 1, y) * sobel_1(2)); output_x_inter.compute_root(); Func sobel_x("sobel_x"); sobel_x(x, y) = f32(output_x_inter(x, y + 1) * sobel_2(0) + output_x_inter(x, y) * sobel_2(1) + output_x_inter(x, y - 1) * sobel_2(2)); // sobel_x.compute_root(); didn't work // sobel_x.trace_stores(); Buffer&lt;float&gt; output_x = sobel_x.realize(left_buffer.width(), left_buffer.height()); output_x.set_name("output_x"); Func sobel_y_inter("sobel_y_inter"); sobel_y_inter(x, y) = f32(left_original(x + 1, y) * sobel_2(0) + left_original(x, y) * sobel_2(1) + left_original(x - 1, y) * sobel_2(2)); Func sobel_y("sobel_y"); sobel_y(x, y) = f32(sobel_y_inter(x, y + 1) * sobel_1(0) + sobel_y_inter(x, y) * sobel_1(1) + sobel_y_inter(x, y - 1) * sobel_1(2)); sobel_y.compute_root(); // sobel_y.trace_stores(); Buffer&lt;float&gt; output_y = sobel_y.realize(left_buffer.width(), left_buffer.height()); output_y.set_name("output_y"); int k = 4; // # of support points vector&lt;pair&lt;Expr, Expr&gt;&gt; support_points(k * left_buffer.width() * left_buffer.height()); // Calculate support pixel for each Func support("support"); support(x, y) = Tuple(i32(0), i32(0), f32(0)); vector &lt;pair&lt;Expr, Expr&gt;&gt; scan_range(2); pair &lt;Expr, Expr&gt; scan_height(0, (Expr) left_buffer.height()); pair &lt;Expr, Expr&gt; scan_width; std::vector&lt;Expr&gt; top_k(k * 3); Expr predicate[3]; int count = 0; RDom scanner; bool left; bool center; bool right; int which_pred = 0; Expr next_val, next_x, next_y, prev_val, prev_x, prev_y; Expr should_swap; pair&lt;Expr, Expr&gt; c; for (int yi = 0; yi &lt; left_buffer.height(); yi++) { for (int xi = 0; xi &lt; left_buffer.width() - 2; xi++) { left = xi &lt; left_buffer.width() / 4; center = (xi &gt;= left_buffer.width() / 4 &amp;&amp; xi &lt; left_buffer.width() * 3 / 4); right = xi &gt;= left_buffer.width() * 3 / 4; if (left) { scan_width = make_pair((Expr) 0, (Expr) left_buffer.width() / 2); which_pred = 0; } else if (center) { scan_width = make_pair((Expr) xi - left_buffer.width() / 4, (Expr) left_buffer.width() / 2); which_pred = 1; } else if (right) { scan_width = make_pair((Expr) left_buffer.width() / 2, (Expr) left_buffer.width() / 2); which_pred = 2; } else { cout&lt;&lt;"Error"&lt;&lt;endl; } scan_range[0] = scan_width; scan_range[1] = scan_height; // so far 1e-05 per iteration scanner = (scan_range); //slow 0.006 // these three kind of slow 0.002 predicate[0] = scanner.x != xi &amp;&amp; scanner.y != yi; predicate[1] = scanner.x != 0 &amp;&amp; scanner.y != 0; predicate[2] = scanner.x != xi &amp;&amp; scanner.y != yi; scanner.where(predicate[which_pred]); // this loop is 1e-05 for (int i = 0; i &lt; k; i++) { // say we want top 4 support points. top_k[3*i] = 10000.0f; top_k[3*i+1] = 0; top_k[3*i+2] = 0; } Func argmin("argmin"); // 0.003 argmin() = Tuple(top_k); next_val = abs(output_x(xi, yi) - output_x(scanner.x, scanner.y)) + abs(output_y(xi, yi) - output_y(scanner.x, scanner.y)); next_x = scanner.x; next_y = scanner.y; top_k = Tuple(argmin()).as_vector(); // Insert a single element into a sorted list without actually branching top_k.push_back(next_val); top_k.push_back(next_x); top_k.push_back(next_y); for (int i = k; i &gt; 0; i--) { prev_val = top_k[(i-1)*3]; prev_x = top_k[(i-1)*3 + 1]; prev_y = top_k[(i-1)*3 + 2]; should_swap = top_k[i*3] &lt; prev_val; top_k[(i-1)*3] = select(should_swap, top_k[i*3], prev_val); top_k[(i-1)*3 + 1] = select(should_swap, top_k[i*3 + 1], prev_x); top_k[(i-1)*3 + 2] = select(should_swap, top_k[i*3 + 2], prev_y); top_k[i*3] = select(should_swap, prev_val, top_k[i*3]); top_k[i*3 + 1] = select(should_swap, prev_x, top_k[i*3 + 1]); top_k[i*3 + 2] = select(should_swap, prev_y, top_k[i*3 + 2]); // cout&lt;&lt;"(165)"&lt;&lt;endl; } // Discard the k+1th element top_k.pop_back(); top_k.pop_back(); top_k.pop_back(); argmin() = Tuple(top_k); argmin.compute_root(); // argmin.trace_stores(); argmin.compile_to_lowered_stmt("argmin.html", {}, HTML); // cout&lt;&lt;"(184)"&lt;&lt;endl; Realization real = argmin.realize(); //1.5 ms // cout&lt;&lt;"(186)"&lt;&lt;endl; for (int i = 0; i &lt; k; i++) { c.first = top_k[3*i+1]; c.second = top_k[3*i+2]; support_points.push_back(c); } count++; } } double t2 = current_time(); cout&lt;&lt;count&lt;&lt;" "&lt;&lt;(t2-t1)/100&lt;&lt;" ms"&lt;&lt;endl; cout&lt;&lt;"executed"&lt;&lt;endl; } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>This part looks ripe for refactoring:</p>\n\n<pre><code> top_k = Tuple(argmin()).as_vector();\n // Insert a single element into a sorted list without actually branching\n top_k.push_back(next_val);\n top_k.push_back(next_x);\n top_k.push_back(next_y);\n for (int i = k; i &gt; 0; i--) {\n Expr prev_val = top_k[(i-1)*3];\n Expr prev_x = top_k[(i-1)*3 + 1];\n Expr prev_y = top_k[(i-1)*3 + 2];\n Expr should_swap = top_k[i*3] &lt; prev_val;\n\n top_k[(i-1)*3] = select(should_swap, top_k[i*3], prev_val);\n top_k[(i-1)*3 + 1] = select(should_swap, top_k[i*3 + 1], prev_x);\n top_k[(i-1)*3 + 2] = select(should_swap, top_k[i*3 + 2], prev_y);\n top_k[i*3] = select(should_swap, prev_val, top_k[i*3]);\n top_k[i*3 + 1] = select(should_swap, prev_x, top_k[i*3 + 1]);\n top_k[i*3 + 2] = select(should_swap, prev_y, top_k[i*3 + 2]);\n }\n // Discard the k+1th element\n top_k.pop_back(); top_k.pop_back(); top_k.pop_back();\n</code></pre>\n\n<p>If I understand correctly, what you're doing here is bubble-sorting a triple <code>(next_val, next_x, next_y)</code> into the proper place in vector <code>top_k</code>, and then removing the now-smallest triple from the vector.</p>\n\n<p>The first thing you could do is use proper data types. Instead of triples of ints (and the continual multiplications-by-<code>3</code> that entails), you should make a struct type, like</p>\n\n<pre><code>struct Triple {\n int x;\n int y;\n int value;\n struct descending {\n bool operator()(const Triple&amp; a, const Triple&amp; b) const {\n return a.value &gt; b.value;\n }\n };\n};\n</code></pre>\n\n<p>And then your insertion can become</p>\n\n<pre><code>std::vector&lt;Triple&gt; top_k = [...]\nTriple new_item = { next_x, next_y, next_val };\nauto insertion_point = std::lower_bound(top_k.begin(), top_k.end(), new_item, Triple::descending);\ntop_k.insert(insertion_point, new_item);\ntop_k.pop_back();\n</code></pre>\n\n<p>(Or maybe my <code>descending</code> should be <code>ascending</code>. I didn't expend many brain cells on it.)</p>\n\n<hr>\n\n<p>If your algorithm <em>depends</em> on this operation, then (A) maybe you should use a <code>priority_queue</code>, (B) maybe you should use a <code>priority_queue</code> that supports the <a href=\"https://quuxplusone.github.io/blog/2018/04/27/pq-replace-top/\" rel=\"nofollow noreferrer\"><code>replace_top</code> operation</a>, and (C) <em>certainly</em> you should use something that never allocates memory in your inner loop.</p>\n\n<p>Right now it seems you're spending a lot of time resizing STL containers in the inner loop, which causes heap traffic. For performance, instead of</p>\n\n<pre><code>for (int yi = 0; yi &lt; left_buffer.height(); yi++) {\n for (int xi = 0; xi &lt; left_buffer.width() - 2; xi++) {\n [...]\n vector&lt;pair&lt;Expr, Expr&gt;&gt; scan_range = {scan_width, scan_height};\n</code></pre>\n\n<p>you should do</p>\n\n<pre><code>vector&lt;pair&lt;Expr, Expr&gt;&gt; scan_range(2);\nfor (int yi = 0; yi &lt; left_buffer.height(); yi++) {\n for (int xi = 0; xi &lt; left_buffer.width() - 2; xi++) {\n [...]\n scan_range[0] = scan_width;\n scan_range[1] = scan_height;\n</code></pre>\n\n<p>This puts the heap allocation <em>outside</em> the inner loop, which means now you're doing 1 allocation where in your original code you're doing <code>left_buffer.height()*(left_buffer.width() - 2)</code> allocations.</p>\n\n<p>Applying this strategy to your other allocations (e.g. <code>top_k</code> itself) should give a <em>huge</em> performance boost.</p>\n\n<hr>\n\n<p>EDIT: Looking for more wasted cycles in your updated code, I see the following four lines at the end of your loop:</p>\n\n<pre><code> argmin.compile_to_lowered_stmt(\"argmin.html\", {}, HTML);\n// cout&lt;&lt;\"(184)\"&lt;&lt;endl;\n Realization real = argmin.realize(); //1.5 ms\n// cout&lt;&lt;\"(186)\"&lt;&lt;endl;\n</code></pre>\n\n<p>Variable <code>real</code> is never used, so you can eliminate it. If I'm interpreting that comment correctly, eliminating <code>real</code> will save you 1.5ms per loop.</p>\n\n<p><code>argmin.compile_to_lowered_stmt(...)</code> seems to be Halide's equivalent of a \"debugging printf.\" It will do a lot of work to compile the function, and then also open a file, write to it, and close the file again. Those are both horribly slow operations. So unless you <em>need</em> <code>argmin.html</code> — and I don't see how you possibly could, since you overwrite it for every pixel of the input — you should eliminate this line.</p>\n\n<p>In general, when you're trying to make something run fast, you should go over each line with a critical eye and ask, \"How expensive is this line? What benefit does this line get me?\" If it's expensive and has no benefit, then remove or rewrite it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T15:39:46.223", "Id": "437815", "Score": "0", "body": "Please check out my edit." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T14:40:25.260", "Id": "225466", "ParentId": "225420", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T15:16:50.853", "Id": "225420", "Score": "3", "Tags": [ "c++", "performance", "algorithm", "c++11", "image" ], "Title": "Stereo image matching implementation in Halide" }
225420
<p>This is my solution to <a href="https://leetcode.com/problems/next-greater-element-i/" rel="nofollow noreferrer">LeetCode's &quot;Next Greater Element Ⅰ&quot;</a>:</p> <blockquote> <p>You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2.</p> <p>The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.</p> </blockquote> <pre><code>class Solution: def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -&gt; List[int]: need, ready, next_greater = set(nums1), set(), {} for n in nums2: for k in ready: if k &lt; n: next_greater[k] = n ready = {k for k in ready if k not in next_greater} if n in need and n not in next_greater and n not in ready: ready.add(n) return [next_greater[k] if k in next_greater else -1 for k in nums1] </code></pre> <p>The <code>nextGreaterElement</code> method accepts 2 lists. Neither list contains duplicates, and <code>nums1</code> is a subset of <code>nums2</code>. For every <code>num</code> in <code>nums1</code>, it will output the first number greater than <code>num</code> positioned to the right of <code>num</code> in <code>nums2</code>, or <code>-1</code> is none is found. e.g.:</p> <pre><code>Input: nums1 = [4,1,2], nums2 = [1,3,4,2]. Output: [-1,3,-1] </code></pre> <p>I loop through the keys in <code>ready</code>, and the body of the loop does nothing unless <code>k &lt; n</code>. <code>len(ready)</code> can be very large relative to the number of values that satisfy <code>k &lt; n</code>. This seems like a very common thing so I'm wondering if there's a more explicit/pythonic way to write this?</p> <p>Or should I be using a different data structure entirely?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T20:19:10.027", "Id": "437713", "Score": "0", "body": "@dfhwze My question is more about writing Python loops in general, not my specific implementation of the loop. Would StackOverflow be a better place for that kind of question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T07:14:27.417", "Id": "437742", "Score": "0", "body": "No this is the correct place for it. You added a description of the problem statement, so it's on-topic now." } ]
[ { "body": "<p>Your code seems unnecessarily complicated.</p>\n\n<p><code>nums1</code> is subset of <code>nums2</code>. So no need to iterate over <code>nums2</code>. Because <code>nums2</code> may be bigger than <code>nums1</code> </p>\n\n<p>Here's the algo; </p>\n\n<ol>\n<li>Take a number <code>n</code> from <code>nums1</code> </li>\n<li>Find <code>n</code>'s index in <code>nums2</code>. Because <code>nums1</code> is subset of <code>nums2</code> <code>n</code> will definitely be found. </li>\n<li>Check if there's a number say <code>m</code> which is greater than <code>n</code> starting from the <code>index + 1</code> index at <code>nums2</code> </li>\n<li>If found output the number </li>\n<li><p>Otherwise output <code>-1</code> </p>\n\n<pre><code>class Solution:\n def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -&gt; List[int]:\n output = []\n for n in nums1:\n idx = nums2.index(n)\n for m in nums2[idx+1:]:\n if m &gt; n:\n output.append(m)\n break\n else:\n output.append(-1)\n return output\n</code></pre>\n\n<p>Finding index sucks time. To optimize the index can be pre-calculated. </p>\n\n<pre><code>output = []\nindex = { n: i for i, n in enumerate(nums2) }\nfor n in nums1:\n idx = index[n]\n for m in nums2[idx+1:]:\n if m &gt; n:\n output.append(m)\n break\n else:\n output.append(-1)\nreturn output\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T21:56:15.177", "Id": "437719", "Score": "1", "body": "Implementation details of Python's `list.index` might make this faster (I don't know), but the algorithm you're proposing is slower asymptotically as all elements of `nums2` will be iterated for every element in `nums1` (`O(nm)`) vs iterating each list once" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T22:04:13.927", "Id": "437720", "Score": "0", "body": "@user107870 that's good point" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T00:37:47.720", "Id": "437722", "Score": "0", "body": "@user107870 reduced iteration" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T21:18:09.643", "Id": "225436", "ParentId": "225430", "Score": "0" } }, { "body": "<p>Since list one is a subset of list two, iterating over two lists can be avoided. This can be achieved by finding the next greater element of each element for the bigger list and storing the result in a hash table.</p>\n\n<p>To calculate the next greater element of each element in a list we can iterate the list. For each element, we can find the next greater element by again iterating the list. This approach is simple but will have O(n^2) complexity.</p>\n\n<p>Another approach is by using stack. </p>\n\n<ul>\n<li>First, push the first element of the list int the stack. </li>\n<li>Now iterate the list and compare the top element of the stack with the current element of the list. </li>\n<li>If the current element is greater than the top element then that means the current element is the next greater element of the top element of the stack. Store this result in a dictionary. Pop the top element out of the stack. </li>\n<li>Repeat above two steps until the stack top element is greater than the current element or stack is empty. </li>\n<li>At the end of each iteration push the current element in the stack.</li>\n</ul>\n\n<p>The code will make things clearer: </p>\n\n<pre><code>\ndef calculate_nge_dict(arr):\n\n nge_dict = {}\n stack_ = []\n stack_.append(arr[0])\n nge_dict[arr[0]] = -1\n for i in arr[1:]:\n next_ = i\n nge_dict[next_] = -1\n while stack_:\n top_ = stack_.pop()\n if next_ &lt;= top_:\n stack_.append(top_)\n break\n else:\n nge_dict[top_] = next_\n stack_.append(next_)\n return nge_dict\n\ndef next_greater_element(nums1, nums2):\n nge_dict = calculate_nge_dict(nums2)\n return [nge_dict[i] for i in nums1]\n\n</code></pre>\n\n<p>You can get a better understanding of the algorithm from <a href=\"https://stackoverflow.com/a/19722651/7662129\">this answer</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-31T06:09:40.470", "Id": "234854", "ParentId": "225430", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T19:12:01.963", "Id": "225430", "Score": "3", "Tags": [ "python", "python-3.x", "programming-challenge" ], "Title": "Solution to LeetCode Next Greater Element Ⅰ in Python" }
225430
<p>How can I improve this hash matching program using either abstraction or search/sort algorithms?</p> <p>We briefly were introduced to searching methods such as bubble sort and merge sort, but I'm not sure how they can be implemented to improve my code.</p> <p>The program takes a command-line hash input, compares it against generated hashes, and if it finds a match, prints out the key used to generate the matched hash.</p> <p>(This is part of Harvard's CS50 on eDx Week 2 Problem Set)</p> <pre><code>#include &lt;cs50.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;crypt.h&gt; #define _XOPEN_SOURCE #include &lt;unistd.h&gt; /* * Goal: Program that takes cmd ln arg of password hash * and compares it to program generated hashes until a * match is found. * Assumptions: password is max 5 chars &amp;&amp; all chars alpha */ bool crack(string hash); int main(int argc, string argv[]) { // Check for 2 command line arguments if (argc != 2) { printf("[ERROR 1] Usage: ./crack hash\n"); return 1; } string hash = argv[1]; if (!crack(hash)) { printf("[ERROR 2] Could not crack! \n"); return 1; } } bool crack(string hash) { string alphas = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; char key[6]; char salt[3]; salt[0] = hash[0]; salt[1] = hash[1]; salt[2] = '\0'; // 1 char pw test for (int i = 0; i &lt; strlen(alphas); i++) { // Iterate over alpha chars to generate test key key[0] = alphas[i]; key[1] = '\0'; // Create new test hash string crackhash = crypt(key, salt); // Compare hashes if(strcmp(crackhash, hash) == 0) { printf("%s \n", key); // Array of chars is a string return true; } } // 2 char pw test for (int i = 0; i &lt; strlen(alphas); i++) { key[0] = alphas[i]; for (int j = 0; j &lt; strlen(alphas); j++) { key[1] = alphas[j]; key[2] = '\0'; char* crackhash = crypt(key, salt); if(strcmp(crackhash, hash) == 0) { printf("%s \n", key); return true; } } } // 3 char pw test for (int i = 0; i &lt; strlen(alphas); i++) { key[0] = alphas[i]; for (int j = 0; j &lt; strlen(alphas); j++) { key [1] = alphas[j]; for (int k = 0; k &lt; strlen(alphas); k++) { key[2] = alphas[k]; key[3] = '\0'; char* crackhash = crypt(key, salt); if(strcmp(crackhash, hash) == 0) { printf("%s \n", key); return true; } } } } // 4 char pw test for (int i = 0; i &lt; strlen(alphas); i++) { key[0] = alphas[i]; for (int j = 0; j &lt; strlen(alphas); j++) { key [1] = alphas[j]; for (int k = 0; k &lt; strlen(alphas); k++) { key [2] = alphas[k]; for (int l = 0; l &lt; strlen(alphas); l++) { key[3] = alphas[l]; key[4] = '\0'; char* crackhash = crypt(key, salt); if(strcmp(crackhash, hash) == 0) { printf("%s \n", key); return true; } } } } } // 5 char pw test for (int i = 0; i &lt; strlen(alphas); i++) { key[0] = alphas[i]; for (int j = 0; j &lt; strlen(alphas); j++) { key [1] = alphas[j]; for (int k = 0; k &lt; strlen(alphas); k++) { key [2] = alphas[k]; for (int l = 0; l &lt; strlen(alphas); l++) { key[3] = alphas[l]; for (int m = 0; m &lt; strlen(alphas); m++) { key[4] = alphas[m]; key[5] = '\0'; char* crackhash = crypt(key, salt); if(strcmp(crackhash, hash) == 0) { printf("%s \n", key); return true; } } } } } } return false; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-09T02:58:46.467", "Id": "438575", "Score": "1", "body": "Do not edit your question once an answer has been posted. (See [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers). If you have a new problem with updated code, ask a new question." } ]
[ { "body": "<h2><code>stderr</code></h2>\n\n<p>I don't know the requirements of the problem, but in a real program, error messages should be written to <code>stderr</code>:</p>\n\n<pre><code>fprintf(stderr, \"[ERROR] Whatever\\n\");\n</code></pre>\n\n<hr>\n\n<h2><code>char *</code></h2>\n\n<p>If CS50 allows it, use <code>char *</code> instead of <code>string</code>. It's the same (CS50 writes a <code>typedef</code> in <code>&lt;cs50.h&gt;</code>), but you will have it more present.</p>\n\n<p>Thanks to @TobySpeight for noting that it's not only something visual, but also the <code>typedef</code> (<code>string</code>) has problems when mixed with <code>const</code> (the behaviour is non-obvious; <code>const</code> is applied to the pointer, and not to the variable type).</p>\n\n<hr>\n\n<h2>Don't leave whitespace in a line ending</h2>\n\n<pre><code>printf(\"%s \\n\", key);\n</code></pre>\n\n<p>This code will write a space at the end of a line, which is useless, and sometimes not good at all.</p>\n\n<hr>\n\n<h2>DRY</h2>\n\n<p>Don't repeat yourself: the 5 loops are very similar. In fact the inner loop of each one is identical and could be put inside a function. Repetition usually leads to typos and bugs.</p>\n\n<hr>\n\n<h2>Compiler specific optimizations</h2>\n\n<p>AFAIK, CS50 uses Clang, which can apply optimizations beyond what you could write in standard C. To do that, you need to write code that only some compilers will understand (you can write that code inside <code>#if</code>s to support other compilers, or decide that your code will only support a specific set of compilers). GCC, Clang, and possibly other compilers make use of <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes\" rel=\"nofollow noreferrer\">function attributes</a> to tell the compiler that a function is able to be optimized more than what it may think.</p>\n\n<p>For example, @chux told in his answer that <em>good</em> compilers know that even if you write <code>strlen</code> many times, as long as the string isn't modified in between, the compiler can reuse the length from the last call. The compiler uses one of those attributes to know that (it isn't black magic). This is what the prototype for <code>strlen</code> might look like in Clang's libc:</p>\n\n<pre><code>__attribute__((pure))\nsize_t strlen(const char *s);\n</code></pre>\n\n<p>Your function crack has the same property: if you call it twice without modifying the string, the return value will be the same (and it has no side effects). You could write your prototype as:</p>\n\n<pre><code>__attribute__((pure))\nbool crack(const char *hash);\n</code></pre>\n\n<p>You could write a macro to support compilers that don't understand <code>__attribute__</code>:</p>\n\n<pre><code>#if defined(__GNUC__)\n#define pure__ __attribute__((pure))\n#else\n#define pure__\n#endif\n</code></pre>\n\n<p>If you want other compilers to be able to optimize your functions as pure but use different constructions for that, you can extend this macro. The usage would be:</p>\n\n<pre><code>pure__\nbool crack(const char *hash);\n</code></pre>\n\n<p>Note: there are other attributes that would be applicable to that function. I leave it to you to find them (read the link above).</p>\n\n<hr>\n\n<h2><code>static</code></h2>\n\n<p>Functions that are private to a <code>.c</code> file should be declared <code>static</code>. <code>crack</code> is one of those:</p>\n\n<pre><code>__attribute__((pure))\nstatic\nbool crack(const char *hash);\n\n...\n\nstatic\nbool crack(const char *hash)\n{\n ...\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T06:30:17.697", "Id": "437737", "Score": "1", "body": "Why do you say to prefer char*?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T07:33:41.457", "Id": "437747", "Score": "4", "body": "@Josiah Because it's the reality. `string` doesn't exist in C." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T17:04:14.153", "Id": "437829", "Score": "0", "body": "@Josiah The `bool` variable type also doesn't exist in C unless stdbool.h is included." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T18:34:57.510", "Id": "437840", "Score": "1", "body": "@pacmaninbw But `_Bool` exists always; it's not the same (since C99, of course). It would have been a good comparison 21 years ago, but I never use C89, and I would recommend everyone to do the same. Even in Linux they are trying to move to C11 :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T19:06:53.790", "Id": "437847", "Score": "0", "body": "I started programming in C in 1984, it was K&R C.so I predate the C89 standard. My current compiler, Visual Studio 2017 requires the stdbool.h header file. All of my Linux systems and my MacBook pro have unfortunately died so I'm currently stuck with just windows." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T20:19:13.333", "Id": "437856", "Score": "1", "body": "To clarify, I meant the Linux Kernel code, which now uses GNU C89 (`gnu89`), but they want to move to `gnu11`. In Linux, using GCC, C17 is almost fully supported. @pacmaninbw I only wrote one C program before 1999, and none before 1989 (I was born in '93), so I practically learnt C already with `bool` (lucky me); it's very sad that Windows has such bad support for C (not only C99, but C), many decades after." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-06T02:08:31.253", "Id": "438135", "Score": "0", "body": "Thanks for the suggestions, I've implemented these in the next iteration of the code. stderr is not mentioned in the course through week 3 but I will look into this." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T22:28:38.123", "Id": "225437", "ParentId": "225432", "Score": "6" } }, { "body": "<p>I agree with everything @CacahueteFrito mentioned in their answer. There is one observation there I would like to expand on, and one observation I would like to add.</p>\n\n<p><strong>Use the Type size_t When Indexing Arrays</strong><br>\nEach of the <code>for</code> loops in the function <code>bool crack(char *hash)</code> uses a type <code>int</code> variable as the loop control variable. When indexing into arrays, it is better to use the type <a href=\"http://www.cplusplus.com/reference/cstring/size_t/\" rel=\"noreferrer\">size_t</a> which is <a href=\"https://stackoverflow.com/questions/2550774/what-is-size-t-in-c\">defined as unsigned int in both C and C++</a>. The C library functions <a href=\"https://stackoverflow.com/questions/22753595/strlen-function-return-type-c-programing\">strlen</a> and <code>sizeof</code> return the type <code>size_t</code>.</p>\n\n<p>One of the benefits of using an unsigned index is that a negative number can not be used to index an array. Since arrays in C start at zero this is important and prevent bugs. A second possible benefit of using <code>size_t</code> is that it may prevent warning messages about type mismatches from some compilers when using functions such as <code>strlen</code> or <code>sizeof</code>.</p>\n\n<p><strong>Complexity of Functions</strong><br>\nWhen @CacahueteFrito mentions the <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"noreferrer\">DRY Programming Principle</a> he is providing a fix for function complexity. There is another programming principle that is involved here as well, the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"noreferrer\">Single Responsibility Principle</a>. The single responsibility principle states</p>\n\n<blockquote>\n <p>... every module, class, or function should have responsibility over a single part of the functionality provided by the software.</p>\n</blockquote>\n\n<p>While the single responsibility principle primarily applies to object oriented programming, the function part of the statement refers to non object oriented programming as well. Well written functions will have a single goal to accomplish and will generally be short. In the code there are comments of the form <code>// 2 char pw test</code>, each of the code blocks following these comments could be a function. Well named functions here would reduce the need for these comments and the overall effect would be a much simpler version of the function `bool crack(char* hash).</p>\n\n<p>Small simple functions are much easier to debug and maintain then functions that are over 100 lines long. This would also decrease the scope of variables such as <code>char key[6]</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T18:53:37.733", "Id": "437846", "Score": "3", "body": "I agree in everything but the type. I agree that there is (actually, are) a specialized type for arrays, though. To avoid giving my subjective point of view, here are both types with their pros and cons: [`ptrdiff_t` (signed) vs `size_t` (unsigned)](https://stackoverflow.com/q/3174850/6872717). But the point is there: don't use `int` for accessing arrays." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T19:13:30.600", "Id": "437848", "Score": "0", "body": "@CacahueteFrito nice link! One gets both views from the answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-06T02:30:44.940", "Id": "438136", "Score": "0", "body": "Appreciate the articulation. My goal was to have working code, and then see how I can optimize it from there. As for DRY principles, I am going to start with the easiest abstraction here which is the part where it generates a crackhash and tests versus the hash into a function. The harder part conceptually, for me as a novice programmer, is how I can write a function that generates another char in the key, and adds the next loop until the length of the key reaches a certain point." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-06T08:44:46.620", "Id": "438170", "Score": "0", "body": "`size_t` (and `std::size_t`) is an unsigned type, but not necessarily `unsigned int`. That's kind of the point: it can be `unsigned long` or `unsigned long long` as appropriate for the process's address space." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T16:25:03.207", "Id": "225471", "ParentId": "225432", "Score": "5" } }, { "body": "<p><strong>Below can lead to terrible performance.</strong></p>\n\n<p>A <em>good</em> compiler will recognize <code>alphas</code> does not change and so perform <code>strlen(alphas)</code> only once - which time complexity is the length of the string - say <code>N</code>.</p>\n\n<p>A lesser compiler will execute <code>strlen(alphas)</code> each and every time, thus the <code>5 char pw test</code> loops will cost <code>N*N*N*N*N</code> time!</p>\n\n<pre><code>// 5 char pw test\nfor (int i = 0; i &lt; strlen(alphas); i++)\n{\n key[0] = alphas[i];\n for (int j = 0; j &lt; strlen(alphas); j++)\n {\n ....\n</code></pre>\n\n<p>Instead simply use</p>\n\n<pre><code>size_t n = strlen(alphas);\nfor (size_t i = 0; i &lt; n; i++)\n{\n key[0] = alphas[i];\n for (size_t j = 0; j &lt; n; j++)\n {\n ....\n</code></pre>\n\n<p>Or idiomatic C and look for the <em>null character</em>.</p>\n\n<pre><code>for (size_t i = 0; alphas[i]; i++)\n{\n key[0] = alphas[i];\n for (size_t j = 0; alphas[j]; j++)\n {\n ....\n</code></pre>\n\n<hr>\n\n<p>Code only needed once. Recommend to move <code>key[N] = '\\0';</code> to just before each set of loops.</p>\n\n<pre><code> key[5] = '\\0';\n</code></pre>\n\n<hr>\n\n<p><strong>Minor: Use <code>const</code></strong></p>\n\n<p>Some compiler will emit more efficient code when told that <code>hash</code> does not point to changeable data. Some compilers may deduce this already. Also see <a href=\"https://codereview.stackexchange.com/questions/225432/c-based-hash-matching-cracker/225626?noredirect=1#comment438169_225626\">@Toby Speight</a></p>\n\n<pre><code>// bool crack(string hash)\nbool crack(const char *hash)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-06T02:39:12.283", "Id": "438137", "Score": "0", "body": "Awesome stuff here. These are optimizations I was hoping to learn. The 5 char password hashes were indeed taking a significant amount of time to crack. Going to implement these changes and note the difference in run time. Can you elaborate on moving the null character for the key array to outside the loops. Since each iteration is is a different length (example one password is OK another is YES), how would you tell it to be at the end regardless of the number of chars in the cracked key." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-06T04:25:47.647", "Id": "438145", "Score": "0", "body": "@stiction Every iteration within `// 5 char pw test\n for (int i = 0; i < strlen(alphas); i++)` is 5 so `key[5] = '\\0';` can precede those loops. Every iteration within `// 4 char pw test\n for (int i = 0; i < strlen(alphas); i++)` is 4 so `key[4] = '\\0';` can precede those loops. ..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-06T07:15:44.223", "Id": "438155", "Score": "0", "body": "Typo: `for (size_t j = 0; alphas[i]; j++)` -> `for (size_t j = 0; alphas[j]; j++)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-06T07:51:42.563", "Id": "438163", "Score": "0", "body": "@stiction CS50 uses Clang (AFAIK), which is a good compiler; you shouldn't notice any difference with the `strlen` calls. In fact, what Clang (probably) uses to know that it only needs to call `strlen` once is something special: `__attribute__((pure))`. I will add that to my answer, because you can apply it to your function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-06T08:42:11.823", "Id": "438169", "Score": "2", "body": "`const string` is really `char *const`, not `char const*` (thus demonstrating the problems with that typedef)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-06T10:16:38.363", "Id": "438184", "Score": "0", "body": "@TobySpeight Oh, sheet. I wouldn't have guessed that. Taking note :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-06T10:24:14.957", "Id": "438186", "Score": "0", "body": "@TobySpeight I have added that important note to my answer about `char *` vs `string` noting that you said it. If you prefer to write your own answer, I'll remove it from mine ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T10:10:50.793", "Id": "439708", "Score": "0", "body": "Regarding `string` vs. `const char *`: I have created https://github.com/cs50/libcs50/issues/175, let's see if the teachers agree this time that their typedef is a bad idea." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T19:06:37.510", "Id": "439938", "Score": "0", "body": "cs50 no longer uses `const string` in their prototypes. The typedef for `string` is still there, and it probably needs several more bug reports before they dare to remove it." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-06T01:16:58.860", "Id": "225626", "ParentId": "225432", "Score": "4" } }, { "body": "<h1>Iterating over all possible keys</h1>\n\n<p>You have the problem that you need to nest more and more loops for longer passwords.\nInstead of having nested for-loops, where each loop has an iterator that represents one character of the key, you should treat the whole key as one single iterator. For example, with a key of length 5, the lowest value of that iterator is <code>\"aaaaa\"</code>, and the highest is <code>\"ZZZZZ\"</code>. Now think of how you write a regular for-loop, and instead of <code>int i</code>, use <code>char key[]</code> as the iterator variable. Then, you have to check whether the key is valid; let's assume we will set it to the empty string if we reached the end. At the end of the loop we have to increment our iterator. That's too much work to do inside a single for-statement, but we can write functions for it. So the for-loop should look like:</p>\n\n<pre><code>for(char key[] = \"aaaaa\"; key[0] != '\\0'; increment(key)) {\n char *crackhash = crypt(key, salt);\n\n if(strcmp(crackhash, hash) == 0) {\n printf(\"%s\\n\", key);\n return true;\n } \n}\n</code></pre>\n\n<p>The function <code>increment()</code> should look like this:</p>\n\n<pre><code>void increment(char *key) {\n static const char *alphas = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n /* Increment the first character of key.\n If it was 'Z', then reset the first character to 'a',\n and continue with the next character, otherwise exit.\n If every character is 'Z', make the key an empty string.\n */\n for (int i = 0; key[i] != '\\0'; i++) {\n char *value = strchr(alphas, key[i]);\n ptrdiff_t pos = value - alphas;\n pos++;\n\n if (alphas[pos]) {\n key[i] = alphas[pos];\n break;\n } else {\n if (key[i + 1] == '\\0') {\n key[0] = '\\0';\n } else {\n key[i] = alphas[0];\n }\n }\n } \n}\n</code></pre>\n\n<p>The first time <code>increment()</code> is called with a key of length 5, <code>key</code> will be <code>\"aaaaa\"</code>. The function will then look at the first character, and look up where in the string <code>alphas</code> this character appears. Since <code>'a'</code> is the first character in <code>alphas</code>, <code>pos</code> will be <code>0</code>. It then increments <code>pos</code> to <code>1</code>, and will write back <code>alphas[pos]</code>, which is <code>'b'</code>, to the first position in <code>key</code>. Thus, the contents of <code>key</code> will then be <code>\"baaaa\"</code>. At this point, it breaks out of the for-loop and returns. The next time <code>increment()</code> will be called, it will set <code>key</code> to <code>\"caaaa\"</code>, and so on, until it is <code>\"Zaaaa\"</code>. When <code>increment()</code> is called with that value of the key, it will notice that after incrementing <code>pos</code>, <code>alphas[pos]</code> is the NUL character at the end of the the string <code>alphas</code>. It then sets the first character of <code>key</code> to the first character in <code>alphas</code> (<code>'a'</code>), and instead of breaking out of the for loop, it will continue with the second character of <code>'key'</code>. Here it does exactly the same as it did for the first character, so it sees an <code>'a'</code> and turns it into a <code>'b'</code>. So after <code>\"Zaaaa\"</code>, <code>key</code> will now become <code>\"abaaa\"</code>. Next time it will again only increment the first character, until it becomes <code>\"Zbaaa\"</code>, then the next key will be <code>\"acaaa\"</code>, and so on until it reaches <code>\"ZZaaa\"</code>. At that time, the for-loop goes all the way to the third character in <code>key</code>, and the next value will be <code>\"aabaa\"</code>. This goes on and on until <code>key</code> is <code>\"ZZZZZ\"</code>; when <code>increment()</code> is called with this value, it will reach the point where it sees that there is no sixth character to increment (<code>key[i + 1] == '\\0'</code> is true), and will then set the first character of <code>key</code> to the NUL byte, which means <code>key</code> will become an empty string. This is the signal that it has completed iterating over all possible keys.</p>\n\n<p>Note how we now just have two for loops, one in <code>increment()</code> and one in the main function. Also note that nowhere did we actually have to specify the length of the key, so the above code works for any length of key! So we can write just one more, outer for-loop to check keys of all possible sizes:</p>\n\n<pre><code>char key[MAX_LEN + 1] = \"\";\n\nfor(int len = 1; len &lt;= MAX_LEN; len++) {\n for(memset(key, 'a', len); key[0] != '\\0'; increment(key)) {\n char *crackhash = crypt(key, salt);\n ...\n }\n}\n</code></pre>\n\n<p>The call to <code>memset()</code> is used to set the initial value for the key. It sets the first <code>len</code> bytes of <code>key</code> to the value <code>'a'</code>. So with <code>len</code> being 1, this results in <code>key</code> becoming the string <code>\"a\"</code>. If len is 2, then <code>key</code> will become <code>\"aa\"</code>, and so on. It uses the fact that all the other bytes have already been initialized to zero by <code>char key[MAX_LEN + 1] = \"\"</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-13T05:46:56.820", "Id": "439056", "Score": "1", "body": "I don't know if this has a name. It's just for-loops. The only thing special is that the iterator variable is a string, and incrementing a string is just something you don't do often. Maybe it is analogous to https://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-14T21:25:51.407", "Id": "439324", "Score": "0", "body": "never seen MAX_LEN before, can you explain the usage in this context? It's giving errors." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-14T21:27:55.077", "Id": "439325", "Score": "1", "body": "It's just a placeholder for the maximum length of keys you want to test." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T01:34:51.413", "Id": "439692", "Score": "0", "body": "Can you articulate what's going on in the increment() function? It works, but this seems cryptic for someone new to CS and C. Also, can you explain the use of memset(key, 'a', len) in this context?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-06T20:45:16.450", "Id": "225687", "ParentId": "225432", "Score": "5" } } ]
{ "AcceptedAnswerId": "225687", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T20:00:11.220", "Id": "225432", "Score": "5", "Tags": [ "c", "search", "mergesort" ], "Title": "C-based hash matching cracker" }
225432
<p>The Folder struct definition below is given:</p> <pre><code>type Folder struct { ID int emailCount int childFolderIDs []int } </code></pre> <p>Description of the fields are:</p> <ul> <li><code>Id</code> : folder id </li> <li><code>emailCount</code> : number of emails in the folder </li> <li><code>childFolderIDS</code> : if the folder has subfolders, this list contains folder IDS of the subfolders. </li> </ul> <p>I am trying to write a function:</p> <ul> <li>Function is taking two parameters: <ul> <li>First parameter is a list of all folders in the email application <pre class="lang-golang prettyprint-override"><code> var folders = []Folder{ Folder{1, 30, []int{2, 4}}, Folder{2, 10, []int{3}}, Folder{4, 60, []int{}}, Folder{3, 20, []int{}}, } </code></pre></li> <li>Second parameter is folder id of a folder </li> </ul></li> <li>Function will return a total number of emails with ID=Folder Id and all of its children recursively.</li> </ul> <p>For example:</p> <p>If the second parameter is: </p> <ul> <li><p><strong>four</strong>, then the function should return <strong>60</strong> (there is no subfolder)</p></li> <li><p><strong>two</strong>, then the function should return <strong>30</strong></p></li> </ul> <p>My code is below:</p> <pre class="lang-golang prettyprint-override"><code> package main import "fmt" type Folder struct { ID int emailCount int childFolderIDs []int } func InsertIntoMap(data_arr []Folder) map[int]Folder { var retval = make(map[int]Folder) var child_folders []int for _, elem := range data_arr { child_folders = elem.childFolderIDs var folder Folder folder.ID = elem.ID folder.emailCount = elem.emailCount folder.childFolderIDs = child_folders retval[elem.ID] = folder } return retval } func GetTotalEmailCount(p_map map[int]Folder, folder_id int) int { total := 0 var child_folders []int child_folders = p_map[folder_id].childFolderIDs total = total + p_map[folder_id].emailCount if len(child_folders) == 0{ return total }else{ for e := range child_folders { return total + GetTotalEmailCount(p_map, child_folders[e]) } } return total } func main() { var folders = []Folder{ Folder{1, 30, []int{2, 4}}, Folder{2, 10, []int{3}}, Folder{4, 60, []int{}}, Folder{3, 20, []int{}}, } var m = InsertIntoMap(folders) fmt.Println(GetTotalEmailCount(m,1)) // result is 60 fmt.Println(GetTotalEmailCount(m,2)) // result is 30 fmt.Println(GetTotalEmailCount(m,3)) // result is 20 fmt.Println(GetTotalEmailCount(m,4)) // result is 60 } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T08:36:01.040", "Id": "437754", "Score": "1", "body": "Welcome to CodeReview. The indentation of your code is inconsistent, and part of your example (`Second parameter is:`) ended up in a code block. You may want to fix this before reviewing starts. (Code in the question shall stay unchanged conce you got answers. Or serious time passed since asking (- 24 hours?))" } ]
[ { "body": "<p>First, your code doesn't give correnct answers; for <code>(m, 1)</code> the answer should be 120 (30 in <code>./1</code>, +10 in <code>./1/2</code>, +20 in <code>./1/2/3</code>, +60 in <code>./1/4</code>; you never count more than a single entry in the sub-folder slice).</p>\n\n<p>Also, you should run <code>go fmt</code> (or <a href=\"https://golang.org/x/tools/cmd/goimports\" rel=\"nofollow noreferrer\"><code>goimports</code></a>) on your code (perhaps you did and that was lost when posting). Also, adding a <a href=\"https://play.golang.org/p/web83IsUyly\" rel=\"nofollow noreferrer\">Go Playground</a> link to your original code in posts is helpful.</p>\n\n<p>You mention that you wanted to create a function taking two parameters, the first being <code>[]Folder</code> but your code instead converts the slice into a map and uses that as the first argument. Which did you intend? When you have a function or functions that are answering questions based on an argument you could consider making a method. For example, perhaps something like:</p>\n\n<pre class=\"lang-golang prettyprint-override\"><code>type Folders []Folder\n// or\ntype Folders struct {\n list []Folder\n byID map[int]Folder\n}\n\nfunc (f Folders) EMailCount(folder int) int {\n // code that uses f and folder as arguments\n}\n</code></pre>\n\n<p>You use <code>snake_case</code> for some of your identifiers and <code>camelCase</code> for others; idiomatic Go code uses <code>camelCase</code> for all identifiers.</p>\n\n<p>In your <code>InsertIntoMap</code> function:</p>\n\n<ul>\n<li>When you <code>make</code> the map you know how many entries you expect so you should include that number to make as a size hint (e.g. <code>make(map[int]Folder, len(data))</code>). If the size is large this avoids the having to dynamically re-size the map as you add entries.</li>\n<li>You name the map <code>retval</code>, I'd instead name it based on what contains (a map of folders by ID) rather than it happens to be the return value. I'd call it just <code>m</code> or <code>byID</code>.</li>\n<li>Within the loop you effectively copy the element <code>elem</code> to the variable <code>folder</code>. You can do this with just <code>folder := elem</code> but at that point the entire loop body can just be rewritten as <code>retval[elem.ID] = elem</code>.</li>\n</ul>\n\n<p>In your <code>GetTotalEmailCount</code> function:</p>\n\n<ul>\n<li><p>Normally in Go instead of:</p>\n\n<pre><code>var foo []int\nfoo = something[bar].foo\n</code></pre>\n\n<p>you'll just see:</p>\n\n<pre><code>foo := something[bar].foo\n</code></pre>\n\n<p>not only is it shorter but it can make future code changes easier. In the latter if the field <code>foo</code> changes type you don't need to edit the type of the variable <code>foo</code> to match. (By the way, shorter isn't always better. Clarity is more important than conciseness).</p></li>\n<li><p>Idiomatic Go code tends avoid indenting code by using early returns (see <a href=\"https://github.com/golang/go/wiki/CodeReviewComments#indent-error-flow\" rel=\"nofollow noreferrer\">https://github.com/golang/go/wiki/CodeReviewComments#indent-error-flow</a>). You return if <code>len(…) == 0</code> so you should just drop the <code>else</code> clause and remove the indent (<a href=\"https://golang.org/x/lint/golint\" rel=\"nofollow noreferrer\"><code>golint</code></a> will suggest this). E.g, instead of:</p>\n\n<pre><code>if someCondition {\n return something\n} else {\n // other code\n // possibly with more conditional/loop indenting\n}\n</code></pre>\n\n<p>it would be:</p>\n\n<pre><code>if someCondition {\n return something\n}\n\n// other code\n// possibly with more conditional/loop indenting\n</code></pre></li>\n<li><p>In this specific case, you don't even need the conditional since <code>for range</code> loops don't do anything on empty/nil slices the following <code>return total</code> line is sufficient.</p></li>\n<li><p>It's in this <code>for</code> loop your your bug exists. On the first iteration you stop looping and return the total of this folder and it's first child without iterating to the next child.</p>\n\n<pre><code>return total + GetTotalEmailCount(p_map, child_folders[e])\n</code></pre>\n\n<p>should be:</p>\n\n<pre><code>total += GetTotalEmailCount(p_map, child_folders[e])\n</code></pre></li>\n</ul>\n\n<p>Without changing the basic structure of your code, all the above gives something like this (<a href=\"https://play.golang.org/p/_SLPYNTOwcu\" rel=\"nofollow noreferrer\">Go Playground</a>):</p>\n\n<pre class=\"lang-golang prettyprint-override\"><code>package main\n\nimport \"fmt\"\n\ntype Folder struct {\n ID int\n emailCount int\n childFolderIDs []int\n}\n\nfunc InsertIntoMap(data []Folder) map[int]Folder {\n m := make(map[int]Folder, len(data))\n for _, e := range data {\n m[e.ID] = e\n }\n return m\n}\n\nfunc GetTotalEmailCount(m map[int]Folder, folder int) int {\n children := m[folder].childFolderIDs\n total := m[folder].emailCount\n\n for e := range children {\n // BUG: doesn't detect infinite loops\n total += GetTotalEmailCount(m, children[e])\n }\n\n return total\n}\n\nfunc main() {\n var folders = []Folder{\n Folder{1, 30, []int{2, 4}},\n Folder{2, 10, []int{3}},\n Folder{4, 60, []int{}},\n Folder{3, 20, []int{}},\n }\n\n var m = InsertIntoMap(folders)\n fmt.Println(GetTotalEmailCount(m, 1)) // result is 120, 30+10+20+60\n fmt.Println(GetTotalEmailCount(m, 2)) // result is 30\n fmt.Println(GetTotalEmailCount(m, 3)) // result is 20\n fmt.Println(GetTotalEmailCount(m, 4)) // result is 60\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T13:15:50.563", "Id": "437796", "Score": "2", "body": "This was my first Go code. Thank you for your valuable comments." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T12:50:02.407", "Id": "225459", "ParentId": "225435", "Score": "2" } } ]
{ "AcceptedAnswerId": "225459", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T21:11:11.597", "Id": "225435", "Score": "4", "Tags": [ "beginner", "recursion", "go" ], "Title": "Find the total number of emails in a folder (with all of the subfolders)" }
225435
<p>Here's my approach to an extensible version of the FizzBuzz challenge in Swift (so one can add more numbers to be checked against other than just <code>3</code> and <code>5</code>).</p> <p>I initially tried using dictionaries but since they don't necessarily preserve the order of elements it could lead to <code>BuzzFizz</code> return values.</p> <p>I personally think that, while the program does work as expected, it isn't clear how it works. I mean, it's not as readable as I'd like it to be for doing such a simple task. </p> <p>How can I improve it?</p> <pre><code>func fizzBuzz (n: Int, responsesByMultiples: [(Int, String)] = [(3, "Fizz"), (5, "Buzz")]) -&gt; String { var result: String = "" for key in responsesByMultiples { let (multiple, response) = key, isMultiple: Bool = (n % multiple) == 0 if isMultiple { result += response } } return result == "" ? String(n) : result } for i in 1...100 { print(fizzBuzz(n: i)) } </code></pre>
[]
[ { "body": "<h1> Bright side</h1>\n\n<p>Your code gives the correct output and delivers on the premise of extensibility.</p>\n\n<h1> Suggestions</h1>\n\n<p>Here are some suggestions:</p>\n\n<ol>\n<li><p>The name <code>key</code> is a name that doesn't tell a lot about the nature of the tuple. If you feel that it is appropriate, that would conflict with <code>responsesByMultiples</code>. Then It would have made more sense for the latter to be named <code>keys</code>. Personally, I'd prefer to call <code>responses</code> or <code>rules</code>.</p></li>\n<li><p>These <em>rules</em> expressed by a tuple without labels is a little bit confusing. Better use a struct, or just add labels.</p></li>\n<li><p>You can easily decompose a tuple this way:</p>\n\n<pre><code>for (multiple, response) in responsesByMultiples {\n ...\n}\n</code></pre></li>\n<li><p>Calling the first element <code>multiple</code> is a little bit too optimistic (or pessimistic depending on the way you to see things), it presumes that there is a high probability that <code>n</code> is actually a multiple of <code>multiple</code>. It would make more sense to me to name the first element of the tuples <code>dividsor</code>.</p></li>\n<li><p><code>n</code> is a bit too generic, use <code>dividend</code> instead.</p></li>\n<li><p>You don't have to specify the type in <code>isMultiple: Bool</code>, type inference can do the job for you. Generally speaking, specifying the type can help in reducing the compile times, but in this case, it wouldn't make a difference.</p></li>\n<li><p>Instead of using <code>(n % multiple) == 0</code>, there is a nice <a href=\"https://github.com/apple/swift-evolution/blob/master/proposals/0225-binaryinteger-iseven-isodd-ismultiple.md\" rel=\"nofollow noreferrer\">syntax</a> in Swift 5 :</p>\n\n<pre><code>n.isMultiple(of: multiple)\n</code></pre>\n\n<p>(this syntax exacerbates the problem mentioned in 4.)</p></li>\n<li><p>To check that a String is empty, it is more efficient to check the <code>.isEmpty</code> property. <a href=\"https://tio.run/##tY/PSgQxDMbv8xRh8NCClgoeZNnByyp68rAPsNRpZzfQP0ObUZZlX93aVlnwLAYSQki@75f0gRPdZXRziARPYfFaEQafrSFQMaojDMCkEOvbnZSyJhdOzXCCHaDv4Cc2YXmzRkTldXAM/QraDYd1ae7hAfoeVrCliH7P@mdjbehFOizTZI1mnDehc9fpAKfWV/9EqkANsFFkGL@Mo0mLrfPGJya0ZGIBupIwDNXofFk1Xv@@b2UuFMS@ZcRYfqbruikInXnxRexd2S360bBGUOj@TCYwPbqZjv/BlvPnOFm1T/nm9Qs\" rel=\"nofollow noreferrer\">Here</a> is a benchmark that confirms it:</p>\n\n<pre><code>import Foundation\n\nlet array = (0..&lt;1_000_000).map { _ in\n Double.random(in: 0..&lt;1) &lt; 0.8 ? \"\" : String(\"Hello\".shuffled())\n}\n\ndo {\n let start = Date()\n let result = array.filter { $0 == \"\" }\n let end = Date()\n\n print(result.count, end.timeIntervalSince(start))\n}\n\ndo {\n let start = Date()\n let result = array.filter { $0.isEmpty }\n let end = Date()\n\n print(result.count, end.timeIntervalSince(start))\n}\n</code></pre>\n\n<p>The execution times are respectively <code>44ms</code> and <code>34ms</code>.</p></li>\n</ol>\n\n<h1> Putting it all together ❤️</h1>\n\n<p>Here a version of your code that takes the previous points into account :</p>\n\n<pre><code>func fizzBuzz (\n number dividend: Int,\n rules: [(Int, String)] = [(3, \"Fizz\"), (5, \"Buzz\")]\n ) -&gt; String {\n\n var result: String = \"\"\n\n for (divider, response) in rules\n where dividend.isMultiple(of: divider) {\n result += response\n }\n\n return result.isEmpty ? String(dividend) : result\n}\n</code></pre>\n\n<h1> Further reading</h1>\n\n<p>You can find many implementations of this classic question on Code Review. <a href=\"https://codereview.stackexchange.com/q/91663/49921\">Here</a> is a quite informative one.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T00:38:57.113", "Id": "437723", "Score": "1", "body": "Damn that is a very well formatted answer! I agree with every point on the list, except maybe #6 because I personally like using explicit typing. Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T00:23:59.920", "Id": "225439", "ParentId": "225438", "Score": "4" } } ]
{ "AcceptedAnswerId": "225439", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-02T22:52:49.987", "Id": "225438", "Score": "2", "Tags": [ "swift", "fizzbuzz" ], "Title": "FizzBuzz with more parameters in Swift" }
225438
<p>Recently I was reading a book called <strong>Code Complete</strong> by Steve McConnell and I came across a chapter called The <strong>PseudoCode Programming Process(PPP)</strong> where the chapter taught me on how to write <strong>Pseudo code</strong> and gave guidelines on how to convert that pseudo code to <strong>real code</strong>. That chapter inspired me a lot and I decided to follow that technique for writing all of my code. Inspired from the example given in the book I tried to write a simple routine that nearly follows those guidelines. Can you guys help me out on whether I am going in the right direction after looking the code below. </p> <p>Here is the Pseudo code and real code that I wrote for a function called <code>getErrorLocation</code> that basically returns the coordinates of where the error occurred in a piece of code while parsing it.</p> <p>Pseudo Code:</p> <pre class="lang-none prettyprint-override"><code>This routine outputs coordinate of error location found in gml code in x/80 format based on the startlocation and currentlocation as supplied by the calling routine. Also it outputs a error state indicating whether the operation was successful or not. Set default value of error to FAIL *Precondition IF currentlocation&lt;startlocation return FAIL Calculate distance by subtracting currentlocation from startlocation Divide distance by 80 and set the rownumber and colnumber to quotient and remainder of the division result respectively. Set errorstate to SUCCESS return coordinate with errorstate </code></pre> <p>Here is the C++ code written from the Pseudo Code given above</p> <pre><code>#include&lt;iostream&gt; #include&lt;cstdlib&gt; struct Point { int x; int y; }; /*This routine outputs coordinate of error location found in gml code in x/80 format based on the startlocation and currentlocation as supplied by the calling routine. Also it outputs a error state indicating whether the operation was successful or not.*/ template&lt;typename Iter&gt; std::pair&lt;Point, bool&gt;getErrorLocation(Iter locationcurrent, Iter locationstart) { //Set default value of errorstate to FAIL bool error = true; //*Precondition //IF currentlocation&lt;startlocation if (locationcurrent &lt; locationstart) // return FAIL return { {0,0},error }; //Calculate distance by subtracting currentlocation from startlocation int distance = locationcurrent - locationstart; //Divide distance by 80 and set the rownumber and colnumber to quotient and remainder of the division result respectively. auto [rownum, colnum] = div(distance, 80); //Set errorstate to SUCCESS error = false; //return coordinate with errorstate return { {rownum,colnum},error }; } </code></pre> <p>The main thing I want to highlight here are the comments that were actually the Pseudo code itself. I read in <strong>Clean Code</strong> by Robert C Martin that comments are harmful for the code and must be used to the minimum. I clearly understand why they are harmful, but I like this method also. Advantages weigh more I think for comments rather than their disadvantages. I feel like writing comments helps novices like me to understand the idea in the first glance itself rather than digging into the technical details and figuring out the code's real purpose. So now I am in a complete dilemma. There are contradictory statements from two of my favorite books. </p> <p>What should I do? </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T08:51:21.047", "Id": "437759", "Score": "0", "body": "Welcome to code review! Form an opinion by reading code (including yours from years ago) and pondering whether existing comments where harmful or helpful. Try identify places where you missed comments and think up ones that would make a real difference and stand a chance of staying helpful when the code gets modified." } ]
[ { "body": "<p>Writing psuedo-code first, then turning it into code is great. However, we should then delete the pseudo-code.</p>\n\n<p>The problem with comments like this is that they mainly just repeat the code. If we need a comment to explain <em>what</em> the code does, we should make the code clearer instead. Comments that explain <em>why</em> the code does something the way it does are more helpful.</p>\n\n<p>Note also that if we change the code in the future, we would have to update all these comments too, which is twice the work.</p>\n\n<p>Comments for documentation purposes tend to be structured according to the documentation tool in use (e.g. short description, purpose of arguments, return values, etc.). However, they are probably unnecessary for a small function that will be used internally in a project.</p>\n\n<hr>\n\n<p>Some issues with the code:</p>\n\n<ul>\n<li><p>Do we ever really expect <code>locationStart</code> to be after <code>locationCurrent</code>? Perhaps an assertion, or an exception would be more appropriate.</p></li>\n<li><p>Otherwise <code>std::optional</code> would be a better choice for the return value.</p></li>\n<li><p>We should use appropriate types for indexing. If the range of indices for <code>Iter</code> cannot be negative, and needs to cover the range of a standard container (e.g. <code>std::string</code>), we should use <code>std::size_t</code>, not <code>int</code>.</p></li>\n<li><p>It's probably clearer to use the divide and remainder operators directly, instead of <code>std::div</code> (if that's what <code>div</code> is). Note that <code>std::div</code>, <code>std::ldiv</code>, and <code>std::lldiv</code> all use signed integer types, which probably don't cover the appropriate range.</p></li>\n<li><p>The local <code>error</code> variable is unnecessary.</p></li>\n<li><p>What is <code>80</code>? Perhaps this should be a function argument (or at least a named constant).</p></li>\n<li><p>We can be more consistent with naming. (The function is <code>getErrorPosition</code>, but we're returning a <code>Point</code>. Perhaps <code>CharacterPosition</code> would be a better name than <code>Point</code>).</p></li>\n<li><p>Although it's called <code>getErrorPosition</code>, this function is not specific to errors - it just gets the character position from the iterators. If we give it a more general name, then we can use it for other things too.</p></li>\n</ul>\n\n<hr>\n\n<p>So I'd suggest something like this (though the doc comments are probably not needed):</p>\n\n<pre><code>#include &lt;cassert&gt;\n#include &lt;cstdlib&gt;\n#include &lt;iterator&gt;\n\nstruct CharacterPosition\n{\n std::size_t row;\n std::size_t column;\n};\n\n/// \\brief Returns the character position (row / column) from its index.\n/// \\param index The distance of the character from start of the document.\n/// \\param lineLength The line length of the document (all lines must be this length for the returned character position to be correct).\n/// \\return Row and column of the character.\nCharacterPosition getCharacterPosition(std::size_t index, std::size_t lineLength)\n{\n return { index / lineLength, index % lineLength };\n}\n\n/// \\brief Returns the character position (row / column) from its iterator position.\n/// \\param start An iterator pointing to the first character of the document.\n/// \\param current An iterator pointing to the current character (for which we will return the position).\n/// \\param lineLength The line length of the document (all lines must be this length for the returned character position to be correct).\n/// \\return Row and column of the character.\n/// \\pre The current iterator must not be positioned before the start iterator\ntemplate&lt;typename Iter&gt;\nCharacterPosition getCharacterPosition(Iter start, Iter current, std::size_t lineLength)\n{\n assert(start &lt;= current);\n\n auto distance = std::distance(start, current);\n\n return getCharacterPosition(distance, lineLength);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T09:03:05.050", "Id": "437760", "Score": "0", "body": "Sir you are exactly right!!! The routine that you wrote now is much more easily understandable and short. Extremely Thankyou for the help" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T07:41:19.373", "Id": "225448", "ParentId": "225440", "Score": "3" } } ]
{ "AcceptedAnswerId": "225448", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T04:32:44.197", "Id": "225440", "Score": "4", "Tags": [ "c++" ], "Title": "errorlocation() routine, implemented in C++ based on pseudocode" }
225440
<p>My goal with this snippet is to create an array of coordinates which in turn is a tuple of 68 elements, area and modified area array for all 10k elements and assign it to the <code>df</code> column.</p> <ul> <li>Running the complete code results in 5.3, 4.8, 4.6, 4.5 seconds. </li> </ul> <pre class="lang-py prettyprint-override"><code>#%% arrayc = [] #array for array of coordinates areaAr = [] #area type 1 modifiedarea = [] #area type 2 ts = time.time() for i in range(10708): #number of files f = open(df["filepath"][i], "r") #df has column of filepaths x,y = [], [] for l in f: row = l.split() x.append(int(float(row[0]))) #68 pairs are of kind 3.82382323e+02 4.563524234e+02. y.append(int(float(row[1]))) #I am taking int rounded off to three digits. arrayc.append((x,y)) f.close() #x= arrayc[i][0] #y = arrayc[i][1] areaAr.append(PolyArea(x[36:41],y[36:41])) distance = max(np.abs(x[36]-x[39]),np.abs(x[42]-x[45])) modifiedarea.append((PolyArea(x[36:41],y[36:41]))/distance) te = time.time() print(-ts+te) def PolyArea(x,y): return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1))) </code></pre> <p>How can I minimise the execution time ? </p> <p>Updates: </p> <ul> <li>File generator code:</li> </ul> <pre class="lang-py prettyprint-override"><code>import numpy as np filepath = [] root = '~/Desktop/test/' for i in range(10): for j in range(68): numx = ( np.random.randint(100,200)) numy = np.random.randint(100,200) f = open(root + str(i) + ".txt","a") f.write(str(numx) + " " + str(numy) + "\n") </code></pre> <ul> <li>The numbers 36 41 etc are the coordinates of the polygon of interest on the image. It is fixed that the polygon will always be marked by these coordinates. </li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T08:45:45.597", "Id": "437758", "Score": "0", "body": "Welcome to CodeReview. Your timings include I/O, which is notoriously difficult to do in an unbiased way. Opening (and, to a lesser extent, reading & closing) a legion of files is going to take its time, sweet or not. Did you repeat the measurement for the first case immediately following one of the others?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T09:30:34.033", "Id": "437762", "Score": "0", "body": "@greybeard I am currently running the different tests on terminal, instead of integrated jupyter. Can you clarify which order should I run them in? I can do the same in Jupyter if it matters. But the order first. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T10:45:11.367", "Id": "437773", "Score": "0", "body": "The order *should* be almost immaterial. Running from an empty block&file cache as opposed to a primed one *may* make all of a difference: in an automated way, do each of the approaches in turn, about seven \"turns\". Put the first runs aside and have a look on the variance of the remaining readings." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T11:11:38.143", "Id": "437777", "Score": "0", "body": "@greybeard the runtimes are more consistent now. My laptop was under load when I ran the 21 seconds etc tests. A lot of apps were running, jupyter GUI was also less responsive and had a lag. Had to put laptop to sleep, freed up some space and restarted VScode and now the readings are,: around 1 second for area calculations, around 2 -3 for landmarks and total being 4-5, in both Terminal and Jupyter. For minute details, see if anything can be changed in the code itself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T11:23:30.633", "Id": "437778", "Score": "1", "body": "Please see [What (not) to do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) and roll back any changes to the code presented." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T11:27:08.677", "Id": "437780", "Score": "2", "body": "\"The low-hanging fruits\" are not handling a lot of files and not doing things over (like the duplicated call to `PolyArea()` [Georgy spotted](https://codereview.stackexchange.com/a/225450/93149), too)." } ]
[ { "body": "<p>I couldn't run your code, so I can't say how much faster the following will be.</p>\n\n<p>My suggestion is to use NumPy's <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html\" rel=\"nofollow noreferrer\"><code>loadtxt</code></a> function to get the array of the necessary coordinates. With this function, you can specify <code>skiprows</code> and <code>max_rows</code> parameters to get the necessary rows, 36-45. This should be more efficient than reading all the file in memory. </p>\n\n<p>Here:</p>\n\n<blockquote>\n<pre><code>areaAr.append(PolyArea(x[36:41],y[36:41])) \ndistance = max(np.abs(x[36]-x[39]),np.abs(x[42]-x[45]))\nmodifiedarea.append((PolyArea(x[36:41],y[36:41]))/distance) \n</code></pre>\n</blockquote>\n\n<p>you calculate <code>PolyArea</code> two times, but it is enough to calculate it only once and then reuse the result. </p>\n\n<p>The final code could lool like this:</p>\n\n<pre><code>for filepath in df['filepath'].iloc[:10708]:\n values = np.loadtxt(filepath, \n skiprows=35,\n max_rows=10)\n x = values[:, 0]\n y = values[:, 1]\n area = PolyArea(x[:5], y[:5])\n areaAr.append(area)\n distance = max(np.abs(x[0] - x[3]), np.abs(x[6] - x[9]))\n modifiedarea.append(area / distance) \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T10:45:50.060", "Id": "225450", "ParentId": "225442", "Score": "2" } }, { "body": "<p>For the same PolyArea function, Priority order goes like this: </p>\n\n<p>Order of milliseconds.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>\ndef PolyArea(urll):\n values = np.loadtxt(urll, skiprows=35, max_rows=10)\n x = values[:,0]\n y = values[:,1]\n x = x[:5]\n y = y[:5] \n return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1)))\n\ndf[\"areaAr\"] = PolyArea(df['filepath'].all())\n</code></pre>\n\n<p>The above method is fastest that I tried. Below is another with order of single digit seconds.</p>\n\n<pre><code>def PolyArea(urll):\n values = np.loadtxt(urll, skiprows=35, max_rows=10)\n x = values[:,0]\n y = values[:,1]\n x = x[:5]\n y = y[:5] \n return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1)))\n\ndf[\"areaAr\"] = df.apply(lambda row: PolyArea(row['filepath']), axis=1)\n</code></pre>\n\n<p>Below is another moderate method. Still better than crude iteration which goes double digit. </p>\n\n<pre><code>def PolyArea(urll):\n values = np.loadtxt(urll, skiprows=35, max_rows=10)\n x = values[:,0]\n y = values[:,1]\n x = x[:5]\n y = y[:5] \n return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1)))\nfor index,row in df.iterrows():\n areaAr.append(PolyArea(row[\"filepath\"]))\n</code></pre>\n\n<p>Source, Medium blog: <a href=\"https://engineering.upside.com/a-beginners-guide-to-optimizing-pandas-code-for-speed-c09ef2c6a4d6\" rel=\"nofollow noreferrer\">https://engineering.upside.com/a-beginners-guide-to-optimizing-pandas-code-for-speed-c09ef2c6a4d6</a> \n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T17:00:27.943", "Id": "437825", "Score": "0", "body": "The first code looks strange. [`pd.Series.all`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.all.html) returns `True` or `False`, so I'm not sure how you managed to run it without getting an error. The difference in time between the second and the third code, AFAIK, should be minimal as `apply` also runs a loop under the hood." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T17:03:59.417", "Id": "437828", "Score": "0", "body": "@Georgy yes, first one is troubling. I didn't verify after I used the `.all`. I meant to do something like `df[\"areaAr\"] = PolyArea(df['landmarkpath'])` but got `The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()`. Ik it's offtopic, but I would appreciate directions/edits. I should have taken care of series in `PolyArea` function. Since all other use loops, only this is different." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T17:30:46.707", "Id": "437832", "Score": "1", "body": "Unfortunately, I don't have experience of improving performance further than what you have right now. I don't think you can squeeze more out of NumPy or pandas here. For some directions, take a look at [Dask](https://docs.dask.org/en/latest/) and [Numba](https://numba.pydata.org/), or try out [PyPy](https://pypy.org/). I've never tested them myself though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-04T01:58:05.443", "Id": "437867", "Score": "0", "body": "Regrettably, I'm out of my depth, here." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T13:10:01.900", "Id": "225460", "ParentId": "225442", "Score": "0" } } ]
{ "AcceptedAnswerId": "225450", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T05:24:51.243", "Id": "225442", "Score": "0", "Tags": [ "python", "python-3.x", "time-limit-exceeded", "numpy", "computational-geometry" ], "Title": "Read coordinates from many files and calculate polygon areas" }
225442
<p>I am currently developing a framework to facilitate writing controller programs for scientific instruments. I use <code>attrs</code> extensively in the internal parts of the code. I have some parts of the code which exposes classes to be derived from, but I don't want to call <code>@attr.s</code> in the beginning whenever I derive a class. I have an ad-hoc solution, but I would like to know if this decision will give me headaches on the way.</p> <p>I am using a metaclass when declaring the base class to be further derived from. I use the <code>__new__</code> of the metaclass to decorate the base class.</p> <p>Here is a stripped down version of my code:</p> <pre><code>import typing as t import attr def setting( unit: str = "", nicename: t.Optional[str] = None, default: t.Optional[t.Any] = None): """Returns a setting attribute field to be used in InstrumentSettings derived classes. Args: nicename: (optional) A unique nice name for referring to the setting in texts. """ metadata = dict( metatype='setting', unit=unit, nicename=nicename) return attr.ib(metadata=metadata, default=default) class _InstrumentSettingsMeta(type): def __new__(cls, clsname, supers, attrdict): newcls = super().__new__(cls, clsname, supers, attrdict) decorated = attr.s(auto_attribs=True)(newcls) return decorated class InstrumentSettings(metaclass=_InstrumentSettingsMeta): pass # Usage class FooSettings(InstrumentSettings): bar: int = setting(default=1) foosettings = FooSettings() </code></pre> <p>So the above implementation gives the correct behavior as <code>FooSettings</code> is perfectly <code>attrs</code> decorated. The thing is that I don't really wanna fiddle with metaclasses because I don't think I fully grok them. I would appreciate very much if someone could state the downsides &amp; upsides to my approach. I am also open to other suggestions.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T08:39:12.807", "Id": "437756", "Score": "2", "body": "Welcome to CodeReview! Be careful when *stripping down code*: [we need to see real, concrete code, and understand the context in which the code is used](https://codereview.stackexchange.com/help/on-topic)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T05:30:48.343", "Id": "225443", "Score": "1", "Tags": [ "python", "python-3.x", "object-oriented", "meta-programming" ], "Title": "Using metaclass to decorate derived classes to be `attrs` classes" }
225443
<p>I am working on a NodeJS port listener code that listens to a particular TCP port on the server. The obtaining the data from the port, the data is split using a delimited (for instance comma <code>,</code>) and inserts this data into the MySQL database.</p> <p>I have written the code and I was successfully able to insert data into MySQL server. My issue is that the process is consuming more CPU than expected.</p> <p>For instance, I ran the code on a 2 core 4 GB RAM Linux Server. The process consumes about 25-50% CPU when only one packet is received every 60 secs. The project should be able to listen to at least 00 packets of data per second on this configuration.</p> <pre><code>var net = require('net'); var mysql = require('mysql'); var PORT = 5000; net.createServer(function(sock) { console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort); sock.on('data', function(data) { console.log('DATA ' + sock.remoteAddress + ': ' + data); var dataArray = data.toString().split(','); var pool = mysql.createPool({ host: hostname, user: "abc", password: "123", database: "abc", connectionLimit:100 }); console.log("Connected!"); var sql = "INSERT INTO `table`(`val1`, `val2`, `val3`, `val4`, `val5`, `val6`) VALUES ('1','"+dataArray[6]+"','"+dataArray[10]+"','"+dataArray[9]+"','"+dataArray[11]+"','"+dataArray[13]+"')"; console.log(sql); pool.getConnection(function(err, connection) { if (err) throw err; connection.query(sql, function (err, result) { connection.release() if (err) throw err; console.log("Data Inserted into Table1"); }); var sql = "INSERT INTO `table2`(`datafield`) VALUES ('"+data+"')"; console.log(sql); pool.getConnection(function(err, connection) { if (err) throw err; connection.query(sql, function (err, result) { connection.release() if (err) throw err; console.log("Data Inserted into Table2"); }); sock.write('You said "' + data + '"'); connection.release(); }); sock.on('close', function(data) { console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort); }); }).listen(PORT); console.log('Server listening on '+ PORT); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T06:33:53.380", "Id": "437738", "Score": "0", "body": "Please take care to format your code correctly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T06:42:44.227", "Id": "437739", "Score": "0", "body": "I have removed the ` from the code, which I think was the issue with the format." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T06:44:24.977", "Id": "437740", "Score": "0", "body": "Also do you need all those bloating empty lines?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T06:52:10.083", "Id": "437741", "Score": "0", "body": "Not Necessarily. It can be removed, not an issue. But do you have a solution to the issue I face? How can we optimized the solution for lesser CPU consumption?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T08:17:08.157", "Id": "437750", "Score": "0", "body": "Your code is not complete both `net.createServer` and `sock.on` do not close! I've attempted to correct this and other minor formatting issues so that everyone can read your intent... have ya by chance looked into `async` and `await`? ... I've a feeling that such _syntactic sugar_ might be a _treat_ for making the code a bit more responsive." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T09:56:13.180", "Id": "437767", "Score": "0", "body": "Thank you S0AndS0. Yes that was a mistake. I had opened connections each time data was listened to. I have fixed the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T09:57:32.100", "Id": "437768", "Score": "0", "body": "But that doesn't solve my issue completely. I am not able to get maximized CPU utilization. With only 1 packet being send every 30 seconds, my CPU utilization shouldn't be more than 1 percent." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T13:36:10.833", "Id": "437798", "Score": "0", "body": "_sock.on('data'_ and _net.createServer_ are not closed." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T06:31:42.720", "Id": "225446", "Score": "1", "Tags": [ "javascript", "mysql", "node.js" ], "Title": "Optimizing Node MySQL Query for CPU Utilization" }
225446
<p>I have a tableview which shows a list of objects called Requests. It has 3 segments. Namely <strong>Accepted</strong>, <strong>Received</strong> and <strong>Sent</strong>. And the objects for each segment are in 3 arrays.</p> <p><a href="https://i.stack.imgur.com/W5pXkm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/W5pXkm.jpg" alt="enter image description here"></a></p> <p>I want to enable deleting rows (in turn the objects) <em>only</em> for <strong>Accepted</strong> and <strong>Sent</strong> segments.</p> <p><a href="https://i.stack.imgur.com/45dOWm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/45dOWm.jpg" alt="enter image description here"></a></p> <p>This is my current implementation.</p> <pre><code>func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -&gt; UISwipeActionsConfiguration? { var deleteAction: UIContextualAction? switch currentShowingStatus { case .accepted: deleteAction = UIContextualAction(style: .destructive, title: "Delete") { action, view, completionHandler in let request = self.acceptedRequests[indexPath.row] completionHandler(true) } case .sent: deleteAction = UIContextualAction(style: .destructive, title: "Delete") { action, view, completionHandler in let request = self.sentRequests[indexPath.row] completionHandler(true) } default: break } if let deleteAction = deleteAction { let configuration = UISwipeActionsConfiguration(actions: [deleteAction]) configuration.performsFirstActionWithFullSwipe = false return configuration } else { return UISwipeActionsConfiguration(actions: []) } } </code></pre> <p>As you can see there is quite a bit of duplicating code. And I can't extract away the <code>UIContextualAction</code> declaration part because of it's completion handler. Selecting the object to be deleted happens in there.</p> <p>I also can't define <code>UISwipeActionsConfiguration</code> as a local variable and reduce its duplicating due to that class must be initialized with <code>UIContextualAction</code> instances.</p> <p><strong>Note</strong>: You have to pass an empty actions array to <code>UISwipeActionsConfiguration</code> in order to <em>not</em> show the swipe actions in cell. Returning <code>nil</code> doesn't do it.</p> <p>So all this has produced an ugly piece of code. I'm wondering if there's a better way to refactor this.</p> <hr> <p><strong>Alternative Approach</strong></p> <p>Instead of checking for segment first and then adding multiple delete actions, I put the checking for segment part inside one completion handler like this.</p> <pre><code>func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -&gt; UISwipeActionsConfiguration? { var actions = [UIContextualAction]() let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { action, view, completionHandler in switch self.currentShowingStatus { case .accepted: let request = self.acceptedRequests[indexPath.row] self.deleteClientRequest(request) case .sent: let request = self.sentRequests[indexPath.row] self.deleteClientRequest(request) default: break } completionHandler(true) } switch currentShowingStatus { case .accepted, .sent: actions.append(deleteAction) case .received: actions.removeAll() } let configuration = UISwipeActionsConfiguration(actions: actions) configuration.performsFirstActionWithFullSwipe = false return configuration } </code></pre> <p>The downside is I still have to check for segment <em>again</em> in order to show the swipe action for just the <strong>Accepted</strong> and <strong>Sent</strong> segments.</p>
[]
[ { "body": "<p>In your first implementation you can make <code>deleteAction</code> a <em>constant</em> if you initialize it in all cases of the switch-statement:</p>\n\n<pre><code> let deleteAction: UIContextualAction?\n switch currentShowingStatus {\n case .accepted:\n deleteAction = UIContextualAction(...)\n case .sent:\n deleteAction = UIContextualAction(...)\n case .received:\n deleteAction = nil\n }\n</code></pre>\n\n<p>That makes it clear that the variable is initialized exactly once before used. I would also replace <code>default:</code> by the explicit <code>case received:</code>. That makes it obvious to reader in which case no swipe action is configured (without looking up the enum definition) and forces you to update the code if more cases are added.</p>\n\n<p>The double definition of <code>UISwipeActionsConfiguration</code> could be avoided by initializing the <em>array</em> of actions instead:</p>\n\n<pre><code> let actions: [UIContextualAction]\n switch currentShowingStatus {\n case .accepted:\n actions = [UIContextualAction(...)]\n case .sent:\n actions = [UIContextualAction(...)]\n default:\n actions = []\n }\n\n let configuration = UISwipeActionsConfiguration(actions: actions)\n configuration.performsFirstActionWithFullSwipe = false\n return configuration\n</code></pre>\n\n<p>It remains the code duplication for <code>UIContextualAction</code> though.</p>\n\n<p>In your alternative approach you append or remove elements from the <code>actions</code> array. But that array is initially empty. Similarly as above, you can simplify it to</p>\n\n<pre><code> let deleteAction = ...\n\n let actions: [UIContextualAction]\n switch currentShowingStatus {\n case .accepted, .sent:\n actions = [deleteAction]\n case .received:\n actions = []\n }\n</code></pre>\n\n<p>But – as you noticed – you have to evaluate <code>self.currentShowingStatus</code> inside the closure again. I would avoid that for an additional reason: You are relying on the fact that the status has not changed when the closure is <em>executed.</em></p>\n\n<p>The code duplication for <code>UIContextualAction</code> can be avoided if you initialize the <em>request</em> first:</p>\n\n<pre><code> let request: Request?\n switch currentShowingStatus {\n case .accepted:\n request = self.acceptedRequests[indexPath.row]\n case .sent:\n request = self.sentRequests[indexPath.row]\n case .received:\n request = nil\n }\n\n if let request = request {\n let deleteAction = UIContextualAction(style: .destructive, title: \"Delete\") {\n _, _, completionHandler in\n self.deleteClientRequest(request)\n completionHandler(true)\n }\n let configuration = UISwipeActionsConfiguration(actions: [deleteAction])\n configuration.performsFirstActionWithFullSwipe = false\n return configuration\n } else {\n return UISwipeActionsConfiguration(actions: [])\n }\n</code></pre>\n\n<p>Note also that unused closure parameters can be replaced by the wildcard parameter <code>_</code>. </p>\n\n<p>I would probably leave it like that, but of course you can combine the techniques:</p>\n\n<pre><code> let request: Request?\n switch currentShowingStatus {\n case .accepted:\n request = self.acceptedRequests[indexPath.row]\n case .sent:\n request = self.sentRequests[indexPath.row]\n case .received:\n request = nil\n }\n\n let actions: [UIContextualAction]\n if let request = request {\n actions = [UIContextualAction(style: .destructive, title: \"Delete\") {\n _, _, completionHandler in\n self.deleteClientRequest(request)\n completionHandler(true)\n }]\n } else {\n actions = []\n }\n\n let configuration = UISwipeActionsConfiguration(actions: actions)\n configuration.performsFirstActionWithFullSwipe = false\n return configuration\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-05T05:42:44.483", "Id": "437982", "Score": "0", "body": "Thanks Martin, for the very detailed answer. This looks much cleaner and concise." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-04T17:11:34.907", "Id": "225535", "ParentId": "225447", "Score": "2" } } ]
{ "AcceptedAnswerId": "225535", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T06:44:34.493", "Id": "225447", "Score": "3", "Tags": [ "comparative-review", "swift", "ios", "cocoa" ], "Title": "UITableView allowing some kinds of requests to be deleted with swipe gestures" }
225447
<p>Here's the problem at hand:</p> <blockquote> <p>2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?</p> </blockquote> <p>Here's the code Ive written to solve it:</p> <pre class="lang-py prettyprint-override"><code>from math import sqrt def prime_factorization(n: int) -&gt; dict: ''' Returns a dict with the prime factorization of the integer n, where the keys of the dict are the prime numbers and the values are the powers in the factorization for the appropriate prime number key. :param n: an integer we want to compute he's prime factorization ''' prime_dict = {} # dealing with even prime numbers - e.g. 2 while n % 2 == 0: if 2 not in prime_dict: prime_dict[2] = 0 prime_dict[2] += 1 n = n // 2 # dealing with odd numbers upper_bound = int(sqrt(n)) for i in range(3,upper_bound+1): while n % i == 0: if i not in prime_dict: prime_dict[i] = 0 prime_dict[i] += 1 n = n // i # In case n is prime by itself if n &gt; 1: prime_dict[n] = 1 return prime_dict def smallest_dividable_num(n:int) -&gt; int: ''' Returns the smallest integer whose dividable by all the numbers from 1 to n. :param n: an integer upper bound which we want to compute the smallest divisable num from 1 to it. ''' prime_dict = {} for i in range(1,n+1): tmp_dict = prime_factorization(i) for k,_ in tmp_dict.items(): if k not in prime_dict or prime_dict[k] &lt; tmp_dict[k]: prime_dict[k] = tmp_dict[k] res = 1 for k,v in prime_dict.items(): res = res*(k**v) return res </code></pre> <p>And here's a small test case Ive written for this code:</p> <pre class="lang-py prettyprint-override"><code>from ProjectEuler.problem5 import smallest_dividable_num if __name__ == "__main__": # The prime factorization is {2**3,3**2,5,7} -&gt; returns 2520 print(smallest_dividable_num(10)) # The prime factorization is {2**2,3,5} -&gt; returns 60 print(smallest_dividable_num(6)) # The prime factorization is {2**4,3**2,5,7,11,13,17,19} -&gt; returns 232792560 print(smallest_dividable_num(20)) </code></pre> <p>Let me know your thoughts about my solution. thanks :)</p>
[]
[ { "body": "<p><strong>Handling values not in dict in <code>prime_factorization</code></strong></p>\n\n<p>In 2 places in <code>prime_factorization</code>, we end up performing dictionnary lookup to set the default value 0 when needed.</p>\n\n<p>There are various other ways to do so:</p>\n\n<p>We could use a variable to store the coefficient for the current divisor:</p>\n\n<pre><code> # dealing with even prime numbers - e.g. 2\n d = 2\n coef = 0\n while n % d == 0:\n coef += 1\n n = n // d\n if coef:\n prime_dict[d] = coef\n\n # dealing with odd numbers\n for d in range(3, int(sqrt(n))+1):\n coef = 0\n while n % d == 0:\n coef += 1\n n = n // d\n if coef:\n prime_dict[d] = coef\n</code></pre>\n\n<p>(Note that <code>if coef</code> is not required if we do not mind having 0s in our dictionnary).</p>\n\n<p>An alternative could be to use an appropriate data structure.</p>\n\n<pre><code>import collections\n\ndef prime_factorization(n: int) -&gt; dict:\n '''\n Returns a dict with the prime factorization of the integer n, where the keys of the dict are the prime numbers\n and the values are the powers in the factorization for the appropriate prime number key.\n :param n: an integer we want to compute he's prime factorization\n '''\n prime_dict = collections.defaultdict(int)\n\n # dealing with even prime numbers - e.g. 2\n d = 2\n while n % d == 0:\n prime_dict[d] += 1\n n = n // d\n\n # dealing with odd numbers\n for d in range(3, int(sqrt(n))+1):\n while n % d == 0:\n prime_dict[d] += 1\n n = n // d\n</code></pre>\n\n<p>Or a Counter:</p>\n\n<pre><code>import collections\n\ndef prime_factorization(n: int) -&gt; dict:\n '''\n Returns a dict with the prime factorization of the integer n, where the keys of the dict are the prime numbers\n and the values are the powers in the factorization for the appropriate prime number key.\n :param n: an integer we want to compute he's prime factorization\n '''\n prime_dict = collections.Counter()\n\n # dealing with even prime numbers - e.g. 2\n d = 2\n while n % d == 0:\n prime_dict[d] += 1\n n = n // d\n\n # dealing with odd numbers\n for d in range(3, int(sqrt(n))+1):\n while n % d == 0:\n prime_dict[d] += 1\n n = n // d\n</code></pre>\n\n<p>However, my preference is to completely split the concerns between the logic generating the prime divisors and the one counting them. Using a generator, we can get something like:</p>\n\n<pre><code>import collections\n\ndef yield_prime_factors(n: int):\n '''Yield prime factors.'''\n d = 2\n while n % d == 0:\n yield d\n n = n // d\n\n # dealing with odd numbers\n for d in range(3, int(sqrt(n))+1):\n while n % d == 0:\n yield d\n n = n // d\n\n # In case n is prime by itself\n if n &gt; 1:\n yield n\n\n\ndef prime_factorization(n: int) -&gt; dict:\n '''\n Returns a dict with the prime factorization of the integer n, where the keys of the dict are the prime numbers\n and the values are the powers in the factorization for the appropriate prime number key.\n :param n: an integer we want to compute he's prime factorization\n '''\n return collections.Counter(yield_prime_factors(n))\n</code></pre>\n\n<p><strong>Iterating over keys and values in <code>smallest_dividable_num</code></strong></p>\n\n<p>You use <code>for k,_ in tmp_dict.items()</code> which dumps the values from the dict and use <code>tmp_dict[k]</code> which gets the values from the dict.</p>\n\n<p>You could as well just write:</p>\n\n<pre><code> tmp_dict = prime_factorization(i)\n for k, v in tmp_dict.items():\n if k not in prime_dict or prime_dict[k] &lt; v:\n prime_dict[k] = v\n</code></pre>\n\n<p>which can also be written:</p>\n\n<pre><code> for k, v in prime_factorization(i).items():\n if k not in prime_dict or prime_dict[k] &lt; v:\n prime_dict[k] = v\n</code></pre>\n\n<p><strong>Using max and default values</strong></p>\n\n<p>The snippet just above could be written by taking advantage of the Python builtins:</p>\n\n<pre><code> prime_dict[k] = max(v, prime_dict.get(k, 0))\n</code></pre>\n\n<p><strong>Using in place operator</strong></p>\n\n<p>You can write things such as:</p>\n\n<pre><code> n //= d\n</code></pre>\n\n<p>or</p>\n\n<pre><code> res *= (k**v)\n</code></pre>\n\n<p>to avoid repeating the left member of the operand.</p>\n\n<p><strong>A different algorithm</strong></p>\n\n<p>The algorithm is all about computing <a href=\"https://en.wikipedia.org/wiki/Least_common_multiple\" rel=\"nofollow noreferrer\">Least Common Multiple</a> which can be easily computed with the <a href=\"https://en.wikipedia.org/wiki/Greatest_common_divisor\" rel=\"nofollow noreferrer\">Greatest Common Divisor</a>.</p>\n\n<p>When this is implemented and tests cases are rewritten to ensure benchmark gives relevant timing:</p>\n\n<pre><code>from timeit import default_timer as timer\nimport functools\n\ndef gcd(a, b):\n \"\"\"Computes gcd for 2 numbers.\"\"\"\n while b:\n a, b = b, a % b\n return a\n\n\ndef lcm(a, b):\n \"\"\"Computes lcm for 2 numbers.\"\"\"\n return a * b // gcd(a, b)\n\n\ndef lcmm(*args):\n \"\"\"Computes lcm for numbers.\"\"\"\n return functools.reduce(lcm, args)\n\ndef smallest_dividable_num(n:int) -&gt; int:\n '''\n Returns the smallest integer whose dividable by all the numbers from 1 to n.\n :param n: an integer upper bound which we want to compute the smallest divisable num from 1 to it.\n '''\n return lcmm(*range(1, n + 1))\n\n\nif __name__ == \"__main__\":\n start = timer()\n for i in range(20):\n assert smallest_dividable_num(10) == 2520\n assert smallest_dividable_num(6) == 60\n assert smallest_dividable_num(20) == 232792560\n for i in range(1, 40):\n smallest_dividable_num(i)\n end = timer()\n print(end - start)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-12T16:59:51.343", "Id": "225989", "ParentId": "225449", "Score": "4" } } ]
{ "AcceptedAnswerId": "225989", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T10:10:11.073", "Id": "225449", "Score": "3", "Tags": [ "python", "beginner", "python-3.x", "programming-challenge" ], "Title": "Project Euler - Problem No.5 - Smallest multiple" }
225449
<p>I'm making a news aggregator using newsAPI, and have everything working - to begin with. But was wondering if the code I use to filter through an object can be made more efficient - meaning fewer lines of code. </p> <p>So far, it only returns what I need from the raw JSON file, then filters it using a for loop to ignore objects with blank values.</p> <p>Any help would be great.</p> <pre><code> if (!error &amp;&amp; response.statusCode == 200) { let data = JSON.parse(body); let articles = data.articles.map(article =&gt; { return { "title": article.title, "date": article.publishedAt, "image": article.urlToImage, "description": article.description, "link": article.url } }); let filtered = [] for (let i = 0; i &lt; articles.length; i++) { if (articles[i].title !== null &amp;&amp; articles[i].date !== null &amp;&amp; articles[i].image !== null &amp;&amp; articles[i].description !== null &amp;&amp; articles[i].link !== null) { filtered.push(articles[i]) } } console.log(filtered) res.render("index", { filtered: filtered }); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T15:45:35.230", "Id": "437816", "Score": "0", "body": "Too lazy to write an answer. Array to hold property names, filter then map. `array.reduce` to transform each object. Chain them to avoid intermediates and you are done. `const keys = [[\"title\", \"title\"], [\"publishedAt\", \"date\"], [\"urlToImage\", \"image\"], [\"description\", \"description\"], [\"url\", \"link\"]];\n res.render(\"index\", { filtered: JSON.parse(body).articles\n .filter(article => keys.some(key => article[key[0]] !== null)) \n .map(article => keys.reduce((art, k) => (art[k[1]] = article[k[0]], art), {}))\n });` BTW your code is missing a closing `}`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T18:51:33.347", "Id": "437844", "Score": "2", "body": "Looks like closing brace for the outer `if` is missing. That begs the question, is there other code missing?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-05T15:10:14.867", "Id": "438049", "Score": "0", "body": "Your code could be so much cleaner if you used the same property names throughout your code. Is that possible?" } ]
[ { "body": "<ul>\n<li><code>let</code> -> <code>const</code></li>\n<li>Use the <code>Array</code> methods (<code>filter</code>, <code>every</code>)</li>\n<li>Use object destructuring</li>\n<li>Use object short-hand</li>\n<li>Use a method for the null check so you don't have to write it for every property</li>\n</ul>\n\n<pre class=\"lang-js prettyprint-override\"><code>if (!error &amp;&amp; response.statusCode == 200) {\n const data = JSON.parse(body);\n\n const filtered = data.articles\n .filter(({ title, publishedAt, urlToImage, description, url }) =&gt;\n [title, publishedAt, urlToImage, description, url].every(\n prop =&gt; prop !== null\n )\n )\n .map(\n ({\n title,\n publishedAt: date,\n urlToImage: image,\n description,\n url: link\n }) =&gt; ({\n title,\n date,\n image,\n description,\n link\n })\n );\n\n res.render(\"index\", { filtered });\n}\n</code></pre>\n\n<p>Update: filtered first for lower memory consumption as by @FreezePhoenix suggestion.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-05T15:08:44.827", "Id": "438047", "Score": "1", "body": "You seem to miss that the source properties and the rendered properties do not have the same name" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-05T15:09:52.747", "Id": "438048", "Score": "0", "body": "@konijn Thanks! Fixed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-05T15:18:12.443", "Id": "438050", "Score": "0", "body": "@konijn Actually still had it wrong Now it's fixed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-05T15:37:46.727", "Id": "438055", "Score": "0", "body": "Hm... this creates a 2 new objects for each one being filtered... perhaps there is a better way?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-05T15:48:35.267", "Id": "438058", "Score": "2", "body": "@FreezePhoenix Not quite sure what you are getting at. Do you mean to lower the space complexity?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-05T15:51:40.700", "Id": "438060", "Score": "0", "body": "In my experience, for large projects (which this seems like it might grow into one), you want to squeeze almost every bit of memory you can out of it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-05T15:54:28.540", "Id": "438064", "Score": "0", "body": "In my experience, for large projects, you want to maintain readability " }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-05T16:05:36.557", "Id": "438066", "Score": "2", "body": "@Mohrn Your new edit in an attempt to incorporate my suggestion errors :) because none of the variables are defined." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-05T15:04:18.100", "Id": "225587", "ParentId": "225453", "Score": "2" } }, { "body": "<p>Revising @Mohrn's answer:</p>\n\n<ul>\n<li>Avoid creating new objects if possible.</li>\n<li>As mentioned by @radarbob, you are excluding the closing if bracket.</li>\n</ul>\n\n<p>As such, I recommend a few changes be made:</p>\n\n<pre><code>if (!error &amp;&amp; response.statusCode == 200) {\n const data = JSON.parse(body);\n\n const filtered = data.articles\n .map(\n ({\n title,\n publishedAt: date,\n urlToImage: image,\n description,\n url: link\n }) =&gt; (\n ([title, date, image, description, link].every(_ =&gt; _ !== null) ?\n { title, date, image, description, link } :\n null\n )\n )).filter(_ =&gt; _ !== null);\n\n res.render(\"index\", { filtered });\n}\n</code></pre>\n\n<p>This does result in fewer objects being created per iteration.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-05T15:51:22.323", "Id": "438059", "Score": "0", "body": "You're returning objects with the shape `{ title, publishedAt, utlToImage, description, url }` rather than `{ title, date, image, description, link }`. The difference between our solutions is that you lack the mapping of property names." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-05T15:54:13.463", "Id": "438063", "Score": "0", "body": "@Mohrn Edited, now the difference is that it doesn't create a second object for ones that don't need to be made. Instead of making the object and then getting values, we're getting values and then making the object if needed." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-05T15:42:16.243", "Id": "225589", "ParentId": "225453", "Score": "1" } } ]
{ "AcceptedAnswerId": "225587", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T12:06:17.753", "Id": "225453", "Score": "3", "Tags": [ "javascript", "node.js" ], "Title": "Filtering an object JS" }
225453
<p>I use my own logger adapter that collects data into a dictionary:</p> <pre><code>public class Log : Dictionary&lt;string, object&gt; { } </code></pre> <p>This is really all I have. I then pass it to my <code>NLogRx</code> - this is an <code>IObserver&lt;Log&gt;</code> that <em>translates</em> my <code>Log</code> into <code>NLog</code>'s entries.</p> <p>I need this <em>layer</em> for all kinds of <em>freaky</em> stuff I do with that dictionary: add stopwatch, contexts with correlation-ids or default attachmentes that are applied to each entry. </p> <p>Currently I just pass it to the actual logger but... I had that idea (and a need) of adding a <em>transaction</em>. That should act like a <em>buffer</em> and collect entries until I commit them. This should help me avoid unnecessary logging for code paths that actually didn't do anything useful (and would mean only garbage). It required a lot of <em>workarounds</em> with my current design (it's even super difficult to explain) so I was looking for something more structured.</p> <hr> <h3>Core</h3> <p>After some reaserch and trail-and-error I created the following <strong>proof-of-concept</strong> (LINQPad, not extra dependencies). It uses the idea of a <strong><em>middleware</em></strong> and is a <strong>doubly-linked-list</strong> that acts as a <strong>chain of responsibility</strong>.</p> <p><code>LoggerMiddleware</code> is the node. It maintains the <code>Previous</code> and <code>Next</code> link in the chain. When disposed, it removes itself from it (an example follows).</p> <pre><code>public abstract class LoggerMiddleware : IDisposable { public LoggerMiddleware Previous { get; private set; } public LoggerMiddleware Next { get; private set; } public T Add&lt;T&gt;(T next) where T : LoggerMiddleware { next.Previous = this; next.Next = Next; Next = next; return next; } public abstract void Invoke(Log request); public void Dispose() { if (!(Previous is null)) { Previous.Next = Next; Previous = null; Next = null; } } } </code></pre> <p>Based on this class, I created four more middlewares.</p> <ul> <li><code>LoggerInitializer</code> - this is supposed to add the name of the logger to <code>Log</code></li> <li><code>LoggerLambda</code> - allows me to let the caller modify the <code>Log</code> as he pleases</li> <li><code>LoggerTransaction</code> - allows me to buffer logs and commit them</li> <li><code>LoggerFilter</code> - allows me to filter logs and short-circuit the pipeline</li> <li><code>LoggerEcho</code> - this is the final link that forwards <code>Log</code> to the actual adapter</li> </ul> <pre><code>public class LoggerInitializer : LoggerMiddleware { private readonly string _name; public LoggerInitializer(string name) { _name = name; } public override void Invoke(Log request) { request["name"] = _name; Next?.Invoke(request); } } public class LoggerLambda : LoggerMiddleware { private readonly Action&lt;Log&gt; _transform; public LoggerLambda(Action&lt;Log&gt; transform) { _transform = transform; } public override void Invoke(Log request) { _transform(request); Next?.Invoke(request); } } public class LoggerTransaction : LoggerMiddleware { private readonly IList&lt;Log&gt; _buffer = new List&lt;Log&gt;(); public override void Invoke(Log request) { _buffer.Add(request); //Next?.Invoke(request); // &lt;-- don't call Next until Commit } public void Commit() { foreach (var request in _buffer) { Next?.Invoke(request); } } public void Rollback() { _buffer.Clear(); } } public class LoggerFilter : LoggerMiddleware { public Func&lt;Log, bool&gt; CanLog { get; set; } public override void Invoke(Log request) { if (CanLog(request)) { Next?.Invoke(request); } } } public class LoggerEcho : LoggerMiddleware { public override void Invoke(Log request) { request.Dump(); } } </code></pre> <h3>Logger</h3> <p>A <code>Logger</code> is constructed with a middleware and interally adds the <em>echo</em> for writing. It provides a helper API <code>Add</code> that chains a new middleware just before the <em>echo</em>. This middleware is automatically removed from the chain when it's disposed. This way I can intercept the flow of <code>Log</code>s and filter or buffer them... I guesss other ideas will pop-up later.</p> <pre><code>public class Logger { private readonly LoggerMiddleware _middleware; public Logger(LoggerMiddleware middleware) { _middleware = middleware; _middleware.Add(new LoggerEcho()); } public T Add&lt;T&gt;(T next) where T : LoggerMiddleware { return _middleware.NextToLast().Add(next); } public void Log(Log log) { _middleware.Invoke(log); } } </code></pre> <h3>Utilities</h3> <p>The raw API would be cumbersome to use so I also created a couple of convenience extensions.</p> <ul> <li><code>LogExtensions</code> - simplifies setting various log properties</li> <li><code>LoggerExtensions</code> - simplifies <code>Log</code> transformations</li> <li><code>LoggerMiddlewareExtensions</code> - simplifies finding the next-to-last middleware</li> </ul> <pre><code>public static class LogExtensions { public static Log Message(this Log log, string message) { log["message"] = message; return log; } } public static class LoggerExtensions { public static void Log(this Logger logger, Action&lt;Log&gt; transform) { using (logger.Add(new LoggerLambda(transform))) { logger.Log(new Log()); } } } public static class LoggerMiddlewareExtensions { public static LoggerMiddleware NextToLast(this LoggerMiddleware loggerMiddleware) { while (!(loggerMiddleware.Next is null)) { loggerMiddleware = loggerMiddleware.Next; } return loggerMiddleware.Previous; } } </code></pre> <h3>Example</h3> <p>By all these powers combined I am now able to chain all features and <em>inject</em> new ones at the end (before last) when necessary:</p> <pre><code>void Main() { var logger = new Logger(new LoggerInitializer("init")); // Include to filter certain messages out. //logger.Add(new LoggerFilter { CanLog = l =&gt; !l["message"].Equals("tran-2-commit") }); logger.Log(l =&gt; l.Message("begin")); using (var tran = logger.Add(new LoggerTransaction())) { logger.Log(l =&gt; l.Message("tran-1-commit")); logger.Log(l =&gt; l.Message("tran-2-commit")); tran.Commit(); // both messages are logged } using (var tran = logger.Add(new LoggerTransaction())) { logger.Log(l =&gt; l.Message("tran-1-rollback")); logger.Log(l =&gt; l.Message("tran-2-rollback")); tran.Rollback(); // both messages are ignored } logger.Log(l =&gt; l.Message("end")); } </code></pre> <hr> <h3>Questions</h3> <p>I know there are a lot of convenience extensions necessary to make it more user-friendly (like creating a new transaction) but what do you think about it as a low level API? Do the middlewares make sense as nodes of a linked-list and links in the chain of responsibility? What would you improve and how?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T14:06:56.417", "Id": "437800", "Score": "1", "body": "I put the code on [GitHub Gist](https://gist.github.com/he-dev/c2fcbdd0a7415e4d1a49c19eea055cee) for easier copy/paste if anyone wanted to. It's from LINQPad and it uses `Dump`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-06T18:48:43.937", "Id": "438240", "Score": "1", "body": "Minor nit: I am not really a fan of `!(x is null)` notation - I prefer seeing positive condition tests and that can read `x is object`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-06T18:56:39.047", "Id": "438243", "Score": "0", "body": "@JesseC.Slicer me either. I always prefer postive conditions but somtimes there is just no other way to handle it :-[ an `is not` operator would be awsome!" } ]
[ { "body": "<h3>Review</h3>\n\n<ul>\n<li><code>Add</code> usually means append at the back of a list. I would prefer <code>InsertAfter</code>.</li>\n<li>Disposing the root <code>LoggerMiddleware</code> of the chain is not possible. Is this as designed?</li>\n<li>Should <code>LoggerTransaction</code> be idempotent? If so, use a <code>Queue</code> instead of <code>List</code> and <em>dequeue</em> the items on <code>Commit</code>.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T12:30:34.830", "Id": "437784", "Score": "0", "body": "Yes, there always be the init and echo middlewares that won't be disposed. In which way do you mean idempotent? I'm not sure how to apply that concept to this class. I know what it means in terms of POST and PUT requests but not sure what to do with that here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T12:32:03.790", "Id": "437785", "Score": "1", "body": "If you call _Commit_ twice, you wish to forward the log entries twice to the next in chain?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T12:32:31.877", "Id": "437786", "Score": "1", "body": "Oh! Of course not! Good catch." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T12:34:41.177", "Id": "437787", "Score": "1", "body": "I have made a similar log wrapper in my current project. The way I use it is similar to your transaction. But I also allow to combine the logs, and forward a single log entry to the next in chain. This way, multiple logs can be grouped together to get a nice 'report' layout in some log backend. Might be an interesting concept to put in your framework as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T12:38:36.353", "Id": "437789", "Score": "1", "body": "Yeah, I already thought of it ;-) I call my _system_ semantic-logging and I actually very rarely log any messages. I use my logs directly to generate reports. They have multiple levels of correlation ids, layer ids like business, service, io, snapshot in json format or elapsed times; so I can join or put together virtually any data I want ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T12:53:51.883", "Id": "437792", "Score": "0", "body": "ok, I already have a use case for the log-aggregator too (it could be a performance counter for certain events)... and another one for the stopwatch... what other cool ideas have you implemented in your solution?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T13:06:17.770", "Id": "437793", "Score": "0", "body": "Well, one other thing to think about is _async_ logging. Do you want to support this? Would you use a single queue for all log requests, one at a certain middleware level, or any other synchronization context?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T13:11:05.263", "Id": "437794", "Score": "1", "body": "I once read about async logging in an article about the logger in microsoft extensions. They meant logging should be fast and that's why they don't provide an async API. I like that theory and I think I won't be considering making it async currently... until I stumble on something else that would convince me of the opposite." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T13:14:47.167", "Id": "437795", "Score": "0", "body": "I think it might be interesting once you have a use case where the log scheduler does not require to be in sync with the log call. For instance, when some appender polls some queue periodically to batch log." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T14:17:08.370", "Id": "437802", "Score": "0", "body": "btw, what do you think of `(next.Previous, next.Next, Next) = (this, Next, next);` with tuples instead of doing it line by line like I currently do in `Add`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T14:39:08.197", "Id": "437808", "Score": "0", "body": "That's an unusual syntax for me :) I'm ok with it as long these tuples are short and readable. This one is borderline. (x, y) = (0, 1); seems a much better candidate :p" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T18:20:21.317", "Id": "437838", "Score": "1", "body": "I've almost entirely rewritten my old logging framework and I must say that this pattern is like the logging's silver-bullet o_O it's so easy to add and test new features and the old ones has become so much simpler :-\\ it's really strange that there is no such thing already... feeling inventive :]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-06T18:08:40.067", "Id": "438232", "Score": "1", "body": "If you're curious what it has become, you can take a look at an [example](https://github.com/he-dev/reusable/blob/feature/console-models/Reusable.app.Console/src/Examples/OmniLog/Example.cs#L31) in my repo. I call middleware nodes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-06T18:11:32.153", "Id": "438233", "Score": "0", "body": "Neat, perhaps it's time to self answer ;-)" } ], "meta_data": { "CommentCount": "14", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T12:25:56.793", "Id": "225456", "ParentId": "225454", "Score": "2" } }, { "body": "<p><em>(self-answer)</em></p>\n\n<hr>\n\n<p>This pattern has proven itself in practice so I'll keep it for my logging layer. I extended the POC in many places. The middleware has gotten an interface and each middleware I now call <code>Node</code>s. I have implemented also many ideas from other related questions (like <code>IsActive</code> or queues). Thanks a lot! ;-)</p>\n\n<pre><code>public interface ILinkedListNode&lt;T&gt;\n{\n T Previous { get; }\n\n T Next { get; }\n\n T InsertNext(T next);\n\n /// &lt;summary&gt;\n /// Removes this node from the chain an returns the Previous item or Next if Previous is null.\n /// &lt;/summary&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n T Remove();\n}\n</code></pre>\n\n<p>Thre is also a default implementation with linked-list operations that I need for this framework only so some of them are missing.</p>\n\n<pre><code>public abstract class LoggerNode : ILinkedListNode&lt;LoggerNode&gt;, IDisposable\n{\n public LoggerNode(bool isActive)\n {\n IsActive = isActive;\n }\n\n public virtual bool IsActive { get; set; } = true;\n\n #region ILinkeListNode\n\n [JsonIgnore]\n public LoggerNode Previous { get; private set; }\n\n [JsonIgnore]\n public LoggerNode Next { get; private set; }\n\n #endregion\n\n // Inserts a new middleware after this one and returns the new one.\n public LoggerNode InsertNext(LoggerNode next)\n {\n (next.Previous, next.Next, Next) = (this, Next, next);\n return next;\n }\n\n public LoggerNode Remove()\n {\n var result = default(LoggerNode);\n\n if (!(Previous is null))\n {\n result = Previous;\n (Previous.Next, Previous) = (Next, null);\n }\n\n if (!(Next is null))\n {\n result = result ?? Next;\n (Next.Previous, Next) = (Previous, null);\n }\n\n return result;\n }\n\n public void Invoke(LogEntry request)\n {\n if (IsActive)\n {\n InvokeCore(request);\n }\n else\n {\n Next?.Invoke(request);\n }\n }\n\n protected abstract void InvokeCore(LogEntry request);\n\n // Removes itself from the middleware chain.\n public virtual void Dispose()\n {\n Remove();\n }\n}\n</code></pre>\n\n<hr>\n\n<p><code>TransactionNode</code> was a little bit challenging. It now uses a <code>LoggerScope&lt;T&gt;</code> helper that is borrowed from the asp.net-core console logger and made reusable because I need it for other nodes too. It maintains a <code>State</code> in an async context which allows to open many independent scopes:</p>\n\n<pre><code>public class LoggerScope&lt;T&gt;\n{\n private static readonly AsyncLocal&lt;LoggerScope&lt;T&gt;&gt; State = new AsyncLocal&lt;LoggerScope&lt;T&gt;&gt;();\n\n private LoggerScope(T value)\n {\n Value = value;\n }\n\n public T Value { get; }\n\n private LoggerScope&lt;T&gt; Parent { get; set; }\n\n public static LoggerScope&lt;T&gt; Current\n {\n get =&gt; State.Value;\n private set =&gt; State.Value = value;\n }\n\n public static bool IsEmpty =&gt; Current is null;\n\n public static LoggerScope&lt;T&gt; Push(T value)\n {\n return Current = new LoggerScope&lt;T&gt;(value) { Parent = Current };\n }\n\n public void Dispose()\n {\n Current = Current?.Parent;\n }\n}\n</code></pre>\n\n<p>Here, I use it for keeping <code>Queue</code> buffers fol log-entries.</p>\n\n<pre><code>public class TransactionNode : LoggerNode, ILoggerScope&lt;TransactionNode.Scope, object&gt;\n{\n public TransactionNode() : base(false) { }\n\n public override bool IsActive =&gt; !LoggerScope&lt;Scope&gt;.IsEmpty;\n\n protected override void InvokeCore(LogEntry request)\n {\n LoggerScope&lt;Scope&gt;.Current.Value.Buffer.Enqueue(request);\n // Don't call Next until Commit.\n }\n\n public Scope Push(object parameter)\n {\n return LoggerScope&lt;Scope&gt;.Push(new Scope { Next = Next }).Value;\n }\n\n public class Scope : IDisposable\n {\n internal Queue&lt;LogEntry&gt; Buffer { get; } = new Queue&lt;LogEntry&gt;();\n\n internal LoggerNode Next { get; set; }\n\n public void Commit()\n {\n while (Buffer.Any())\n {\n Next?.Invoke(Buffer.Dequeue());\n }\n }\n\n public void Rollback()\n {\n Buffer.Clear();\n }\n\n\n public void Dispose()\n {\n Buffer.Clear();\n LoggerScope&lt;Scope&gt;.Current.Dispose();\n }\n }\n}\n</code></pre>\n\n<hr>\n\n<p>The entire framework has grown a lot. If anyone would like to take a look at the API, it's in my repo <a href=\"https://github.com/he-dev/reusable/blob/feature/console-models/Reusable.app.Console/src/Examples/OmniLog/Example.cs\" rel=\"nofollow noreferrer\">here</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-06T18:43:22.683", "Id": "438239", "Score": "1", "body": "A cool thing you can do now with the node is to add methods _cloack_ and _uncloack_. Cloacking a node removes itself from the chain, but keeps the references to prev and next in the deleted node. Uncloacking the node lets the node put itself back in the chain at its location before cloacking. Whether you would need this, is up to you. It's an alternative for _IsActive_." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-06T18:51:01.503", "Id": "438241", "Score": "1", "body": "@dfhwze haha, this is pretty cool, indeed. I have currently no idea why I would need it but it may be fun to implement it anyway :-P Why not go all out and make a node move along the chain handling outputs of each previous node like a walking telemetry node - so whacked out! At the end it could _jump_ back to the beginning." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-06T18:37:40.097", "Id": "225672", "ParentId": "225454", "Score": "2" } } ]
{ "AcceptedAnswerId": "225456", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T12:06:34.737", "Id": "225454", "Score": "3", "Tags": [ "c#", "design-patterns", "linked-list", "logging" ], "Title": "Logger adapter with a configurable chain of responsibility of middlewares" }
225454
<p>I'm starting to study sorting algorithms in Python. Merge Sort has a complexity at best and worst cases <span class="math-container">\$\mathcal{O}(n\log{}n)\$</span>, I want generation a list where Merge Sort is slow but I would some complication. Could you help me with this problem?</p> <p>This is the code:</p> <pre class="lang-py prettyprint-override"><code>def mergeSort(l): #print("Splitting ",l) if len(l)&gt;1: mid = len(l)//2 lefthalf = l[:mid] righthalf = l[mid:] mergeSort(lefthalf) mergeSort(righthalf) i=0 j=0 k=0 while i&lt;len(lefthalf) and j&lt;len(righthalf): if lefthalf[i]&lt;righthalf[j]: l[k]=lefthalf[i] i=i+1 else: l[k]=righthalf[j] j=j+1 k=k+1 while i&lt;len(lefthalf): l[k]=lefthalf[i] i=i+1 k=k+1 while j&lt;len(righthalf): l[k]=righthalf[j] j=j+1 k=k+1 #print("Merging ",l) return </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T22:55:53.520", "Id": "440454", "Score": "0", "body": "That's not really the purpose of this site. Take a look at [this question](https://stackoverflow.com/questions/24594112/when-will-the-worst-case-of-merge-sort-occur) for how to create a worst case input for merge sort." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T12:15:25.470", "Id": "225455", "Score": "1", "Tags": [ "python", "mergesort" ], "Title": "Vector of numbers where merge sort is slow" }
225455
<p><strong>DO NOT REVIEW IT. I PROVIDED BIG CHANGES, SO THIS CODE IS NOT UPDATED</strong></p> <p>I'm developing my bookscraper to improve myself in coding and I think I have solid structure that I want to be reviewed by more experienced people than me. It is app based on SpringBoot which fetches data from 2 different bookstores. For now it has 3 options of fetching books. </p> <p>1) Bestsellers</p> <p>2) Book with given title e.g: You say you want to get book with title "Great boy" and it gives you book from each bookstore with title, price, link to the book</p> <p>3) Categorized books (currently for 5 categories e.g.: crimes, biogrpahies etc)</p> <p>I have created ranking for categorized books which takes 15 books from each bookstore, then it counts how many given title was repeated (if for example two, then it is higher in the ranking) and returns it in the map <code>Map&lt;String,Integer&gt;</code> which goes for title and number of occurrences.</p> <p>I have integration and unit tests. In my test resources I put 3 files for each bookstore which contains <code>.html</code> files for each type of fetching (bestsellers,categorized book,most precise book).</p> <p>Here is the link to github, because I'm not gonna put all the classes here as there is a lot of them. <a href="https://github.com/must1/BookstoreScraper" rel="nofollow noreferrer">https://github.com/must1/BookstoreScraper</a></p> <p>I added also CI with Travis and SonarCloud. <strong>JsoupConnector (responsible for connecting to the given url)</strong></p> <pre><code>package bookstore.scraper.utilities; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.springframework.stereotype.Component; import java.io.IOException; @Component public class JSoupConnector { public Document connect(String url) { try { return Jsoup.connect(url).get(); } catch (IOException e) { throw new IllegalArgumentException("Cannot connect to" + url); } } } </code></pre> <p><strong>MerlinUrlProperties</strong> (all links are stored in <code>.yml</code> file), same class for second bookstore</p> <pre><code>package bookstore.scraper.urlproperties; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Getter @Setter @Component @ConfigurationProperties("external.library.url") public class MerlinUrlProperties { private Merlin merlin = new Merlin(); @Getter @Setter public static class Merlin { private String mostPreciseBook; private String bestSellers; private String concreteBook; private String romances; private String biographies; private String crime; private String guides; private String fantasy; } } </code></pre> <p><strong>MerlinFetchingBookService (fetches data from the net)</strong></p> <pre><code>package bookstore.scraper.fetcher.merlin; import bookstore.scraper.book.Book; import bookstore.scraper.urlproperties.MerlinUrlProperties; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; @Service public class MerlinFetchingBookService { private static final int BESTSELLERS_NUMBER_TO_FETCH = 6; private static final int CATEGORIZED_BOOKS_NUMBER_TO_FETCH = 16; private final MerlinUrlProperties merlinUrlProperties; @Autowired public MerlinFetchingBookService(MerlinUrlProperties merlinUrlProperties) { this.merlinUrlProperties = merlinUrlProperties; } public Book getMostPreciseMerlinBook(Document document) { String title = document.select("div.b-products-list__title-holder").select("a").first().text(); String price = document.select("div.b-products-list__price-holder &gt; a").first().text(); String author = document.select("div.b-products-list__manufacturer-holder").select("a").first().text(); String productID = document.select("div.grid__col.grid__col--20-80-80.b-products-wrap &gt; ul &gt; li:nth-child(1)").first().attr("data-ppc-id"); String bookUrl = createBookUrl(title, productID); return new Book.BookBuilder() .withAuthor(author) .withPrice(price) .withTitle(title) .withProductID(productID) .withBookUrl(bookUrl) .build(); } public List&lt;Book&gt; get5BestSellersMerlin(Document document) { return IntStream.range(1, BESTSELLERS_NUMBER_TO_FETCH) .mapToObj(iterator -&gt; getBestSellerOrCategorizedBook(document, iterator)) .collect(Collectors.toList()); } public List&lt;Book&gt; get15BooksFromCategory(Document document) { return IntStream.range(1, CATEGORIZED_BOOKS_NUMBER_TO_FETCH) .mapToObj(iterator -&gt; getBestSellerOrCategorizedBook(document, iterator)) .collect(Collectors.toList()); } //Todo //need to think about better name for the method as it can be used for fetching bestseller and categorized book private Book getBestSellerOrCategorizedBook(Document document, int iteratedBook) { Elements siteElements = document.select("div.grid__col.grid__col--20-80-80.b-products-wrap &gt; ul &gt; li:nth-child(" + iteratedBook + ")"); String author = siteElements.select(" &gt; div &gt; div.b-products-list__desc-wrap &gt; div &gt; div.b-products-list__main-content &gt; div.b-products-list__desc-prime &gt; div.b-products-list__manufacturer-holder").select("a").first().text(); String title = siteElements.select(" &gt; div &gt; div.b-products-list__desc-wrap &gt; div &gt; div.b-products-list__main-content &gt; div.b-products-list__desc-prime &gt; div.b-products-list__title-holder &gt; a").first().text(); String price = siteElements.select(" div.b-products-list__price-holder &gt; a").first().text(); String productID = siteElements.first().attr("data-ppc-id"); String bookUrl = createBookUrl(title, productID); return new Book.BookBuilder() .withAuthor(author) .withPrice(price) .withTitle(title) .withProductID(productID) .withBookUrl(bookUrl) .build(); } private String createBookUrl(String title, String productID) { return String.format(merlinUrlProperties.getMerlin().getConcreteBook(), title, productID); } } </code></pre> <p><strong>CategorizedBookRankingService (responsible for ranking for given category)</strong></p> <pre><code>package bookstore.scraper.rankingsystem; import bookstore.scraper.book.Book; import bookstore.scraper.book.scrapingtypeservice.CategorizedBookService; import bookstore.scraper.enums.Bookstore; import bookstore.scraper.enums.CategoryType; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.*; import java.util.stream.Stream; import static java.util.stream.Collectors.*; @Slf4j @Component public class CategorizedBooksRankingService { private final CategorizedBookService categorizedBookService; @Autowired public CategorizedBooksRankingService(CategorizedBookService categorizedBookService) { this.categorizedBookService = categorizedBookService; } public Map&lt;String, Integer&gt; getRankingForCategory(CategoryType category) { Map&lt;Bookstore, List&lt;Book&gt;&gt; bookstoreWith15CategorizedBooks = chooseGetterImplementationByCategory(category); List&lt;Book&gt; merlinBooks = bookstoreWith15CategorizedBooks.get(Bookstore.MERLIN); List&lt;Book&gt; empikBooks = bookstoreWith15CategorizedBooks.get(Bookstore.EMPIK); Map&lt;String, List&lt;String&gt;&gt; purifiedTitleWithOriginalTitles = getPurifiedTitleWithAccordingOriginalTitles(merlinBooks, empikBooks); Map&lt;String, Integer&gt; bookTitleWithOccurrencesNumber = getTitleWithOccurrences(purifiedTitleWithOriginalTitles); return getSortedLinkedHashMapByValue(bookTitleWithOccurrencesNumber); } private Map&lt;String, List&lt;String&gt;&gt; getPurifiedTitleWithAccordingOriginalTitles(List&lt;Book&gt; list1, List&lt;Book&gt; list2) { return Stream.concat(list1.stream(), list2.stream()) .collect( groupingBy(Book::getPurifiedTitle, mapping(Book::getTitle, toList()))); } private Map&lt;String, Integer&gt; getTitleWithOccurrences(Map&lt;String, List&lt;String&gt;&gt; map) { return map.values().stream().collect(toMap(list -&gt; list.get(0), List::size)); } private Map&lt;String, Integer&gt; getSortedLinkedHashMapByValue(Map&lt;String, Integer&gt; mapToSort) { return mapToSort.entrySet() .stream() .sorted(Collections.reverseOrder(Map.Entry.comparingByValue())) .collect( toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -&gt; e2, LinkedHashMap::new)); } private Map&lt;Bookstore, List&lt;Book&gt;&gt; chooseGetterImplementationByCategory(CategoryType categoryType) { Map&lt;Bookstore, List&lt;Book&gt;&gt; map = new EnumMap&lt;&gt;(Bookstore.class); if (categoryType.equals(CategoryType.CRIME)) map = categorizedBookService.get15BooksFromCrimeCategory(); if (categoryType.equals(CategoryType.ROMANCES)) map = categorizedBookService.get15BooksFromRomanceCategory(); if (categoryType.equals(CategoryType.FANTASY)) map = categorizedBookService.get15BooksFromFantasyCategory(); if (categoryType.equals(CategoryType.GUIDES)) map = categorizedBookService.get15BooksFromGuidesCategory(); if (categoryType.equals(CategoryType.BIOGRAPHY)) map = categorizedBookService.get15BooksFromBiographiesCategory(); return map; } } </code></pre> <p><strong>CategorizedBookService</strong></p> <pre><code>package bookstore.scraper.book.scrapingtypeservice; import bookstore.scraper.enums.Bookstore; import bookstore.scraper.book.Book; import bookstore.scraper.fetcher.empik.EmpikFetchingBookService; import bookstore.scraper.fetcher.merlin.MerlinFetchingBookService; import bookstore.scraper.urlproperties.EmpikUrlProperties; import bookstore.scraper.urlproperties.MerlinUrlProperties; import bookstore.scraper.utilities.JSoupConnector; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.EnumMap; import java.util.List; import java.util.Map; @Service @Slf4j public class CategorizedBookService { private final EmpikFetchingBookService empikBookService; private final MerlinFetchingBookService merlinFetchingBookService; private final EmpikUrlProperties empikUrlProperties; private final MerlinUrlProperties merlinUrlProperties; private final JSoupConnector jSoupConnector; @Autowired public CategorizedBookService(EmpikFetchingBookService empikBookService, MerlinFetchingBookService merlinFetchingBookService, EmpikUrlProperties empikUrlProperties, MerlinUrlProperties merlinUrlProperties, JSoupConnector jSoupConnector) { this.empikBookService = empikBookService; this.merlinFetchingBookService = merlinFetchingBookService; this.empikUrlProperties = empikUrlProperties; this.merlinUrlProperties = merlinUrlProperties; this.jSoupConnector = jSoupConnector; } public Map&lt;Bookstore, List&lt;Book&gt;&gt; get15BooksFromRomanceCategory() { return get15BooksFrom(empikUrlProperties.getEmpik().getRomances(), merlinUrlProperties.getMerlin().getRomances()); } public Map&lt;Bookstore, List&lt;Book&gt;&gt; get15BooksFromFantasyCategory() { return get15BooksFrom(empikUrlProperties.getEmpik().getFantasy(), merlinUrlProperties.getMerlin().getFantasy()); } public Map&lt;Bookstore, List&lt;Book&gt;&gt; get15BooksFromCrimeCategory() { return get15BooksFrom(empikUrlProperties.getEmpik().getCrime(), merlinUrlProperties.getMerlin().getCrime()); } public Map&lt;Bookstore, List&lt;Book&gt;&gt; get15BooksFromGuidesCategory() { return get15BooksFrom(empikUrlProperties.getEmpik().getGuides(), merlinUrlProperties.getMerlin().getGuides()); } public Map&lt;Bookstore, List&lt;Book&gt;&gt; get15BooksFromBiographiesCategory() { return get15BooksFrom(empikUrlProperties.getEmpik().getBiographies(), merlinUrlProperties.getMerlin().getBiographies()); } private Map&lt;Bookstore, List&lt;Book&gt;&gt; get15BooksFrom(String bookStoreEmpikURL, String bookStoreMerlinURL) { Map&lt;Bookstore, List&lt;Book&gt;&gt; bookstoreWith15CategorizedBooks = new EnumMap&lt;&gt;(Bookstore.class); bookstoreWith15CategorizedBooks.put(Bookstore.EMPIK, empikBookService .get15BooksFromCategory(jSoupConnector.connect(bookStoreEmpikURL))); bookstoreWith15CategorizedBooks.put(Bookstore.MERLIN, merlinFetchingBookService .get15BooksFromCategory(jSoupConnector.connect(bookStoreMerlinURL))); return bookstoreWith15CategorizedBooks; } } </code></pre> <p><strong>MostPreciseBookService</strong></p> <pre><code>package bookstore.scraper.book.scrapingtypeservice; import bookstore.scraper.enums.Bookstore; import bookstore.scraper.book.Book; import bookstore.scraper.fetcher.empik.EmpikFetchingBookService; import bookstore.scraper.fetcher.merlin.MerlinFetchingBookService; import bookstore.scraper.urlproperties.EmpikUrlProperties; import bookstore.scraper.urlproperties.MerlinUrlProperties; import bookstore.scraper.utilities.JSoupConnector; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.EnumMap; import java.util.Map; @Service public class MostPreciseBookService { private final EmpikFetchingBookService empikBookService; private final MerlinFetchingBookService merlinBookService; private final EmpikUrlProperties empikUrlProperties; private final MerlinUrlProperties merlinUrlProperties; private final JSoupConnector jSoupConnector; @Autowired public MostPreciseBookService(EmpikFetchingBookService empikBookService, MerlinFetchingBookService merlinBookService, EmpikUrlProperties empikUrlProperties, MerlinUrlProperties merlinUrlProperties, JSoupConnector jSoupConnector) { this.empikBookService = empikBookService; this.merlinBookService = merlinBookService; this.empikUrlProperties = empikUrlProperties; this.merlinUrlProperties = merlinUrlProperties; this.jSoupConnector = jSoupConnector; } public Map&lt;Bookstore, Book&gt; getBookByTitle(String title) { Map&lt;Bookstore, Book&gt; bookstoreWithMostPreciseBook = new EnumMap&lt;&gt;(Bookstore.class); bookstoreWithMostPreciseBook.put(Bookstore.MERLIN, merlinBookService.getMostPreciseMerlinBook( jSoupConnector.connect(concatUrlWithTitle(merlinUrlProperties.getMerlin().getMostPreciseBook(), title)))); bookstoreWithMostPreciseBook.put(Bookstore.EMPIK, empikBookService.getMostPreciseEmpikBook( jSoupConnector.connect(concatUrlWithTitle(empikUrlProperties.getEmpik().getMostPreciseBook(), title)))); return bookstoreWithMostPreciseBook; } private String concatUrlWithTitle(String url, String title) { return String.format(url, title); } } </code></pre> <p><strong>BestsellersService</strong></p> <pre><code>package bookstore.scraper.book.scrapingtypeservice; import bookstore.scraper.enums.Bookstore; import bookstore.scraper.book.Book; import bookstore.scraper.fetcher.empik.EmpikFetchingBookService; import bookstore.scraper.fetcher.merlin.MerlinFetchingBookService; import bookstore.scraper.urlproperties.EmpikUrlProperties; import bookstore.scraper.urlproperties.MerlinUrlProperties; import bookstore.scraper.utilities.JSoupConnector; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.EnumMap; import java.util.List; import java.util.Map; @Service public class BestSellersService { private final EmpikUrlProperties empikUrlProperties; private final MerlinUrlProperties merlinUrlProperties; private final EmpikFetchingBookService empikBookService; private final MerlinFetchingBookService merlinBookService; private final JSoupConnector jSoupConnector; @Autowired public BestSellersService(EmpikFetchingBookService empikBookService, MerlinFetchingBookService merlinBookService, EmpikUrlProperties empikUrlProperties, MerlinUrlProperties merlinUrlProperties, JSoupConnector jSoupConnector) { this.empikBookService = empikBookService; this.merlinBookService = merlinBookService; this.empikUrlProperties = empikUrlProperties; this.merlinUrlProperties = merlinUrlProperties; this.jSoupConnector = jSoupConnector; } public Map&lt;Bookstore, List&lt;Book&gt;&gt; getBestSellers() { Map&lt;Bookstore, List&lt;Book&gt;&gt; bookstoreWithBestSellers = new EnumMap&lt;&gt;(Bookstore.class); bookstoreWithBestSellers.put(Bookstore.EMPIK, empikBookService .get5BestSellersEmpik(jSoupConnector.connect(empikUrlProperties.getEmpik().getBestSellers()))); bookstoreWithBestSellers.put(Bookstore.MERLIN, merlinBookService .get5BestSellersMerlin(jSoupConnector.connect(merlinUrlProperties.getMerlin().getBestSellers()))); return bookstoreWithBestSellers; } } </code></pre> <p><strong>TESTS</strong></p> <p><strong>CategorizedBooksRankingServiceTest</strong></p> <pre><code>package bookstore.scraper.rankingsystem; import bookstore.scraper.book.Book; import bookstore.scraper.book.scrapingtypeservice.CategorizedBookService; import bookstore.scraper.enums.Bookstore; import bookstore.scraper.enums.CategoryType; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import java.util.List; import java.util.Map; import static bookstore.scraper.dataprovider.MerlinBookProvider.prepareExpectedRankingMap; import static bookstore.scraper.dataprovider.MerlinBookProvider.prepareMapWithBookstoreAndCrimeBooks; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class CategorizedBooksRankingServiceTest { @Mock CategorizedBookService categorizedBookService; @InjectMocks CategorizedBooksRankingService categorizedBooksRankingService; @Test public void getRankingForCrimeCategory() { Map&lt;Bookstore, List&lt;Book&gt;&gt; bookstoreWith15CrimeBooks = prepareMapWithBookstoreAndCrimeBooks(); when(categorizedBookService.get15BooksFromCrimeCategory()).thenReturn(bookstoreWith15CrimeBooks); Map&lt;String, Integer&gt; actualMap = categorizedBooksRankingService.getRankingForCategory(CategoryType.CRIME); Map&lt;String, Integer&gt; expectedMap = prepareExpectedRankingMap(); assertEquals(expectedMap, actualMap); } } </code></pre> <p><strong>MerlinFetchingBookService</strong></p> <pre><code>package bookstore.scraper.fetcher.merlin; import bookstore.scraper.book.Book; import bookstore.scraper.fetcher.empik.EmpikFetchingBookServiceTest; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.List; import static bookstore.scraper.dataprovider.MerlinBookProvider.*; import static org.junit.Assert.assertEquals; @SpringBootTest @RunWith(SpringRunner.class) public class MerlinFetchingBookServiceTest { @Autowired private MerlinFetchingBookService merlinFetchingBookService; @Test public void getMostPreciseMerlinBook() throws IOException { File in = getFile("/merlin/MostPreciseBookMerlin.html"); Document doc = Jsoup.parse(in, "UTF-8"); Book actualBooks = merlinFetchingBookService.getMostPreciseMerlinBook(doc); Book expectedBooks = prepareMostPreciseBook(); assertEquals(expectedBooks, actualBooks); } @Test public void get5BestSellersMerlin() throws IOException { File in = getFile("/merlin/BestsellersMerlin.html"); Document doc = Jsoup.parse(in, "UTF-8"); List&lt;Book&gt; actualBooks = merlinFetchingBookService.get5BestSellersMerlin(doc); List&lt;Book&gt; expectedBooks = prepare5Bestsellers(); assertEquals(expectedBooks, actualBooks); } @Test public void get15BooksFromCategory() throws IOException { File in = getFile("/merlin/CrimeCategoryMerlin.html"); Document doc = Jsoup.parse(in, "UTF-8"); List&lt;Book&gt; actualBooks = merlinFetchingBookService.get15BooksFromCategory(doc); List&lt;Book&gt; expectedBooks = prepare15CrimeBooks(); assertEquals(expectedBooks, actualBooks); } private File getFile(String resourceName) { try { return new File(EmpikFetchingBookServiceTest.class.getResource(resourceName).toURI()); } catch (URISyntaxException e) { throw new IllegalStateException(e); } } } </code></pre> <p><strong>BestsellersServiceTest</strong></p> <pre><code>package bookstore.scraper.book.scrapingtypeservice; import bookstore.scraper.book.Book; import bookstore.scraper.dataprovider.EmpikBookProvider; import bookstore.scraper.dataprovider.MerlinBookProvider; import bookstore.scraper.enums.Bookstore; import bookstore.scraper.fetcher.empik.EmpikFetchingBookService; import bookstore.scraper.fetcher.merlin.MerlinFetchingBookService; import bookstore.scraper.urlproperties.EmpikUrlProperties; import bookstore.scraper.urlproperties.MerlinUrlProperties; import bookstore.scraper.utilities.JSoupConnector; import org.jsoup.nodes.Document; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import java.util.List; import java.util.Map; import static bookstore.scraper.dataprovider.MergedBestsellersMapProvider.prepareExpectedMergedBestSellerMap; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class BestsellersServiceTest { @Mock private EmpikFetchingBookService empikBookService; @Mock private MerlinFetchingBookService merlinBookService; @Mock private EmpikUrlProperties empikUrlProperties; @Mock private MerlinUrlProperties merlinUrlProperties; @Mock private EmpikUrlProperties.Empik empikMock; @Mock private MerlinUrlProperties.Merlin merlinMock; @Mock JSoupConnector jSoupConnector; @InjectMocks private BestSellersService bestSellersService; @Test public void getBestSellers() { List&lt;Book&gt; merlinBestsellers = MerlinBookProvider.prepare5Bestsellers(); List&lt;Book&gt; empikBestsellers = EmpikBookProvider.prepare5Bestsellers(); Document empikDocument = mock(Document.class); Document merlinDocument = mock(Document.class); when(jSoupConnector.connect("https://www.empik.com/bestsellery/ksiazki")).thenReturn(empikDocument); when(empikUrlProperties.getEmpik()).thenReturn(empikMock); when(empikMock.getBestSellers()).thenReturn("https://www.empik.com/bestsellery/ksiazki"); when(empikBookService.get5BestSellersEmpik(empikDocument)).thenReturn(empikBestsellers); when(jSoupConnector.connect("https://merlin.pl/bestseller/?option_80=10349074")).thenReturn(merlinDocument); when(merlinMock.getBestSellers()).thenReturn("https://merlin.pl/bestseller/?option_80=10349074"); when(merlinUrlProperties.getMerlin()).thenReturn(merlinMock); when(merlinBookService.get5BestSellersMerlin(merlinDocument)).thenReturn(merlinBestsellers); Map&lt;Bookstore, List&lt;Book&gt;&gt; actualMap = bestSellersService.getBestSellers(); Map&lt;Bookstore, List&lt;Book&gt;&gt; expectedMap = prepareExpectedMergedBestSellerMap(); assertEquals(expectedMap, actualMap); } } </code></pre> <p>Those are main classes that I want to be reviewed. Thanks a lot for each suggestion/opinion!</p>
[]
[ { "body": "<p>I was interested to see your domain model, the <code>Book</code> class.</p>\n\n<p>I noticed that you are using <code>Lombok</code>, <code>@EqualsAndHashCode</code>, override <code>equals</code>, <code>hashCode</code> and it has the builder pattern implemented. </p>\n\n<ul>\n<li>Why did you add <code>@EqualsAndHashCode</code> and then implemented both methods? You need to decide which approach you want.</li>\n<li>Why did you implement the builder pattern instead of using <code>@Builder</code> Lombok annotation? Your approach seems inconsistent.</li>\n</ul>\n\n<p>I used to use Lombok and even their advanced features but stopped using this library. It was so easy to slap bunch of annotation and move one creating classes with bunch of code that was not needed. There are articles explaining other reasons why not to use Lombok. My advise is to not to use it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-06T08:05:35.790", "Id": "438164", "Score": "0", "body": "Good point. I will read about Lombo, but in this project I think I'm gonna use it. I'm gonna also fix things which you mentioned. Thanks a lot." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-05T23:07:37.560", "Id": "225619", "ParentId": "225457", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T12:27:47.160", "Id": "225457", "Score": "2", "Tags": [ "java" ], "Title": "Backbone of bookscraper" }
225457
<p>Question - Write a function that takes an unsigned integer and return the number of '1' bits it has (also known as the Hamming weight).</p> <pre><code>int hammingWeight(uint32_t n) { int count = 0; while(n&gt;0){ count+=n&amp;1; n&gt;&gt;=1; } return count; } </code></pre> <p>Can you come up with a better method?</p> <p>One gentleman came up with this</p> <pre><code>int hammingWeight(uint32_t n) { int count = 0; while (n) { n &amp;= (n - 1); count++; } return count; } </code></pre> <p>How does one come up with such creative solutions?</p> <p>And do you have a better one or any improvements I can make to my solution?</p>
[]
[ { "body": "<p>(Because of the way Code Review works, only <em>your</em> code can be reviewed. Therefore, I will not say anything on the code written by \"one gentleman\".)</p>\n\n<p>The first thing I see is: <em>use consistent indentation and add spaces.</em> Your code becomes much more readable if you format it like this:</p>\n\n<pre><code>int hammingWeight(uint32_t n) {\n int count = 0;\n while (n &gt; 0) {\n count += n &amp; 1;\n n &gt;&gt;= 1;\n }\n return count;\n}\n</code></pre>\n\n<p>Also, it is probably a good idea to use <code>std::uint32_t</code> instead of <code>uint32_t</code> in C++.</p>\n\n<p>You can make this function <code>constexpr</code> and <code>noexcept</code>. Simple computations like this can be done at compile time, and benefit from inlining.</p>\n\n<p>This function can also be generalized to take any unsigned integer type. A template version may look like:</p>\n\n<pre><code>template &lt;typename T, std::enable_if_t&lt;std::is_integral_v&lt;T&gt; &amp;&amp; std::is_unsigned_v&lt;T&gt;&gt;&gt;\nconstexpr int hammingWeight(T n) noexcept\n{\n // the implementation is the same\n}\n</code></pre>\n\n<p>The implementation is good enough and very readable IMO. You don't have to get very creative unless measuring reveals the necessity of optimization.</p>\n\n<p>In C++20, we have a standard function for this &mdash; <code>std::popcount</code>, in header <code>&lt;bit&gt;</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T13:44:20.903", "Id": "225461", "ParentId": "225458", "Score": "1" } } ]
{ "AcceptedAnswerId": "225461", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T12:32:05.930", "Id": "225458", "Score": "1", "Tags": [ "c++", "bitwise" ], "Title": "LeetCode Count number of set bits solution" }
225458
<p>So the exercise is as follows: </p> <blockquote> <p>Try modifying Cacher to hold a hash map rather than a single value. The keys of the hash map will be the arg values that are passed in, and the values of the hash map will be the result of calling the closure on that key. Instead of looking at whether self.value directly has a Some or a None value, the value function will look up the arg in the hash map and return the value, if it’s present. If it’s not present, the Cacher will call the closure and save the resulting value in the hash map associated with its arg value.</p> <p>Another problem with the current Cacher implementation is that it only accepts closures that take one parameter of type u32 and return an u32. We might want to cache the results of closures that take a string slice and return usize values, for example. To fix this issue, try introducing more generic parameters to increase the flexibility of the Cacher functionality</p> </blockquote> <p>I tried to make Cacher as generic as I could so it could cache any type of K/V combination. I am looking for feedback on how I could've done it better. If there are any antipatterns in my approach. Am I making any foundational mistakes?</p> <p>My implementation of it is as under:</p> <p>lib.rs</p> <pre><code>use std::thread; use std::time::Duration; use std::error::Error; // fn simulated_expensive_calculation(intensity: u32) -&gt;u32 { // println!("Calculating slowly..."); // thread::sleep(Duration::from_secs(2)); // intensity // } pub fn run() -&gt; Result&lt;(),Box&lt;dyn Error&gt;&gt; { let simulated_user_specified_value = 10; let simulated_random_number = 7; generate_workout( simulated_user_specified_value, simulated_random_number ); Ok(()) } use std::collections::HashMap; use std::ops::Fn; struct Cacher&lt;K, V, T&gt; where T: Fn(K) -&gt; V, K: std::cmp::Eq + std::hash::Hash, { calculation: T, values: HashMap&lt;K, V&gt;, } use std::collections::hash_map::Entry; impl &lt;K, V, T&gt; Cacher&lt;K, V, T&gt; where T: Fn(K) -&gt; V, K: std::cmp::Eq + std::hash::Hash + std::marker::Copy + std::fmt::Debug, V: std::fmt::Debug { fn new&lt;E,F&gt;(calculation: T) -&gt; Cacher&lt;E, F, T&gt; where T: Fn(E) -&gt; F, E: std::cmp::Eq + std::hash::Hash { Cacher { calculation, values: HashMap::new(), } } fn value(&amp;mut self, arg: &amp;K) -&gt; &amp;V { /* eprintln!("arg: {:?}", *arg); let e = self.values.entry(*arg).or_insert((self.calculation)(*arg)); e */ if let Entry::Vacant(o) = self.values.entry(*arg) { o.insert((self.calculation)(*arg)); } &amp;self.values[arg] } } fn generate_workout(intensity: u32, random_number: u32) { let mut expensive_closure = Cacher::new(|intensity| { println!("Calculating slowly..."); thread::sleep(Duration::from_secs(5)); intensity }); if intensity &lt; 25 { println!( "Today, do {} pushups!", expensive_closure.value(&amp;intensity) ); println!( "Next, do {} situps!", expensive_closure.value(&amp;intensity) ); } else { if random_number == 3 { println!("Take a break today! Remember to stay hydrated!"); } else { println!( "Today, run for {} minutes!", expensive_closure.value(&amp;intensity) ); } } } </code></pre> <p>main.rs:</p> <pre><code>extern crate workout; use std::process; fn main() { if let Err(e) = workout::run() { eprintln!("Application error {}", e); process::exit(1); } } </code></pre> <h1>Code on rust playground</h1> <p><em>slightly modified so you can simply cut and paste it in foo.rs and run it without creating a whole thing</em> -- hehe pun intended</p> <pre><code>use std::process; fn main() { if let Err(e) = workout::run() { eprintln!("Application error {}", e); process::exit(1); } } mod workout { use std::thread; use std::time::Duration; use std::error::Error; // fn simulated_expensive_calculation(intensity: u32) -&gt;u32 { // println!("Calculating slowly..."); // thread::sleep(Duration::from_secs(2)); // intensity // } pub fn run() -&gt; Result&lt;(),Box&lt;dyn Error&gt;&gt; { let simulated_user_specified_value = 10; let simulated_random_number = 7; generate_workout( simulated_user_specified_value, simulated_random_number ); Ok(()) } use std::collections::HashMap; use std::ops::Fn; struct Cacher&lt;K, V, T&gt; where T: Fn(K) -&gt; V, K: std::cmp::Eq + std::hash::Hash, { calculation: T, values: HashMap&lt;K, V&gt;, } use std::collections::hash_map::Entry; impl &lt;K, V, T&gt; Cacher&lt;K, V, T&gt; where T: Fn(K) -&gt; V, K: std::cmp::Eq + std::hash::Hash + std::marker::Copy + std::fmt::Debug, V: std::fmt::Debug { fn new&lt;E,F&gt;(calculation: T) -&gt; Cacher&lt;E, F, T&gt; where T: Fn(E) -&gt; F, E: std::cmp::Eq + std::hash::Hash { Cacher { calculation, values: HashMap::new(), } } fn value(&amp;mut self, arg: &amp;K) -&gt; &amp;V { /* eprintln!("arg: {:?}", *arg); let e = self.values.entry(*arg).or_insert((self.calculation)(*arg)); e */ if let Entry::Vacant(o) = self.values.entry(*arg) { o.insert((self.calculation)(*arg)); } &amp;self.values[arg] } } fn generate_workout(intensity: u32, random_number: u32) { let mut expensive_closure = Cacher::new(|intensity| { println!("Calculating slowly..."); thread::sleep(Duration::from_secs(5)); intensity }); if intensity &lt; 25 { println!( "Today, do {} pushups!", expensive_closure.value(&amp;intensity) ); println!( "Next, do {} situps!", expensive_closure.value(&amp;intensity) ); } else { if random_number == 3 { println!("Take a break today! Remember to stay hydrated!"); } else { println!( "Today, run for {} minutes!", expensive_closure.value(&amp;intensity) ); } } } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T13:57:00.277", "Id": "225462", "Score": "1", "Tags": [ "rust", "hash-map" ], "Title": "Rust book ch 13 Closures + HashMap exercise" }
225462
<p>I am currently working on an Node based Express application. I have found Express's middlewares approach quite pleasing however, we all run in scenarios where a certain route or routes don't need a specific middleware.</p> <p>I have found two approaches:</p> <ol> <li><p>Adding middleware globally exempting the routes it doesn't need to run for. <code>express-jwt</code> is good example of this:</p> <pre><code>app.use(jwt().unless( '/someroute', '/someotherroute', ... ); app.use(someothermiddleware().unless( '/someroute2', ... ); app.use(someothermiddlewaretoo().unless( '/someroute3' ... ); </code></pre></li> <li><p>Adding middleware(s) to each route you define:</p> <pre><code>route.get( '/someroute1', [ jwt(), someothermiddleware, someothermiddlewaretoo ], function(req, res) { ... } ); route.get( '/someroute2', [ jwt(), someothermiddlewaretoo ], function(req, res) { ... } ); route.get( '/someroute3', [ jwt(), someothermiddleware ], function(req, res) { ... } ); </code></pre></li> </ol> <p>I can see that Approach #2 looks like some work however, I believe Approach #2 is way better in terms of a large application where you might have nested routers. <em>You can be on any route and know exactly what middlewares it gets executed with</em>.</p> <p>With Approach #1, you get things up and running easily but, it will be pain to check if this route is being included for specific middleware every time you try to fix a bug.</p> <p><strong>Which approach is better in your opinion? Or, is there another approach that you would like to share?</strong></p>
[]
[ { "body": "<p>I personally prefer <strong>Approach 2</strong> since it will increase readability and you can easily find out which middle-ware are applied to a route rather than to go to each excepted middle-ware and calculate. That is a lot of work for future purpose. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-08T09:42:04.757", "Id": "438474", "Score": "0", "body": "Agreed. Approach #2 seems better. But, I would advise creating *middleware groups* and apply groups to the routes because, if you need to apply another middleware, you can add it to middleware group and avoid having to put it on per-route basis." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-08T09:52:02.967", "Id": "438475", "Score": "0", "body": "For clarity, assume you have **middlewares** folder and within it, all middlewares as separate files and an index.js files that imports those middlewares and export them as a single object. In addition to exporting the middlewares individually, you can create an array of middlewares as a group (say *auth* group) and apply that group to routes exempting routes that need special treatment. You can apply some specific middleware or other group to those special routes. In this way, if you need to add another middleware when user is authenticated, you can update just *auth* group array." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-07T15:44:00.777", "Id": "225725", "ParentId": "225464", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T14:21:58.977", "Id": "225464", "Score": "2", "Tags": [ "javascript", "node.js", "comparative-review", "express.js" ], "Title": "Middlewares with Route definition or Routes with Middleware definition" }
225464
<p>I want to delete files from folder, which are not stored in DB, and DB records, which no more linked to files. My code:</p> <pre class="lang-cs prettyprint-override"><code> public async Task DeleteNonExistingImagesInFolder(string imagesDirectory) { var images = _unitOfWork.Images.AsQueryable(); DirectoryInfo d = new DirectoryInfo(imagesDirectory); FileInfo[] Files = d.GetFiles(); await Task.Run(() =&gt; { foreach (var file in Files) { if (!images.Where(i =&gt; i.Path == file.FullName).Any()) file.Delete(); } }); } public async Task DeleteNonExistingImagesInDB(string imagesDirectory) { var images = _unitOfWork.Images.AsQueryable(); DirectoryInfo d = new DirectoryInfo(imagesDirectory); FileInfo[] Files = d.GetFiles(); await Task.Run(() =&gt; { foreach (var image in images) { if (!Files.Where(f =&gt; f.FullName == image.Path).Any()) _unitOfWork.Images.Remove(image.Id); } }); _unitOfWork.Complete(); } </code></pre> <p>Is there a better way to do this faster and with less code?</p> <h2>UPD</h2> <p>I call these methods in my web-api controller. Here is code:</p> <pre class="lang-cs prettyprint-override"><code> [Authorize(Roles="Admin")] [Route("delete")] [HttpDelete] public async Task&lt;IActionResult&gt; ClearNonExisting() { try { _logger.Warn("Deleting redundant images."); await _imageService.DeleteNonExistingImagesInFolder(_ImageDirectory); _logger.Warn("Deleting empty image links."); await _imageService.DeleteNonExistingImagesInDB(_ImageDirectory); return Ok(); } catch { _logger.Fatal("Exception while clearing empty links from DB and deleting redundant images."); return StatusCode(500); } } </code></pre> <p>I using a generic repository to operate Image records. Repository code:</p> <pre class="lang-cs prettyprint-override"><code> public class Repository&lt;TEntity&gt; : IRepository&lt;TEntity&gt; where TEntity : class { protected readonly DbContext Context; public Repository(DbContext context) { Context = context; } public void Remove(int id) { try { Context.Set&lt;TEntity&gt;().Remove(Get(id)); } catch (Exception e) { throw new DataAccessException($"Cannot remove {typeof(TEntity)} #{id}.", e); } } public void RemoveRange(IEnumerable&lt;TEntity&gt; entities) { try { Context.Set&lt;TEntity&gt;().RemoveRange(entities); } catch (Exception e) { throw new DataAccessException($"Cannot remove range of {typeof(TEntity)}s.", e); } } public IQueryable&lt;TEntity&gt; AsQueryable() { try { return Context.Set&lt;TEntity&gt;().AsQueryable(); } catch (Exception e) { throw new DataAccessException($"Cannot return IQueryable&lt;{typeof(TEntity)}&gt;.", e); } } public void Add(TEntity entity) { try { Context.Set&lt;TEntity&gt;().Add(entity); } catch(Exception e) { throw new DataAccessException($"Cannot add new {typeof(TEntity)}.", e); } } public void AddRange(IEnumerable&lt;TEntity&gt; entities) { try { Context.Set&lt;TEntity&gt;().AddRange(entities); } catch (Exception e) { throw new DataAccessException($"Cannot add range of {typeof(TEntity)}s.", e); } } public IEnumerable&lt;TEntity&gt; Find(Expression&lt;Func&lt;TEntity, bool&gt;&gt; predicate) { try { return Context.Set&lt;TEntity&gt;().Where(predicate); } catch (Exception e) { throw new DataAccessException($"Cannot find the {typeof(TEntity)}s with | {predicate.ToString()} | predicates.", e); } } public TEntity Get(int id) { try { return Context.Set&lt;TEntity&gt;().Find(id); } catch (Exception e) { throw new DataAccessException($"Cannot get {typeof(TEntity)} #{id}.", e); } } public IEnumerable&lt;TEntity&gt; GetAll() { try { return Context.Set&lt;TEntity&gt;().ToList(); } catch (Exception e) { throw new DataAccessException($"Cannot get all {typeof(TEntity)}s.", e); } } public IEnumerable&lt;TEntity&gt; AsEnumerable() { try { return Context.Set&lt;TEntity&gt;().AsEnumerable(); } catch (Exception e) { throw new DataAccessException($"Cannot return IEnumerable&lt;{typeof(TEntity)}&gt;.", e); } } public void Update(int id, TEntity entity) { try { var entry = Context.Entry(Get(id)); entry.CurrentValues.SetValues(entity); entry.State = EntityState.Modified; } catch (Exception e) { throw new DataAccessException($"Cannot update values of {typeof(TEntity)} #{id}.", e); } } } </code></pre> <h2>UPD 2</h2> <p>UnitOfWork code:</p> <pre class="lang-cs prettyprint-override"><code>public class AgencyUnitOfWork:IAgencyUnitOfWork { private readonly AgencyContext _context; private IArticleRepository articleRepository; public IArticleRepository Articles =&gt; articleRepository ?? (articleRepository = new ArticleRepository(_context)); private IContactRepository contactRepository; public IContactRepository Contacts =&gt; contactRepository ?? (contactRepository = new ContactRepository(_context)); private IRealtorRepository realtorRepository; public IRealtorRepository Realtors =&gt; realtorRepository ?? (realtorRepository = new RealtorRepository(_context)); private IRepository&lt;Image&gt; imageRepository; public IRepository&lt;Image&gt; Images =&gt; imageRepository ?? (imageRepository = new Repository&lt;Image&gt;(_context)); /// &lt;summary&gt; /// Constructor with DbContext and needed Repositories. /// &lt;/summary&gt; /// &lt;param name="context"&gt;Context to work with.&lt;/param&gt; [Inject] public AgencyUnitOfWork(AgencyContext context) { _context = context; } public int Complete() { return _context.SaveChanges(); } public void Dispose() { _context.Dispose(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T14:28:58.777", "Id": "437804", "Score": "1", "body": "Why are you using `Task.Run` for this? Could you give us more details about your code? It'd be very helpful to know how you call these two methods." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T14:31:19.880", "Id": "437805", "Score": "0", "body": "@t3chb0t, I want them to complete asyncronously for faster result. Am I doing wrong?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T14:32:49.553", "Id": "437806", "Score": "1", "body": "I don't know, you're not telling us much about the context where you're using it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T14:37:03.653", "Id": "437807", "Score": "1", "body": "They're running synchronously (one after another). Is this what you wanted? We also need to see the `_unitOfWork` or at least know where you _commit_ the deletion. From your current code it looks like it should not delete any images from the database." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T14:45:19.577", "Id": "437809", "Score": "1", "body": "@t3chb0t, i just forgot about calling Complete() method." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T14:46:29.013", "Id": "437810", "Score": "1", "body": "`/*Other repository methods*/` - don't hesitate posting the complete class ;-] Code Review can handle quite a lot. The more the better. I wonder why you are deleting files from the database one by one when you have this API `RemoveRange`? Doing it with `Remove` is pretty inefficient." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T15:00:28.040", "Id": "437811", "Score": "0", "body": "I don't think that `Add`, `Update` or `Get` methods would help ¯\\\\_(ツ)_/¯. I use `Remove`, because in any way I must check every `Image` for existing file." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T15:05:33.830", "Id": "437812", "Score": "1", "body": "We are still missing a link between _unitOfWork_ and _repository_" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T15:18:15.140", "Id": "437814", "Score": "1", "body": "Great! I think we're good to go now ;-]" } ]
[ { "body": "<p>In <code>ClearNotExisting</code>, you log a message when something goes wrong, but it would probably make sense to record what went wrong (i.e. spit out some information about the exception).</p>\n\n<hr />\n\n<p>You have inline documentation in some places, but methods like <code>Complete</code> could really do with it (Will it throw if I call it multiple times? What is the return value? Can I make changes after calling <code>Complete</code>?). Personally, I'm of the opinion that any public API should have at least basic inline documentation, because otherwise I can't be sure that the person who wrote it knows what they were writing (which is usually the case with me).</p>\n\n<hr />\n\n<p>I'm not convinced that it is <code>DeleteNonExistingImagesInDB</code>'s responsibility to call <code>Complete</code> on the unit of work: what if you later decide to perform some other database maintenance task having called it? Then you transaction will be cut in two, and your unit-of-work will have become units-of-work.</p>\n\n<hr />\n\n<p>You should consider using a <code>HashSet</code> (or similar) to perform these checks:</p>\n\n<pre><code>if (!Files.Where(f =&gt; f.FullName == image.Path).Any())\n</code></pre>\n\n<p>If the number of files is big, this will be slow. Such a replacement is trivial, will generally improve the scalability of this 'out of database' method, and will make the code clearer as well:</p>\n\n<pre><code>HashSet&lt;string&gt; files = new HashSet&lt;string&gt;(d.GetFiles().Select(f =&gt; f.FullName));\nif (!Files.Contains(image.Path))\n</code></pre>\n\n<p>You could also achieve this with a <code>Where</code> clause, and then use the <code>RemoveRange</code> method in <code>DeleteNonExistingImagesInDB</code>. This may be more efficient, as t3chb0t has suggested.</p>\n\n<pre><code>_unitOfWork.Images.RemoveRange(images.Where(image =&gt; !Files.Contains(image.Path)));\n</code></pre>\n\n<p>Someone who knows how to use <code>DbContext</code>s seriously can probably suggest a solution that makes use of temporary tables and all that Jazz to avoid transferring the image information about and minimise the duration of the transaction, but I am not such a person.</p>\n\n<hr />\n\n<p>I find it a little unnerving that public instance method <code>DeleteNonExistingImagesInDB</code> takes the directory as a parameter: it would all too easy to call it with the wrong directory, and delete every record in the database (whereafter the cost would delete all the images, because the database is empty). This just feels wrong: it <em>looks</em> like it is meant to support multiple image directories, and feels like a general-purpose static method, but it is not.</p>\n\n<hr />\n\n<p>I would like to see a <code>null</code> check in <code>AgencyUnitOfWork..ctor</code>: it's meant to be injected, but that doesn't stop it being misused in some other fashion. Same with <code>Repository..ctor</code>.</p>\n\n<hr />\n\n<p>Your line-spacing is inconsistent in places (e.g. between <code>RemoveRange</code> and <code>AsQueryable</code>), which just makes the code that little bit more difficult to scan, and has a habit of changing over time, which just clutters commits and messes with the feel of the code.</p>\n\n<hr />\n\n<p>The exception message in <code>AsQueryable</code> is a bit off: I'm not sure that returning is really the problem, but it's good that the inner exception is there.</p>\n\n<pre><code>throw new DataAccessException($\"Cannot return IQueryable&lt;{typeof(TEntity)}&gt;.\", e);\n</code></pre>\n\n<hr />\n\n<p>If <code>AgencyUnitOfWork</code> is to support disposal of the underlying context, then you should consider having it formally implement <code>IDisposable</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T22:34:49.923", "Id": "225490", "ParentId": "225465", "Score": "4" } } ]
{ "AcceptedAnswerId": "225490", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T14:26:43.410", "Id": "225465", "Score": "2", "Tags": [ "c#", "file", "asp.net-core-webapi" ], "Title": "Delete redundant files in folder and db" }
225465
<p>This is from <a href="https://leetcode.com/problems/trapping-rain-water/" rel="noreferrer">Leetcode</a></p> <p><a href="https://i.stack.imgur.com/xLtop.png" rel="noreferrer"><img src="https://i.stack.imgur.com/xLtop.png" alt="Trapping Rain Water"></a></p> <p>My solution is based on Python 3. It was faster than 90% of solutions on Leetcode, but used too much memory. Please what makes this memory hungry? How can I make this more efficient?</p> <pre><code>def trap(height, bound=None): storage = 0 temp_storage = 0 left_bound = None max_left_bound = 0 for elevation in height: if bound and elevation == bound: storage += temp_storage return storage max_left_bound = max(elevation, max_left_bound) if not left_bound: left_bound = elevation continue block_capacity = left_bound - elevation if block_capacity &gt; 0: temp_storage += block_capacity continue storage += temp_storage temp_storage, left_bound = 0, elevation if not temp_storage: return storage height.reverse() r_capacity = trap(height, max_left_bound) storage += r_capacity return storage </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-05T17:36:38.203", "Id": "438088", "Score": "1", "body": "Without going into code details, I can see that this uses recursion. Python does not really optimize recursion A good guess would be to maybe try converting this in iterative format?" } ]
[ { "body": "<p>I'm not sure what you mean by &quot;used too much memory&quot; — if I try submitting a copy of your code now, then LeetCode says:</p>\n<blockquote>\n<p>Memory Usage: 12.3 MB, less than 57.53% of Python online submissions for Trapping Rain Water.</p>\n</blockquote>\n<p>It is impossible to know whether the 12.3 MB is a lot or a little without knowing what this includes and how big the test cases were, neither of which LeetCode tells us.</p>\n<h3>1. Review</h3>\n<ol>\n<li><p>I found it difficult to follow the algorithm because of the proliferation of similarly named variables. There are four variables that contain heights: <code>elevation</code>, <code>bound</code>, <code>left_bound</code> and <code>max_left_bound</code>. How do these variables relate to each other? Is <code>left_bound</code> actually a right bound when iterating over heights in reverse? There are three variables that contain amounts of water: <code>storage</code>, <code>temp_storage</code> and <code>block_capacity</code>. Again, how do these relate to each other?</p>\n<p>Finding good names for variables and writing comments to clarify any remaining difficulties, is crucial in writing code that will be maintainable when you come back to it after having forgotten how it works.</p>\n</li>\n<li><p>The <code>trap</code> function modifies the list <code>heights</code> (by reversing it). It's best if functions don't modify their arguments (unless modifying the arguments is the point). Otherwise callers will be surprised by the side-effects. In this case you could easily use <code>reversed(heights)</code> instead of <code>heights.reverse()</code>.</p>\n</li>\n<li><p>The code considers each vertical slice through the landscape in turn, adding <code>left_bound - elevation</code> (that is, the current water height minus the current land height) to the total trapped water. But in practice <code>left_bound</code> (the current water height) stays the same for several iterations of the loop, so we could wait until it changes and then add the block of water all at once. See §2 below for how to do this.</p>\n</li>\n</ol>\n<h3>2. Alternative solution</h3>\n<p>Consider a typical landscape filled with water:</p>\n<p><a href=\"https://i.stack.imgur.com/kA0Sc.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/kA0Sc.png\" alt=\"\" /></a></p>\n<p>If we ignore the difference between water and land, and just look at the overall surface level, it should be clear that the filled landscape is made up of rectangles arranged like this:</p>\n<p><a href=\"https://i.stack.imgur.com/MBBKC.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/MBBKC.png\" alt=\"\" /></a></p>\n<p>There is a central &quot;plateau&quot; whose height is the maximum height of the landscape, flanked by staircases that start low at the outside and rise up to the plateau.</p>\n<p>If we find the height of the plateau, which is just <code>max(landscape)</code>, then we can work inwards from the left and right ends, finding the rectangles in the rising staircases until we reach the plateau height. By summing the rectangles we get the overall area of the filled landscape, and by subtracting the land part, which is just <code>sum(landscape)</code>, we get the water part.</p>\n<pre><code>def trap2(landscape):\n &quot;&quot;&quot;Return area of water trapped by landscape (a list of heights).&quot;&quot;&quot;\n if not landscape:\n return 0\n plateau_height = max(landscape)\n plateau_width = len(landscape)\n total_area = 0\n for heights in (landscape, reversed(landscape)):\n height_max = i_max = 0 # maximum height so far and its index\n for i, height in enumerate(heights):\n if height &gt; height_max:\n total_area += (i - i_max) * height_max\n if height == plateau_height:\n plateau_width -= i\n break\n height_max = height\n i_max = i\n return total_area + plateau_height * plateau_width - sum(landscape)\n</code></pre>\n<p>It is a bit clearer, I hope, how this works, and it is several times faster than the code in the post. The reasons why this is faster are (i) the accumulation <code>total_area += ...</code> is done once per rectangle, not once per vertical slice; and (ii) the subtraction of the land part is done once by calling the built-in function <code>sum</code>, which runs in fast compiled code.</p>\n<p>The exact speedup depends on the shape of the landscape, but here's a test case where the revised code was about 8 times faster:</p>\n<pre><code>&gt;&gt;&gt; from random import choices\n&gt;&gt;&gt; from timeit import timeit\n&gt;&gt;&gt; HEIGHTS = choices(range(100), weights=(100,) + (1,) * 99, k=1000000)\n&gt;&gt;&gt; timeit(lambda:trap(HEIGHTS), number=1) # code in the post\n0.31537632799881976\n&gt;&gt;&gt; timeit(lambda:trap2(HEIGHTS), number=1) # revised code\n0.04002986599880387\n</code></pre>\n<p>But on LeetCode it runs in much the same time as the code in the post — clearly they are not try big enough test cases to detect the difference.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T11:50:53.053", "Id": "232143", "ParentId": "225467", "Score": "7" } } ]
{ "AcceptedAnswerId": "232143", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T14:52:52.450", "Id": "225467", "Score": "5", "Tags": [ "python", "algorithm", "python-3.x" ], "Title": "Trapping Rain Water in Python" }
225467
<p><a href="https://www.hackerrank.com/challenges/queue-using-two-stacks/problem" rel="noreferrer">Challenge</a></p> <p>Problem Statement - Implement a Queue using two Stacks</p> <p>I implemented <code>dequeue()</code> in <span class="math-container">\$O(1)\$</span> at the cost of <code>enqueue()</code> in <span class="math-container">\$O(n)\$</span></p> <pre><code>#include &lt;cmath&gt; #include &lt;cstdio&gt; #include &lt;vector&gt; #include &lt;iostream&gt; #include &lt;algorithm&gt; #include &lt;stack&gt; using namespace std; struct Queue{ stack&lt;int&gt; s1,s2; int dequeue(){ int x = s1.top(); s1.pop(); return x; } void peek(){ cout&lt;&lt; s1.top()&lt;&lt;"\n"; } void enqueue(int data){ while(!s1.empty()){ s2.push(s1.top()); s1.pop(); } s1.push(data); while(!s2.empty()){ s1.push(s2.top()); s2.pop(); } } }; int main() { int t; cin&gt;&gt;t; Queue q; while(t--){ int k; cin&gt;&gt;k; switch(k){ case 1: int x; cin&gt;&gt;x; q.enqueue(x); break; case 2: q.dequeue(); break; case 3: q.peek(); } } return 0; } </code></pre> <p>There are 15 test cases. This code runs properly for the first 5 test cases then I get a 'Time Limit Exceeded' message for the rest of test cases.</p> <p>This means the complexity of my program is too much.</p> <p>So I tried reversing it, I made enqueue() as <span class="math-container">\$O(1)\$</span> and dequeue() as <span class="math-container">\$O(n)\$</span> but even that did not change anything.</p> <p>What should I do to reduce time complexity of this code?</p>
[]
[ { "body": "<p>You might want to look at the <a href=\"https://www.hackerrank.com/challenges/queue-using-two-stacks/forum\" rel=\"nofollow noreferrer\">discussion tab</a> for why the code is timing out. Basically the code should reverse the input stack only when <code>peek()</code> or <code>dequeue()</code> is called, and not in <code>enqueue()</code>.</p>\n<p>The rest of this answer is a review of the code as posted and it ignores the fact that HackerRank supplied some of the code, such as the includes and the <code>using namespace std</code>. Issues such as readability and maintainability are beyond the scope of HackerRank, but are considerations when writing good code.</p>\n<h2>Avoid Using Namespace <code>std</code></h2>\n<p>If you are coding professionally you probably should get out of the habit of using the <code>using namespace std;</code> directive. The code will then more clearly define where the objects/functions are coming from (<code>std::cin</code>, <code>std::cout</code>). As you start using namespaces in your code, it is better to identify where each function comes from, because there may be function name collisions from different namespaces. The object <code>cout</code> you may override within your own classes. This <a href=\"//stackoverflow.com/q/1452721\">Stack Overflow question</a> discusses this in more detail.</p>\n<h2>Magic Numbers</h2>\n<p>Numeric constants in code are sometimes referred to as <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">Magic Numbers</a>, because there is no obvious meaning for them.\nThe values for the variable <code>k</code> are defined by the problem, but it might be better to use symbolic constants rather than raw numbers in the <code>switch</code> statement. That would make the code easier to read and maintain. C++ provides a couple of methods for this; there could be an <code>enum</code>, or they could be defined as constants using <code>const</code> or <code>constexpr</code>. Any of these would make the code more readable. There is a discussion of this <a href=\"//stackoverflow.com/q/47882\">on Stack Overflow</a>.</p>\n<h2>Use Descriptive Variable Names</h2>\n<p>The variable names <code>s1</code> and <code>s2</code> are not very clear, and if they weren't in <code>std::stack</code> declarations I really would have no idea what they were. Since this is a queue problem it might be better to name them <code>front</code> and <code>rear</code> to represent what they are used for. It is very hard to maintain code with variable names such as <code>s1</code>, <code>s2</code>, <code>q</code>, <code>t</code>, <code>k</code> and <code>x</code>. As an example, for <code>k</code> I might use <code>queryIndex</code>.</p>\n<p>Since the restrictions on all input indicates there will be no negative numbers, it might be better to use <code>unsigned</code> rather than <code>int</code>.</p>\n<h2>Prefer to Not Include What Isn't Necessary</h2>\n<p>It is much better to only include what is necessary in a source file. There are currently 6 headers included, but only two are necessary (<code>&lt;iostream&gt;</code> and <code>&lt;stack&gt;</code>) for this implementation. Including <code>&lt;cstdio&gt;</code> is bad because it might lead the programmer to use C I/O functions rather the C++ ones. Including only what is needed improves compile times, because the contents of all the includes are part of the compilation. It could lead to other problems if you are implementing your own class rather than using a C++ container class (such as <code>std::queue</code> from <code>#include &lt;queue&gt;</code>).</p>\n<pre><code>#include &lt;cmath&gt;\n#include &lt;cstdio&gt;\n#include &lt;vector&gt;\n#include &lt;iostream&gt;\n#include &lt;algorithm&gt;\n#include &lt;stack&gt;\n</code></pre>\n<h2>Prefer One Declaration Per Line</h2>\n<p>Maintaining code is easier when one can find the declarations for variables. It would be easier to find where <code>s2</code> is declared if it was on a separate line.</p>\n<pre><code> std::stack&lt;int&gt; s1, s2;\n</code></pre>\n<p>Versus</p>\n<pre><code> std::stack&lt;int&gt; s1;\n std::stack&lt;int&gt; s2;\n</code></pre>\n<p>Remember you may win a lottery and may not be the one maintaining the code.</p>\n<p>The same reasoning applies to 2 statements on a line, such as</p>\n<pre><code> int k; cin&gt;&gt;k;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T20:26:41.697", "Id": "225481", "ParentId": "225469", "Score": "9" } }, { "body": "<h1>Algorithmic complexity for combined operations</h1>\n\n<p>Containers are interesting elements in most programming languages: they have an internal state, namely their elements and therefore their size.</p>\n\n<p>This introduces an additional state compared to usual algorithmic asymptotical complexity analysis. For example, a naive implemented <code>std::vector::push_back</code> will yield <span class=\"math-container\">\\$\\mathcal O(n^2)\\$</span> complexity if <code>push_back</code> increases the capacity only by one:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>// pseudo-code, also very bad performance and no error handling, do not use!\nvoid vector::push_back(T value){\n if(_size == _capacity) {\n // has to move all elements and is therefore O(n)\n reserve(_capacity + 1);\n }\n _data[_size++] = value;\n}\n</code></pre>\n\n<p>While trivial, this code has a severe problem: we have to copy all elements in <em>ever</em> iteration. If we use <code>push_back</code> in a loop, we end up with a quadratic complexity.</p>\n\n<p>The real <code>push_back</code> has therefore some tricks up in its sleeves, as the standard dictates that it will have <span class=\"math-container\">\\$O(1)\\$</span> <em>amortized</em> complexity. More about that later in this review.</p>\n\n<p>However, this small introduction should give you a hint about the central flaw in your current approach.</p>\n\n<h2>A hidden quadratic term</h2>\n\n<blockquote>\n <p>I implemented <code>dequeue()</code> in <span class=\"math-container\">\\$O(1)\\$</span> at the cost of <code>enqueue()</code> in <span class=\"math-container\">\\$O(n)\\$</span></p>\n</blockquote>\n\n<p>For this task, it's much more important to see the cost on both functions for <span class=\"math-container\">\\$k\\$</span> enqueued elements, not a single one.</p>\n\n<p>So let's envision the queue <code>{1,2,3,4}</code>. How many steps do we need?</p>\n\n<pre><code>to enqueue 1: \n 1. put `1` in `s1`\nto enqueue 2:\n 1. move `1` from `s1` to `s2` \n 2. put `2` in `s1`\n 3. move `1` from `s2` to `s1`\n- to enqueue 3:\n 1. move `1` from `s1` to `s2`\n 2. move `2` from `s1` to `s2`\n 3. put `3` in `s1`\n 4. move `2` from `s2` to `s1`\n 5. move `1` from `s2` to `s1`\n- to enqueue 4:\n 1. move `1` from `s1` to `s2`\n 2. move `2` from `s1` to `s2`\n 3. move `3` from `s1` to `s2`\n 4. put `4` in `s1`\n 5. move `3` from `s2` to `s1`\n 6. move `2` from `s2` to `s1`\n 7. move `1` from `s2` to `s1`\n</code></pre>\n\n<p>We see that the <span class=\"math-container\">\\$n\\$</span>th element will take <span class=\"math-container\">\\$2(n-1)\\$</span> swaps. Therefore, if we insert a total of <span class=\"math-container\">\\$n\\$</span> elements into our queue, we end up with <span class=\"math-container\">\\$\\mathcal O(n^2)\\$</span> to complete all enqueues.</p>\n\n<p>We need to do better.</p>\n\n<h2>A better queue with two stacks</h2>\n\n<p>So let's get back to the drawing board. What do we need?</p>\n\n<ol>\n<li>We need to enqueue</li>\n<li>We need to dequeue</li>\n<li>We need to peek.</li>\n</ol>\n\n<p>None of those terms indicates that we need to have all data in <em>one</em> stack. So first of all, we need to use <strong>better names</strong>, because <code>s1</code> and <code>s2</code> are pretty bland and non-descriptive:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>class Queue{\n stack&lt;int&gt; in;\n stack&lt;int&gt; out;\n\n void flip(); // &lt; new\n\npublic:\n void enqueue(int);\n int dequeue();\n int peek();\n};\n</code></pre>\n\n<p>I'll implement the methods outside of the class declaration to keep the code segments short, but you're free to place them inline again. Note that I switched from a <code>struct</code> to a <code>class</code>, because its <code>Queue</code>s job to make sure that <code>in</code> and <code>out</code> are handled correct; no one else should be able to change them.</p>\n\n<p>What will we use <code>in</code> and <code>out</code> for? Well, as long as we have elements in <code>out</code>, we will use them for <code>dequeue</code> and <code>peek</code>. And whatever gets <code>enqueued</code> gets pushed right ontop of <code>in</code>, no questions asked.</p>\n\n<p>The critical part is how to get an element from <code>in</code> to <code>out</code>, right? I let you think about that for some paragraphs, but you may also stop here and try it yourself; the declaration above contains a clue.</p>\n\n<p>So, let's have a look at my proposal for the definition of <code>enqueue()</code>, <code>peek</code> and <code>dequeue()</code>:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>void Queue::enqueue(int value) {\n in.push(value);\n}\n\nint Queue::peek() {\n if (out.empty()) {\n flip();\n }\n return out.top();\n}\n\nint Queue::dequeue() {\n if (out.empty()) {\n flip();\n }\n int value = out.top();\n out.pop();\n return value;\n}\n</code></pre>\n\n<p>Note that the additional private method <code>flip</code> is yet missing. However, I will state the envisioned complexity:</p>\n\n<ul>\n<li>enqueue is <span class=\"math-container\">\\$\\mathcal O(1)\\$</span> (amortized)</li>\n<li>dequeue is <span class=\"math-container\">\\$\\mathcal O(1)\\$</span> (amortized)</li>\n<li>peek is <span class=\"math-container\">\\$\\mathcal O(1)\\$</span> (amortized)</li>\n</ul>\n\n<p>Intrigued? Great. So let's check <code>flip</code>:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>void Queue::flip() {\n while(not in.empty()) {\n out.push(in.top());\n in.pop();\n }\n}\n</code></pre>\n\n<p><code>flip</code> takes all elements in <code>in</code> and moves them to <code>out</code>. It thereby changes the order of the elements, so that the <code>top</code> in <code>in</code> will be the last to get moved out of <code>out</code>. Note that we call <code>flip</code> only when <code>out</code> is empty.</p>\n\n<h2>Amortized analysis</h2>\n\n<p>*\"Wait a second! That's <span class=\"math-container\">\\$\\mathcal O(n)\\$</span>\" I hear you say. And that's completely correct. However, how often do we need to call <code>flip</code>? Or, rather more important, <strong>how often do elements get moved</strong>?</p>\n\n<p>The answer on the latter question is: exactly one time from <code>in</code> to <code>out</code>. At no point will they move back. The number of <code>flip</code> calls is much trickier, though, but it doesn't really matter. At worst, <code>flip</code> may need to flip all elements, for example if we use it as follows:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>for(int i = 0; i &lt; 100; ++i) {\n queue.enqueue(i);\n}\nfor(int i = 0; i &lt; 100; ++i) {\n queue.dequeue(); // first dequeue will flip\n}\n</code></pre>\n\n<p>However, only the <strong>first</strong> dequeue will flip. All others will yield the element immediately. Therefore, if we enqueue <span class=\"math-container\">\\$n\\$</span> elements and then dequeue all of them, we end up with <code>dequeue()</code>'s complexity as:</p>\n\n<p><span class=\"math-container\">$$\\frac{n\\mathcal O(1) + \\mathcal O(n)}{n} = \\mathcal O(1).$$</span></p>\n\n<p>We can compare that with your original variant:\n<span class=\"math-container\">$$\\frac{n\\mathcal O(n)}{n} = \\mathcal O(n)$$</span></p>\n\n<p>This is why your code exceeded the time limit.</p>\n\n<h1>Further review on code</h1>\n\n<p>There are some other findings that don't need as much detail as the algorithm, but nonetheless can be improved:</p>\n\n<ul>\n<li>there are some unused includes (<code>&lt;vector&gt;</code>)</li>\n<li><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\"><code>using namespace std</code> is considered bad practice</a></li>\n<li>the names are misleading or at least not self-descriptive</li>\n<li><code>peek()</code> usually returns a value and does not print</li>\n<li>the <code>struct Queue</code> should have been a <code>class Queue</code> due to the assumption that the elements are always in the right order.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-04T06:43:11.353", "Id": "437872", "Score": "0", "body": "Thanks. This answer dives in a lot deeper than the question. I am reading the links you provided. Later I used simple arrays to implement stacks rather than STL stack and the solution got accepted." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-04T09:15:15.340", "Id": "437887", "Score": "1", "body": "You might consider `std::vector` as an alternative to an array-based stack, . `std::stack` usually uses `std::vector` underneath. You might as well cut out the middle-man and use `std::vector` and `std::vector::reverse` to make sure that `push_back` won't allocate for the first ~3k elements or so." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T20:32:56.007", "Id": "225482", "ParentId": "225469", "Score": "25" } }, { "body": "<p>One thing not already mentioned in the answers: When you have a member function which does not change the state of the object, then make it <code>const</code>:</p>\n\n<pre><code>// no\nvoid peek(){ cout&lt;&lt; s1.top()&lt;&lt;\"\\n\"; }\n\n// better\nvoid peek() const { cout&lt;&lt; s1.top()&lt;&lt;\"\\n\"; }\n\n// even better\nint peek() const { return s1.top(); }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-04T09:16:17.410", "Id": "437889", "Score": "2", "body": "Excellent addition, completely overlooked that." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-04T07:36:24.447", "Id": "225508", "ParentId": "225469", "Score": "7" } } ]
{ "AcceptedAnswerId": "225482", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T15:35:02.110", "Id": "225469", "Score": "11", "Tags": [ "c++", "programming-challenge", "time-limit-exceeded", "stack", "queue" ], "Title": "HackerRank Implement Queue using two stacks Solution" }
225469
<p>Does this code follow common best practices?</p> <p>I tried to keep the code simple and straight forward adding comments and spacing everything to be readable. My main concern is there a common practice that I did not apply, I am looking into a career change and want to include this in a portfolio for a jr position. I am currently self-taught and I don't know if the code screams that.</p> <p>Note: The reason I put the JS at the end, was just in case it took time to load all the html and css would have loaded and the visitor would have something to see. </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-css lang-css prettyprint-override"><code>* { padding: 0; margin: 0; } body{ background-color:#194E80; } .logo{ display:flex; margin:2em; justify-content:center; width:33%; height:33% } .logo div{ display:flex; height:100%; width:80%; margin:2em; align-items: center; justify-content:center; } @media screen and (min-width: 10em){ .logo div{ font-size: calc( 22px + (24 - 22) * (100vw - 400px) / (800 - 400) ); } } .logo h1{ font-family:'Roboto', sans-serif; color:white; text-align: center; } @media screen and (min-width:600px) { .content { flex-wrap:nowrap; } .image { flex-basis:200px; order:1; } article { flex-basis:1; order:2; } } .content{ display: flex; flex-direction: row; flex-wrap: wrap; justify-content: flex-start; align-items: stretch; } .image{ flex: 1 1 auto; align-self: auto; margin:1em; } .image img{ max-height:400px; max-width:700px; min-height:400px; min-width:300px; width:100%; height:auto; object-fit: contain; } @media screen and (min-width: 10em){ .title{ font-size: calc( 22px + (24 - 22) * (100vw - 400px) / (800 - 400) ); } } @media screen and (min-width: 10em){ .text{ font-size: calc( 26px + (24 - 26) * (100vw - 400px) / (800 - 400) ); } article{ flex: 1 1 auto; align-self: auto; margin:1em; font-family:'Roboto', sans-serif; color:white; text-align: center; } article h2{ margin-top:1.5em; } article p{ margin-top:3em; max-width:1000px; } #button{ background-color:#1BB9A0; width:200px; margin-left:38%; margin-right:38%; border:solid; border-color:#1BB9A0; border-radius:25px; } #button a:link{ text-decoration: none; color:white; } #button a:visited { text-decoration: none; color:white; } #button:hover{ background-color:#19A691; border-color:#19A691; } .call{ margin-top:2em; display: flex; flex-direction: column; flex-wrap: wrap; justify-content: center; align-items: center; font-family:'Roboto', sans-serif; color:white; text-align: center; } @media screen and (min-width: 10em){ .action_head{ font-size: calc( 22px + (24 - 22) * (100vw - 400px) / (800 - 400) ); } .action_head{ min-width:400px; max-width:900px; } @media screen and (min-width: 30em){ .timer h2{ font-size: calc( 10px + (24 - 10) * (100vw - 400px) / (800 - 400) ); } @media screen and (min-width: 15em){ .timer h3{ font-size: calc( 25px + (24 - 25) * (100vw - 400px) / (800 - 400) ); } .timer{ margin-top:2em; display: flex; flex-direction: row; flex-wrap: wrap; justify-content: center; } .timer h2{ margin-bottom:.2em; border:solid; border-color:#323334; border-radius:25px; background-color:#323334; width:200px; } #day{ flex: 1 1 auto; align-self: auto; margin:1em; font-family:'Roboto', sans-serif; color:white; text-align: center; } #hour{ flex: 1 1 auto; align-self: auto; margin:1em; font-family:'Roboto', sans-serif; color:white; text-align: center; } #minute{ flex: 1 1 auto; align-self: auto; margin:1em; font-family:'Roboto', sans-serif; color:white; text-align: center; } #sec{ flex: 1 1 auto; align-self: auto; margin:1em; font-family:'Roboto', sans-serif; color:white; text-align: center; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;title&gt; HAL App Manager 1.0 &lt;/title&gt; &lt;meta charset="UTF-8"&gt; &lt;meta name="description" content="Shop the Nadscollections.com official site. Discover the latest ready to wear, handbags, shoes and accessories collections by Nadia Persaud."&gt; &lt;meta name="keywords" content="handbags,shoes,accessories,Nadscollections, Nadia Persaud"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;link rel="stylesheet" type="text/css" href="main.css" /&gt; &lt;link href="https://fonts.googleapis.com/css?family=Roboto&amp;display=swap" rel="stylesheet"&gt; &lt;/head&gt; &lt;body&gt; &lt;main&gt; &lt;!--main container --&gt; &lt;nav class="logo"&gt; &lt;!--nav bar --&gt; &lt;div&gt; &lt;h1&gt;HAL App Manager&lt;/h1&gt; &lt;/div&gt; &lt;/nav&gt; &lt;!--end of nav bar --&gt; &lt;div class="content"&gt; &lt;!--content container --&gt; &lt;div class="image"&gt; &lt;!--main image --&gt; &lt;img id="imagess" src="#" alt="HAL Phone Icon" &gt; &lt;/div&gt; &lt;!--closing image --&gt; &lt;article&gt; &lt;!--text container --&gt; &lt;div class="title"&gt;&lt;!--main title for text--&gt; &lt;h2&gt; The Application Manger &lt;/br&gt; You've Been Waiting For&lt;/h2&gt; &lt;/div&gt;&lt;!--closing title--&gt; &lt;div class="text"&gt; &lt;!--main text for content --&gt; &lt;p&gt;Introducing the ultimate application launcher for ios and Android. With more power to control multiple applications at once, you've never had so much control. Get on the early access list to get access to in app perks only avalaible to our early subscribers.&lt;/p&gt; &lt;/div&gt; &lt;!--closing main text --&gt; &lt;div class="button"&gt; &lt;!--button for content --&gt; &lt;h2 id="button"&gt; &lt;a href="#"&gt; Get On The List! &lt;/a&gt; &lt;/h2&gt; &lt;/div&gt; &lt;!--closing button --&gt; &lt;/article&gt; &lt;!--closing text container --&gt; &lt;/div&gt; &lt;!--closing content container --&gt; &lt;div class="call"&gt; &lt;!--call to action container --&gt; &lt;div class="action_head"&gt;&lt;!--call to action heading --&gt; &lt;h2&gt; GET EXLUSIVE IN APP PERKS BY SIGNING UP BEFORE OUR OFFICIAL LAUNCH! &lt;/h2&gt; &lt;/div&gt; &lt;!--end of call to action heading --&gt; &lt;div class="timer"&gt; &lt;!--timer container --&gt; &lt;div id="day"&gt; &lt;!--day counter --&gt; &lt;/div&gt; &lt;!--end of day counter --&gt; &lt;div id="hour"&gt; &lt;!--hour counter --&gt; &lt;/div&gt; &lt;!--end of hour counter --&gt; &lt;div id="minute"&gt;&lt;!--min counter --&gt; &lt;/div&gt; &lt;!--end of min counter --&gt; &lt;div id="sec"&gt; &lt;!--sec counter --&gt; &lt;/div&gt; &lt;!--end of sec counter --&gt; &lt;/div&gt; &lt;!--end of timer container --&gt; &lt;/div&gt;&lt;!--end of call to action container --&gt; &lt;/main&gt; &lt;!--end of main container --&gt; &lt;script&gt; var i= 0; // starting image var images= []; //image array empty-array var time= 2000; //2 sec time interval //image list for image array images[0] = 'image_1.png'; //image array starting image images[1] = 'image_2.png'; images[2] = 'image_3.png'; //change image function function changeImg(){ document.getElementById("imagess").src = images[i]; //changes image on html side if(i &lt; images.length-1){ //if var i is less then the length of the array add one, length -1 because array list start with 0 and ends with 2. i++; } else{ // if var is more the array length set it back to 0 to start the slide again i = 0; } setTimeout("changeImg()", time);// the amount of time before the function run if statment } window.onload = changeImg; //when sites loads run script &lt;/script&gt; &lt;script&gt; // Set the date we're counting down to var countDownDate = new Date("Nov 5, 2020 15:37:25").getTime(); // Update the count down every 1 second var x = setInterval(function() { // Get today's date and time var now = new Date().getTime(); // Find the distance between now and the count down date var distance = countDownDate - now; // Time calculations for days, hours, minutes and seconds var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); // Display the result in the element with id day hours minute and sec document.getElementById("day").innerHTML = "&lt;h2&gt;"+days+"&lt;/h2&gt;" + "&lt;h3&gt;Day&lt;/h3&gt;"; document.getElementById("hour").innerHTML = "&lt;h2&gt;"+hours+"&lt;/h2&gt;" + "&lt;h3&gt;Hour&lt;/h3&gt;"; document.getElementById("minute").innerHTML = "&lt;h2&gt;"+minutes+"&lt;/h2&gt;" + "&lt;h3&gt;Minutes&lt;/h3&gt;"; document.getElementById("sec").innerHTML = "&lt;h2&gt;"+seconds+"&lt;/h2&gt;" + "&lt;h3&gt;Seconds&lt;/h3&gt;"; // If the count down is finished, write some text if (distance &lt; 0) { clearInterval(x); document.getElementById("day").innerHTML = days + "&lt;h3&gt;Expire&lt;/h3&gt;"; document.getElementById("hour").innerHTML = hours + "&lt;h3&gt;Expire&lt;/h3&gt;"; document.getElementById("minute").innerHTML = minutes + "&lt;h3&gt;Expire&lt;/h3&gt;"; document.getElementById("sec").innerHTML = seconds + "&lt;h3&gt;Expire&lt;/h3&gt;"; } }, 1000); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T17:54:27.683", "Id": "437835", "Score": "1", "body": "The meta keywords and description is from one of my other projects a fashion store." } ]
[ { "body": "<p>Consistently formatting your code will help it look professional. There are some slight variations in style but many conventions are well-established such as always putting a space before <code>{</code>.</p>\n\n<p>Be particularly strict about your indentation (everything inside <code>setInterval</code> needs one more) and don't mix tabs and spaces (such as the <code>align-self</code> lines). It's not cheating to have your editor format your code for you.</p>\n\n<p>I tend minimalist on comments (preferring to put effort into naming and refactoring instead). With that in mind, your comments are excessive. For example I would change this:</p>\n\n<pre><code> &lt;div id=\"day\"&gt; &lt;!--day counter --&gt;\n\n &lt;/div&gt; &lt;!--end of day counter --&gt;\n</code></pre>\n\n<p>To simply this:</p>\n\n<pre><code> &lt;div id=\"day-counter\"&gt;\n &lt;/div&gt;\n</code></pre>\n\n<p>See how the code documents itself?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-04T03:07:40.287", "Id": "227442", "ParentId": "225476", "Score": "2" } } ]
{ "AcceptedAnswerId": "227442", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T17:50:59.367", "Id": "225476", "Score": "2", "Tags": [ "javascript", "beginner", "css", "html5" ], "Title": "Simple landing page with a countdown timer and automatic slideshow with HTML,CSS,JS" }
225476
<blockquote> <p>The number 145 is well known for the property that the sum of the factorial of its digits is equal to 145:</p> <pre><code>1! + 4! + 5! = 1 + 24 + 120 = 145 </code></pre> <p>Perhaps less well known is 169, in that it produces the longest chain of numbers that link back to 169; it turns out that there are only three such loops that exist:</p> <pre><code>169 → 363601 → 1454 → 169 871 → 45361 → 871 872 → 45362 → 872 </code></pre> <p>It is not difficult to prove that EVERY starting number will eventually get stuck in a loop. For example,</p> <pre><code>69 → 363600 → 1454 → 169 → 363601 (→ 1454) 78 → 45360 → 871 → 45361 (→ 871) 540 → 145 (→ 145) </code></pre> <p>Starting with 69 produces a chain of five non-repeating terms, but the longest non-repeating chain with a starting number below one million is sixty terms.</p> <p>How many chains, with a starting number below one million, contain exactly sixty non-repeating terms?</p> </blockquote> <p>Here's my implementation in Python.</p> <pre><code>from math import factorial from time import time def get_factorial_sequence_length(number, factorials, lengths): """Return length of factorial sequence of number.""" if number in lengths: return lengths[number] chain = [number] while len(chain) == len(set(chain)): if chain[-1] in lengths: index = chain.index(chain[-1]) return lengths[chain[-1]] + len(chain[:index]) chain_next = sum(factorials[digit] for digit in str(chain[-1])) chain.append(chain_next) duplicate_index = chain.index(chain[-1]) for num in chain: index = chain.index(num) if index &lt;= duplicate_index: lengths[num] = len(chain[index:-1]) if index &gt; duplicate_index: lengths[num] = len(chain[duplicate_index:index]) + len(chain[index:-1]) return lengths[number] def get_sequence_counts(upper_bound, target_chain_size, lengths={}): """Return count of factorial sequences which have length target_chain_size within range upper_bound exclusive.""" factorials = {str(n): factorial(n) for n in range(10)} for number in range(1, upper_bound): chain_length = get_factorial_sequence_length(number, factorials, lengths) lengths[number] = chain_length if chain_length == target_chain_size: yield number if __name__ == '__main__': start_time = time() print(len(set(get_sequence_counts(1000000, 60)))) print(f'Time: {time() - start_time} seconds.') </code></pre>
[]
[ { "body": "<p>A few comments.</p>\n\n<p>First, your algorithm for computing the length of a chain is quadratic, because you convert your list to a set at each iteration. Second, there's a lot going on in <code>get_factorial_sequence_length</code>. I'd break the function up. You essentially have three parts: 1. Generate the elements of the sequence; 2: determine when to stop generating the sequence; 3. Determine the length of the non-repeating section (and memoize the length for all the seen numbers). The first part should be its own generator.</p>\n\n<pre><code>def generate_sequence(factorials, num):\n while True:\n yield num\n num = sum(factorials[digit] for digit in str(num)\n</code></pre>\n\n<p>Now <code>get_factorial_sequence_length</code> can look like:</p>\n\n<pre><code>def get_factorial_sequence_length(number, factorials, lengths):\n chain = []\n seen = set()\n for num in generate_sequence(factorials, number):\n if num in lengths:\n memoize_lengths_found(chain, num, lengths)\n return lengths[num] + len(chain)\n if num in seen:\n memoize_lengths_new(chain, num, lengths)\n return lengths[num]\n chain.append(num)\n seen.add(num)\n</code></pre>\n\n<p><code>memoize_lengths_found</code> and <code>memoize_lengths_new</code> could use some work on the names, and I leave the implementations as an exercise to the reader.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-04T02:17:47.023", "Id": "225498", "ParentId": "225478", "Score": "2" } }, { "body": "<h2>Dictionaries -vs- Lists</h2>\n\n<p>A dictionary is a very complex structure, designed to provide close to <span class=\"math-container\">\\$O(1)\\$</span> access to its members. To do this, each element is stored in a location based on the hash of a key. The modulo remainder of the hash and the binning size of the dictionary is computed to determine the \"bin\" the value is stored in. Since more than 1 value can hash to the same value, modulo the dictionary binning size, the bin is then scanned to find the key which matches the input key, and that value is returned.</p>\n\n<p>In contrast, to look up an entry from a list from a given position is simply retrieving the value from that position in the list. No hashing. No modulo arithmetic. No searching. Not only is the time complexity <span class=\"math-container\">\\$O(1)\\$</span>, the constant factor is also very small.</p>\n\n<p>As entries are added to a dictionary, the size of the dictionary grows. Eventually, adding an entry to the dictionary will cause a \"load_factor\" to be exceeded, and the number of bins will increase (probably double), and all of the keys will need to be rehashed, and the elements distributed into new bins. While this rebinning is fairly fast, it still takes time. If you add 1 million entries to a dictionary, you could expect it will rebin about <span class=\"math-container\">\\$\\log _2 1000000\\$</span> times.</p>\n\n<p>If you allocated an list of 1000000 entries, the allocation is done once up front, and you could look up the value of each of those entries in <span class=\"math-container\">\\$O(1)\\$</span> time. In addition, a list of 1000000 sequential numeric entries will take half the memory as the same information store in a dictionary, since no storage is required for the keys.</p>\n\n<p>Based on this, it seems that you could replace the <code>lengths</code> dictionary with a list of 1 million zeros. If <code>lengths[x] == 0</code>, then the length of the chain starting from <code>x</code> hasn't been computed yet. If <code>lengths[x] &gt; 0</code>, then it has been.</p>\n\n<pre><code>lengths = [0]*1000000\n</code></pre>\n\n<p>Except the chain starting at <code>999999</code> immediately exceeds 1 million; <code>9! = 362880</code>, so six <code>9</code> digits produces a 7 digit sum: <code>2177280</code>, which is beyond the length of our list. Fortunately the largest next term that can be produced by a 7 digit term less than <code>2177280</code> would be produced by <code>1999999</code>, which would result in <code>2177281</code>, and that puts a limit on the length of the list that would be required: <code>2177282</code>. Since the list requires approximately half the space as a dictionary, this works out to approximately the same memory requirement. And yet would be significantly faster.</p>\n\n<h2>Dramatically reducing memory</h2>\n\n<p>Based on \"<em>the longest non-repeating chain with a starting number below one million is sixty terms</em>\", we know we will only every need to store the values 0 through 60. These values are all within 0 to 255, so can be stored in a byte, which means we can use a <code>bytearray</code>, instead of a list.</p>\n\n<pre><code>lengths = bytearray(2_177_282)\n</code></pre>\n\n<h2>chain[-1]</h2>\n\n<p>Using <code>chain[-1]</code> to get the last value in the chain is awkward, and uses up time unnecessarily. In the majority of the cases, <code>chain_next</code> is that last value, since you <code>chain.append(chain_next)</code> at the end of your loop. The exception is the first time you enter the loop, you haven't computed <code>chain_next</code>, and <code>chain[-1]</code> is actually just <code>number</code>. Simply set <code>chain_next = number</code> before entering the loop, and you don't need <code>chain[-1]</code>:</p>\n\n<pre><code>chain_next = number\nchain = [chain_next]\nwhile len(chain) == len(set(chain)):\n if chain_next in lengths:\n index = chain.index(chain_next)\n return lengths[chain_next] + len(chain[:index])\n chain_next = sum(factorials[digit] for digit in str(chain_next))\n chain.append(chain_next)\n</code></pre>\n\n<p>What is <code>chain.index(chain[-1])</code>? Or <code>chain.index(chain_next)</code> in the new code? The index of the last entry in the list, assuming it is unique, which it must be due to the loop condition, so it will be <code>len(chain) - 1</code>. And <code>len(chain[:index])</code> is <code>index</code> by definition! So:</p>\n\n<pre><code>chain_next = number\nchain = [chain_next]\nwhile len(chain) == len(set(chain)):\n if chain_next in lengths:\n return lengths[chain_next] + len(chain) - 1\n chain_next = sum(factorials[digit] for digit in str(chain_next))\n chain.append(chain_next)\n</code></pre>\n\n<p>As @ruds point out, <code>len(chain) == len(set(chain))</code> is converting the <code>list</code> to a <code>set</code> at each iteration. See their approach for maintaining both a <code>seen</code> and <code>chain</code> to avoid that inefficiency.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-04T18:59:18.573", "Id": "225542", "ParentId": "225478", "Score": "1" } } ]
{ "AcceptedAnswerId": "225542", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T19:04:23.760", "Id": "225478", "Score": "4", "Tags": [ "python", "performance", "beginner", "python-3.x", "programming-challenge" ], "Title": "Project Euler # 74 Digit factorial chains in Python" }
225478
<p><strong>Explanation:</strong> I am working on String comparison in which I want to cross-compare the list of the same input string. For the same string, I am continuing the loop but if a single string will have similarity greater than 90% than it should not be appended to the refined Input list. The code on which I am working is down there:</p> <p><strong>Source Code:</strong></p> <pre><code>from DatabaseOperations import DatabaseOperations import csv from similarity.jarowinkler import JaroWinkler def refineInputFileData(inputList): jarowinkler = JaroWinkler() refinedInputList = [] refinedDict = {} for outer_keyword in inputList: if outer_keyword == "-": refinedInputList.append(outer_keyword) continue for inner_keyword in inputList: if outer_keyword == inner_keyword: continue similarity = jarowinkler.similarity(outer_keyword, inner_keyword) match_percentage = similarity * 100 if (match_percentage &gt;= 90): break else: refinedDict[outer_keyword] = "" refinedInputList.append(outer_keyword) return refinedInputList if __name__ == '__main__': inputList = getInputDataList() print(inputList) refineList = refineInputFileData(inputList) </code></pre> <p><strong>Data List:</strong></p> <pre><code>inputList = ['2018 form 1040 schedule 1', '2018 schedule 1', '2018 form 1040 schedule 2', '2018 form 1040 schedule a', 'schedule 1 2018', '2018 form 1040 schedule 3', '2018 form 1040 schedule 1 instructions', '2018 form 1040 schedule 4', '2018 form 1040 schedule 5', '1040 schedule 1', '2018 schedule 2', '1040 line 11', '2018 1040 schedule 1', '2018 schedule 1 instructions', '2018 schedule 3', '2018 schedule 5', '2018 1040 schedule a', '1040 line 12', 'form 1040 line 11', 'schedule 1 tax form 2018', 'schedule 2 2018', 'schedule 5 2018', '1040 schedule a 2018', 'schedule 3 tax form 2018', 'schedule 1 line 22', 'form 1040 schedule 1', 'schedule 2 tax form 2018', 'schedule 3 2018', 'schedule 4 tax form 2018', '1040 form 2018 schedule 1', '1040 line 9', '1040 schedule 1 2018', '2018 form 1040 schedule 6', '2018 form 1040 schedules', '2018 1040 schedule 2', '1040 form 2018 schedule a', 'schedule 5 tax form 2018', 'new 1040 schedules', 'form 1040 schedule a 2018', 'schedule 1040 for 2018', 'schedule 1 instructions 2018', '2018 schedule 1040', 'new schedule a', 'irs schedule 1 2018', 'new form 1040 schedules', 'line 22 schedule 1', 'irs schedule 3', 'irs 2018 schedule 1', 'form 1040 schedules 2018', 'new tax schedules 1 6', '2018 schedule a form 1040', '2018 federal tax schedule 1', 'form 1040 schedule 3', '2018 tax form schedule 3', 'what is schedule 1 tax form', 'irs schedule e instructions', '2018 tax return schedule', '1040 schedules 2018', '1040 schedule e instructions', 'schedule a tax form 2018', 'form 1040 schedule e pdf', 'what is schedule 4 other taxes', 'schedule 3 of income tax act', '2018 schedule se', '2018 irs schedule 1', '2018 form 1040 schedule e', 'how to fill out 1040 form 2018', 'schedule e instructions 2018', '2018 schedule a tax form', 'what will the 2018 1040 look like', '2018 form 1040 draft', 'new irs schedules', 'irs form schedule e form 1040', 'irs schedule se instructions', 'tax schedule e 2018', 'what is schedule e form 1040', '2018 tax year schedule a', 'proposed new tax form', 'irs 2018 forms schedule 1', '2018 tax forms schedule a', 'irs schedule one', 'new irs schedule 1', '1040 schedule e 2018', 'tax season 2018 schedule', 'irs form schedule a 2018', 'new tax schedules for 2018', 'schedule se instructions 2018', 'what is schedule e in tax return', 'irs 1040 line 21', 'schedule se 2018 instructions', 'irs gov schedule se', '2018 schedule e instructions', 'irs 2018 schedule a', 'form 1040 schedule e line 16 instructions', 'schedules 1 6 irs', 'irs schedule 3 for 2018', 'schedule e tax return', '2018 draft 1040', '2017 form 1040 schedule e', '2018 instructions schedule c', 'Keyword', '2018 irs schedule 1 form', 'irs schedule e 2018', 'schedule 3 income tax act', 'form 1040 line 12b', 'schedule a form 2018', 'irs 1040 schedule 2', '2018 schedule 4 instructions', '2018 tax forms schedule 1', '2018 schedule a form', 'form 1040 schedule e instructions', 'irs gov schedule c instructions', 'schedule one tax form', 'irs form 1040 schedule e for 2018', 'final 1040 form 2018', 'irs schedule 5 for 2018', 'tax schedule a 2018'] </code></pre>
[]
[ { "body": "<p>Specific suggestions:</p>\n\n<ol>\n<li><code>main</code> doesn't do anything with <code>refineList</code>.</li>\n<li>Rather than multiply by 100 a bunch of times you can simply check <code>similarity &gt;= 0.9</code></li>\n<li>The threshold should be configurable. You have many options for that, including at least a mandatory or optional parameter (using <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\"><code>argparse</code></a>) or a configuration file (using <a href=\"https://docs.python.org/3/library/configparser.html\" rel=\"nofollow noreferrer\"><code>configparser</code></a>).</li>\n<li>In the same vein the list of inputs could be taken from lines (or NUL-separated strings) in standard input.</li>\n<li>Why is there special casing for <code>outer_keyword == \"-\"</code>?</li>\n<li><code>refinedDict</code> is superfluous - it's set but never read.</li>\n<li><p>Since <code>match_percentage &gt;= 90</code> is the last check in that loop you can get rid of the <code>else</code> clause:</p>\n\n<pre><code>if similarity &lt; 0.9:\n refined_input_list.append(outer_keyword)\n</code></pre></li>\n</ol>\n\n<p>General suggestions:</p>\n\n<ol>\n<li><a href=\"https://github.com/ambv/black\" rel=\"nofollow noreferrer\"><code>black</code></a> can automatically format your code to be more idiomatic.</li>\n<li><a href=\"https://github.com/timothycrosley/isort\" rel=\"nofollow noreferrer\"><code>isort</code></a> can group and sort your imports automatically.</li>\n<li><p><a href=\"https://gitlab.com/pycqa/flake8\" rel=\"nofollow noreferrer\"><code>flake8</code></a> with a strict complexity limit will give you more hints to write idiomatic Python:</p>\n\n<pre><code>[flake8]\nmax-complexity = 4\nignore = W503,E203\n</code></pre></li>\n<li><p>I would then recommend adding <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">type hints</a> everywhere and validating them using a strict <a href=\"https://github.com/python/mypy\" rel=\"nofollow noreferrer\"><code>mypy</code></a> configuration:</p>\n\n<pre><code>[mypy]\ncheck_untyped_defs = true\ndisallow_untyped_defs = true\nignore_missing_imports = true\nno_implicit_optional = true\nwarn_redundant_casts = true\nwarn_return_any = true\nwarn_unused_ignores = true\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T21:41:30.030", "Id": "225487", "ParentId": "225479", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T19:15:42.710", "Id": "225479", "Score": "6", "Tags": [ "python", "python-3.x", "strings", "time-limit-exceeded", "edit-distance" ], "Title": "Search for strings in a list that have > 90% similarity" }
225479
<p>To better understand how discrete finite convolution works (read educational purposes) I wrote an all-python implementation of the convolution function. The idea was for it to give the same output as <code>numpy.convolve</code>, including the <code>mode</code> options. I generalized the code so that it functions for n-dimensional convolutions rather than just for 1-dimensional convolutions. This means it more closely matches the behavior of <code>scipy.signal.convolve</code>.</p> <pre><code>def py_nd_convolve(s, k, mode='full'): # All python implementation of n-dimensional scipy.signal.convolve for educational purposes # First ensure that one of the arrays fits inside of the other and by convention call this one # the kernel "k" and call the larger array the signal "s". if all(np.less_equal(k.shape, s.shape)): pass elif all(np.greater(k.shape, s.shape)): s, k = k.astype(float), s.astype(float) else: raise ValueError(f'Arrays have mismatched shapes: {k.shape} and {s.shape}') dim_list = np.arange(s.ndim) n_s = np.array(s.shape, dtype=int) n_k = np.array(k.shape, dtype=int) n_full = n_s + n_k - 1 out = np.zeros(n_full, dtype=float) zero_arr = np.zeros(s.ndim, dtype=int) for ind, val in np.ndenumerate(out): ind_arr = np.array(ind) # convert index tuple to numpy array so it can be used for arithmetic # i_min and i_max specify the allowed range which indices can take on in each dimension # to perform the convolution summation. The values for these are non-trivial near the # boundaries of the output array. i_min = np.maximum(zero_arr, ind_arr - n_k + 1) i_max = np.minimum(ind_arr, n_s - 1) # create a d-dimensional tuple of slices to slice both the kernel and signal to perform the convolution. s_slicer = tuple([slice(i_min[d], i_max[d] + 1) for d in dim_list]) k_slicer = tuple([slice(ind[d]-i_max[d], ind[d]-i_min[d]+1) for d in dim_list]) # element-wise product and summation of subset of signal and reversed kernel out[tuple(ind)] = np.multiply(s[s_slicer], np.flip(k[k_slicer])).sum() # This section of code clips the output data as per user specification to manage boundary effects n_min = np.zeros_like(n_full) n_max = n_full if mode == 'full': # take all possible output points, maximal boundary effects pass elif mode == 'valid': # eliminate any part of the output which is effect by boundary effects n_min = n_k-1 n_max = n_s elif mode == 'same': # clip the output so that it has the same shape as s n_min = (n_k-1)/2 n_max = n_s + (n_k-1)/2 slicer = [slice(int(n_min[d]), int(n_max[d])) for d in dim_list] # d-dimensional slice tuple for clipping return out[tuple(slicer)] </code></pre> <p>Since this code was for educational purposes I did not desire it to run fast, I namely desired for it to be very readable. As written the code is very very slow. While <code>scipy.signal.convolve</code> can convolve a <code>(200, 200)</code> array with a <code>(50, 50)</code> array in a few milliseconds this code takes a few seconds.</p> <p>I am not interested in making this code as fast as possible because I know that for that I could simply use the built in functions. I also know that I could possibly perform this operation faster by using an fft approach.</p> <h1>Question</h1> <p>Rather, I am curious if there are any glaring performance issues with the code that can be easily modified so that I can maintain a similar level of readability and logical flow but a higher level of performance.</p> <p>For example, am I making an egregious numpy mistakes such as copying arrays unnecessarily or misusing memory in a very bad way?</p> <ul> <li>I've noticed that I could flip the <code>k</code> array outside of the loop but it doesn't look like this will save much time.</li> <li>It looks like a big chunk of time is spent on defining <code>s_slicer</code> and <code>k_slicer</code>.</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T20:51:21.723", "Id": "437862", "Score": "0", "body": "Originally asked on Stackoverflow but I think it should have been here originally: https://stackoverflow.com/questions/57245494/all-python-implementation-of-n-dimensional-convolution-help-enhancing-performan" } ]
[ { "body": "<p>Specific suggestions:</p>\n\n<ol>\n<li>All t abbr mks th c hard 2 rd. Plz repl abbrs w/full wrds. Think of variable names as comments – they don't matter at all to the computer, but they do matter to anybody reading the code. A good rule of thumb is that if any of your comments explain <em>what</em> is coming up rather than <em>why</em> it was done like that, you can probably replace the comment with more elegant code. I've been working over a year with some colleagues on a medium-size new system, and we've taken this approach to heart: about 0.5% of the lines in Python files have comments on them.</li>\n<li>Conversions often take a lot of time, especially on a lot of items, and even more especially in a loop. Working with <em>only</em> lists or <em>only</em> tuples might speed up things a bit. In terms of readability, tuples are generally used when there is a fixed number of items, often of different types. Neither of these seem to apply to this code.</li>\n<li>The contents of the function can probably be split into at least three more for readability:\n\n<ol>\n<li>validation,</li>\n<li>mode handling, and</li>\n<li>the loop contents.</li>\n</ol></li>\n<li><p>The modes could be related as <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"nofollow noreferrer\"><code>Enum</code></a> values:</p>\n\n<pre><code>class Mode(Enum):\n FULL = \"full\"\n VALID = \"valid\"\n SAME = \"same\"\n\ndef …(…, mode: Mode = Mode.FULL):\n</code></pre></li>\n</ol>\n\n<p>General suggestions:</p>\n\n<ol>\n<li><a href=\"https://github.com/ambv/black\" rel=\"nofollow noreferrer\"><code>black</code></a> can automatically format your code to be more idiomatic.</li>\n<li><a href=\"https://github.com/timothycrosley/isort\" rel=\"nofollow noreferrer\"><code>isort</code></a> can group and sort your imports automatically.</li>\n<li><p><a href=\"https://gitlab.com/pycqa/flake8\" rel=\"nofollow noreferrer\"><code>flake8</code></a> with a strict complexity limit will give you more hints to write idiomatic Python:</p>\n\n<pre><code>[flake8]\nmax-complexity = 4\nignore = W503,E203\n</code></pre></li>\n<li><p>I would then recommend adding <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">type hints</a> everywhere and validating them using a strict <a href=\"https://github.com/python/mypy\" rel=\"nofollow noreferrer\"><code>mypy</code></a> configuration:</p>\n\n<pre><code>[mypy]\ncheck_untyped_defs = true\ndisallow_untyped_defs = true\nignore_missing_imports = true\nno_implicit_optional = true\nwarn_redundant_casts = true\nwarn_return_any = true\nwarn_unused_ignores = true\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-07T16:29:34.400", "Id": "438408", "Score": "0", "body": "Thank you for your recommendations. I rearranged the loop a bit and I do less type conversions. That seems to have helped a lot. Is it standard for me to post the updated code? Two questions. 1) I've been looking up about `Enum` values but I haven't found any example where they are used to help with function options. Could you create or point me to a basic example? 2) Regarding abbreviations I've kept some variables short because I think of them as variables in equations. I have a science background so lots of math. Do you think things like `n_s` should be renamed to `signal_shape`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-08T09:30:11.923", "Id": "438472", "Score": "0", "body": "You can post another question with the new code - that's welcome and fairly common." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-09T11:12:21.993", "Id": "438594", "Score": "0", "body": "`n_s` is almost completely meaningless to someone unfamiliar with the code, so `signal_shape` would almost certainly be better (if that is really what it is). It would help if I first knew what `s` and `k` are - to me they look interchangeable, like they be named `first` and `second` or `target` and `other`, or something." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T23:31:08.330", "Id": "225493", "ParentId": "225484", "Score": "3" } } ]
{ "AcceptedAnswerId": "225493", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T20:50:51.033", "Id": "225484", "Score": "5", "Tags": [ "python", "performance", "python-3.x", "reinventing-the-wheel" ], "Title": "All-Python implementation of n-dimensional convolution" }
225484
<p><a href="https://www.hackerrank.com/challenges/connected-cell-in-a-grid/problem" rel="nofollow noreferrer">https://www.hackerrank.com/challenges/connected-cell-in-a-grid/problem</a></p> <p><strong>problem statement:</strong></p> <blockquote> <p>Consider a matrix where each cell contains either a 1 or a 0. Any cell containing a 1 is called a filled cell. Two cells are said to be connected if they are adjacent to each other horizontally, vertically, or diagonally. In the following grid, all cells marked X are connected to the cell marked Y.</p> <p>XXX<br> XYX<br> XXX<br> If one or more filled cells are also connected, they form a region. Note that each cell in a region is connected to zero or more cells in the region but is not necessarily directly connected to all the other cells in the region.</p> <p>Given an matrix, find and print the number of cells in the largest region in the matrix. Note that there may be more than one region in the matrix.</p> <p>For example, there are two regions in the following matrix. The larger region at the top left contains cells. The smaller one at the bottom right contains .</p> <p>110<br> 100<br> 001 </p> </blockquote> <p><strong>my solution:</strong> </p> <pre><code># Complete the connectedCell function below. def connectedCell(matrix) highest_count = 0 visited = {} (0...matrix.length).each do |i| (0...matrix[0].length).each do |j| next if visited[[i,j]] if matrix[i][j] == 1 res = get_area_count([i,j], matrix) if res[0] &gt; highest_count highest_count = res[0] end visited = visited.merge(res[1]) end end end highest_count end def get_area_count(pos, matrix) q = [pos] visited = {} count = 0 while q.length &gt; 0 tile_pos = q.shift if !visited[tile_pos] count += 1 visited[tile_pos] = true q += nbrs(tile_pos, matrix) end end return [count, visited] end def nbrs(pos, matrix) right = [pos[0], pos[1] + 1] left = [pos[0], pos[1] - 1] top = [pos[0] + 1, pos[1]] bottom = [pos[0] - 1, pos[1]] top_right = [top[0], right[1]] bottom_right = [bottom[0], right[1]] top_left = [top[0], left[1]] bottom_left = [bottom[0], left[1]] positions = [right, left, top, bottom, top_right, bottom_right, top_left, bottom_left] positions.select{|npos| in_bounds?(npos, matrix.length, matrix[0].length) &amp;&amp; matrix[npos[0]][npos[1]] == 1} end def in_bounds?(pos, m, n) pos[0] &gt;= 0 &amp;&amp; pos[0] &lt; m &amp;&amp; pos[1] &gt;= 0 &amp;&amp; pos[1] &lt; n end </code></pre> <p><strong>thought process:</strong> My thought was to iterate through each cell in the matrix and then if it was a <code>1</code> I would do a depth-first traversal to find all other cells that had a <code>1</code>and were connected to the parent cell. then I would add 1 to the count whenever I visited a cell and add it to the <code>visited</code> hash so that it wouldn't be added to the count. I added helper methods for <code>in_bounds?</code> and <code>nbrs</code>mostly for better readability in the <code>get_area_count</code> method(which is the dfs implementation). The <code>nbrs</code> method is pretty verbose, but I kept it that on purpose because I'm preparing for technical interviews, where accuracy is important, and I thought actually listing out each direction would help in debugging / explaining it to the interviewer.</p>
[]
[ { "body": "<p>I really like clear and speaking method names, I quickly tried to refactor the first method but have had not much time, I hope this helps anyway.</p>\n\n<p>I have not understand the other initialization of the <code>visited</code> hash in the area_count method (yet).</p>\n\n<p>The new neighbors method indeed looks some kind of overloaded with information, no good idea yet how to change it, if needed at all as you described.</p>\n\n<pre><code>require 'json'\nrequire 'stringio'\n\ndef connectedCell(matrix, visited = {})\n (0...matrix.length).each do |row|\n (0...matrix[0].length).each do |col|\n next if visited[[row, col]]\n if matrix[row][col] == 1\n return update_count_stats(row, col, matrix, visited)\n end\n end\n end\nend\n\ndef update_count_stats(row, col, matrix, visited)\n result = area_count([row, col], matrix)\n visited.merge(result[1])\n result[0] &gt; 0 ? result[0] : 0\nend\n\ndef area_count(pos, matrix)\n q = [pos]\n visited = {}\n count = 0\n while q.length &gt; 0\n tile_pos = q.shift\n if !visited[tile_pos]\n count += 1\n visited[tile_pos] = true\n q += neighbors(tile_pos, matrix)\n end \n end\n\n return [count, visited]\nend\n\ndef neighbors(pos, matrix)\n right = [pos[0], pos[1] + 1]\n left = [pos[0], pos[1] - 1]\n top = [pos[0] + 1, pos[1]]\n bottom = [pos[0] - 1, pos[1]]\n\n top_right = [top[0], right[1]]\n bottom_right = [bottom[0], right[1]]\n top_left = [top[0], left[1]]\n bottom_left = [bottom[0], left[1]]\n\n positions = [right, left, top, bottom, top_right, bottom_right, top_left, bottom_left]\n positions.select{|npos| in_bounds?(npos, matrix.length, matrix[0].length) &amp;&amp; matrix[npos[0]][npos[1]] == 1}\nend\n\ndef in_bounds?(pos, number_of_columns, number_of_rows)\n pos[0] &gt;= 0 &amp;&amp; pos[0] &lt; number_of_columns &amp;&amp; pos[1] &gt;= 0 &amp;&amp; pos[1] &lt; number_of_rows \nend\n\nnumber_of_rows = 4 # just for testing, was gets.to_i\nnumber_of_columns = 4 # just for testing, was gets.to_i\nmatrix = Array.new(number_of_rows)\n\n# sample input\n# 1 1 0 0\n# 0 1 1 0\n# 0 0 1 0\n# 1 0 0 0\n\nnumber_of_rows.times do |i|\n matrix[i] = gets.rstrip.split(' ').map(&amp;:to_i)\nend\nresult = connectedCell matrix\nputs result\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-13T15:07:10.243", "Id": "226042", "ParentId": "225485", "Score": "1" } }, { "body": "<h2>Rubocop Report</h2>\n\n<h3>connectedCell</h3>\n\n<p>Avoid nested code blocks if clean alternative statements are available. \nFor instance, in method <code>connectedCell</code> you have the following block:</p>\n\n<blockquote>\n<pre><code>if matrix[i][j] == 1\n # .. code omitted\nend\n</code></pre>\n</blockquote>\n\n<p>Replace the if-statement with <code>next unless matrix[i][j] == 1</code> and you'll be able to reduce nesting with 1 level.</p>\n\n<p>The next part has a similar avoidable nesting, only this time we can use an inline if-statement.</p>\n\n<blockquote>\n<pre><code>if res[0] &gt; highest_count\n highest_count = res[0]\nend\n</code></pre>\n</blockquote>\n\n<p>This could be replaced with <code>highest_count = res[0] if res[0] &gt; highest_count</code>.</p>\n\n<p>And prefer to use <em>snake_case</em> for method names: <code>connected_cell</code>.</p>\n\n<p>The complete method could then be written as:</p>\n\n<pre><code>def connected_cell(matrix)\n highest_count = 0\n visited = {}\n\n (0...matrix.length).each do |i|\n (0...matrix[0].length).each do |j|\n next if visited[[i, j]]\n\n next unless matrix[i][j] == 1\n\n res = get_area_count([i, j], matrix)\n highest_count = res[0] if res[0] &gt; highest_count\n\n visited = visited.merge(res[1])\n end\n end\n\n highest_count\nend\n</code></pre>\n\n<h3>get_area_count</h3>\n\n<p>The while condition <code>while q.length &gt; 0</code> should be replaced by <code>until q.empty?</code> because it's considered a negative condition (pseudo: <code>while !empty</code>). </p>\n\n<p>We have another case of avoidable nesting: replace the <code>if !visited[tile_pos]</code> block with <code>next if visited[tile_pos]</code>.</p>\n\n<p>The method rewritten:</p>\n\n<pre><code>def get_area_count(pos, matrix)\n q = [pos]\n visited = {}\n count = 0\n until q.empty?\n tile_pos = q.shift\n next if visited[tile_pos]\n\n count += 1\n visited[tile_pos] = true\n q += nbrs(tile_pos, matrix)\n end\n\n [count, visited]\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-13T15:57:41.543", "Id": "226047", "ParentId": "225485", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T21:06:00.997", "Id": "225485", "Score": "2", "Tags": [ "ruby", "interview-questions", "matrix", "depth-first-search" ], "Title": "Ruby implementation for Hacker Rank connected cells in a grid" }
225485
<p>Here is my attempt to implement the Ukkonen algorithm for the <a href="http://rosalind.info/problems/lcsm/" rel="nofollow noreferrer">Finding a Shared Motif</a> problem on <a href="http://rosalind.info" rel="nofollow noreferrer">rosalind.info</a>.</p> <p>The code works, it produces a correct answer. It does so in 11 seconds. I am hoping to optimize it so that it runs faster.</p> <pre><code># http://rosalind.info/problems/lcsm/ from sys import stdin # A suffix tree is a tree that represents all the suffixes of a string. # This implementation allows the string to be extended at the end. # Conceptually, the edges between the nodes has some characters on it. # If one reads from the root node to a leaf node, one should read a # suffix of the string. If the last character is unique, the tree # contains all the suffixes. # In any tree, except the root, every node has a parent edge, therefore # We just store the edge information with the root. Because we have the # string, and edge labels are always substrings, it is enough to just # store the indices. # The parent and suffix link fields are a bit unfortunate. They are # artifacts needed for the construction of the tree, but otherwise # often unnecessary for using the tree. class suffix_tree_node: def __init__(self): self._begin = 0 self._end = 0 self._parent = None self._first_child = None self._sibling = None self._suffix_link = None def get_child(self): return self._first_child def get_sibling(self): return self._sibling # # Here is an implementation of the Ukkonen's suffix tree construction algorithm # The code is ported from my C++ implementation. # # The code is best understood by reading Dan Gusfield's book, because that's what # I read and implemented it based on the book. It is chapter 6.1 # # At a high level, the Ukkonen's algorithm allows growing the suffix tree one # character at a time. When the jth character is added, conceptually add all the # new suffixes to the tree. # # Now start reading the append() method to understand how it is achieved. # class suffix_tree: def __init__(self): self._root = suffix_tree_node() self._last_internal_node = None self._start = 0 self._s = [] # # To add a character to a suffix tree, we add all the new suffixes to the tree # A suffix starting from _start is added to the tree by calling the extension method # # To be consistent with the book, we will call each invocation of this method a phase. # # Conceptually, _start should start from 1. It is not in the code because of the # following rule: # # Once a leaf, always a leaf. # # Suppose the last phase introduced a leaf node, in this phase, the only thing that we # need to do for this phase is to extend the edge label. All leaves must terminate at the # end of the string, so if we implicity interprets the end of a leaf node to be the length # of the string and never explicitly store it, there is nothing we need to for them. Therefore # we skipped them all. # # Here begs the question, how do we know from 0 to _start - 1 were leaves in the last phase, # we will read more about that in the extension() method. # # Another things to notice is that if the already_in_tree returned by the extension method is True, # then we stop adding. There is because of the following rule: # # Rule 3 is a show stopper # # Without referring to the book, this would be a mystery. What is rule 3 anyway? Here is an # attempt to describe it succinctly. In the following, We use capital letter to represent strings # and lowercase character to represent characters. # # Suppose we know that in the last extension, we were trying to insert aXb into the tree and we # discovered that it is already there. That means aXb was a suffix in the last phase, so Xb must # also be a suffix in the last phase, so we can skip adding Xb. But not just that, any suffixes # of Xb # # Another interesting piece in this code is the next_node_cursor and next_text_cursor. They can # be understood as the cursors where we search in the tree. We will soon see how they are used # in the extension method. For now, what we needed to know is that the extension() method have # some way to speed up the next suffix insertion by maintaining these states. # # Now start reading the extension() method to see how a single suffix is added the tree. # def append(self, c): self._s.append(c) next_node_cursor = self._root next_text_cursor = self._start while (True): (already_in_tree, next_node_cursor, next_text_cursor) = self._extension(next_node_cursor, next_text_cursor) if already_in_tree: break else: self._start = self._start + 1 if self._start == len(self._s): break def get_root(self): return self._root def get_edge(self, node): length = self._length(node) return (node._begin, node._begin + length) # # The extension method add a suffix into the tree. We knew that the whole suffix besides the last character # must be already in the tree during the last phase, therefore the first thing to do is to find out where # to add the last character. This is done by the search() method. # # Without looking into the search() method yet, it is useful to describe how do we represent a location in # the tree. One could imagine the tree labels are highlighted and the highlight stop somewhere. There are two # cases, either the highlighting is filling every edge label, or the highlighting fill the last edge partially. # In both case, we can represent the location by a pair, the node that owns the edge label, and the number of # character filled by the edge label. That is how node_cursor and edge_cursor are interpreted. # # text_cursor is simply the index of the next character to be added in the tree, so there is no need for a variable # for it, it is simply len(self._s). # # the next_* variables are optimization. They allows the search to be short circuited so that it doesn't always # start from the beginning. For now, just assume the search method always returns node_cursor and edge_cursor at # the right place. # # Now here we are a few cases. The first branch is the case where the edge label is completely filled. If the node # is a leaf, there is nothing to do because the implicit interpretation of the leaf node will make sure the last # character is added. That said, the already_in_tree flag stays False, because conceptually we still added the # character to the tree. # # In case the edge label is completely filled and yet it is not a leaf, there are still two cases. It could be the # case that there is a child node that continues with the last character. In that case we know the suffix is already # in the tree, so we set already_in_tree to True and stop. Otherwise we create a new leaf node and stop. # # Similarly, in case the edge label is not completely filled, we check if the last character is already in the tree. # If it does, we set already_in_tree to True and stop. Otherwise, we have to split the edge. # # In all cases, we maintain two variables. search_end and new_internal_node. search_end represents the last node we # reached in the search, and new internal node represents the new internal node we created in the split edge case. # Theses two variables are used to build suffix links, a tool for speeding up searches. # # Suffix links only applies to nodes that are not leaves and not root. If such a node represents the prefix 'aX', # then the suffix link of it points to an internal node that represents X. Suppose during the insertion of 'aXY' # found such a link, there we could use that to speed to the search for 'XY' in the next extension. It is obvious # why it could be useful. What is not so obvious is that suffix links are easy to build and always available. # # A theorem in the book shows that if an internal node is created in the current extension, the next extension # would have found its suffix link. Therefore, we save the new_internal_node and set its suffix link to search_end # in the next iteration. # # To see how the suffix link is used to speed up the search, read the search() method now. # def _extension(self, next_node_cursor, next_text_cursor): node_cursor = next_node_cursor edge_cursor = self._length(node_cursor) already_in_tree = False (next_node_cursor, next_text_cursor, node_cursor, edge_cursor) = self._search(next_text_cursor, node_cursor, edge_cursor) next_text_char = self._s[len(self._s) - 1] search_end = None new_internal_node = None if edge_cursor == self._length(node_cursor): if (not (node_cursor == self._root)) and (node_cursor._first_child == None): pass else: search = node_cursor._first_child found = False while search != None: if self._first_char(search) == next_text_char: found = True break else: search = search._sibling if found: already_in_tree = True else: new_leaf = suffix_tree_node() new_leaf._begin = len(self._s) - 1 new_leaf._parent = node_cursor new_leaf._sibling = node_cursor._first_child node_cursor._first_child = new_leaf search_end = node_cursor else: next_tree_char = self._s[node_cursor._begin + edge_cursor] if next_text_char == next_tree_char: already_in_tree = True else: new_node = suffix_tree_node() new_leaf = suffix_tree_node() new_leaf._begin = len(self._s) - 1 new_node._begin = node_cursor._begin new_node._end = node_cursor._begin + edge_cursor node_cursor._begin = node_cursor._begin + edge_cursor new_node._parent = node_cursor._parent new_leaf._parent = new_node node_cursor._parent = new_node new_node._sibling = new_node._parent._first_child new_node._parent._first_child = new_node search = new_node while not (search == None): if (search._sibling == node_cursor): search._sibling = search._sibling._sibling break search = search._sibling new_node._first_child = new_leaf new_leaf._sibling = node_cursor node_cursor._sibling = None new_internal_node = search_end = new_node if not (self._last_internal_node == None): self._last_internal_node._suffix_link = search_end self._last_internal_node = None if not (new_internal_node == None): self._last_internal_node = new_internal_node return (already_in_tree, next_node_cursor, next_text_cursor) # # The search method does two things, it starts from the node_cursor and edge_cursor # and find all the way the all but last character of the string. In the process, we # also prepare the next_node_cursor and next_text_cursor for the next search. # # The search for the location is pretty straightforward, there are two things worth # notice. When we hit an edge, we just simply moved the cursor without checking the # character. It is because we knew it has to be correct. # # In the book, this implementation optimization is called the skip/count trick. # # We also set the next_node_cursor and next_text_cursor whenever we found a suffix link. # This is where the suffix link serve its purpose, it make the next search much faster # by starting closest to where we already knew it must reach. # def _search(self, text_cursor, node_cursor, edge_cursor): next_node_cursor = self._root next_text_cursor = text_cursor + 1 while (text_cursor &lt; len(self._s) - 1): node_length = self._length(node_cursor) if (edge_cursor == node_length): if not (node_cursor._suffix_link == None): next_node_cursor = node_cursor._suffix_link next_text_cursor = text_cursor next_char = self._s[text_cursor] child_cursor = node_cursor._first_child while True: if (self._first_char(child_cursor) == next_char): node_cursor = child_cursor edge_cursor = 0 break else: child_cursor = child_cursor._sibling else: text_move = len(self._s) - 1 - text_cursor edge_move = node_length - edge_cursor if text_move &gt; edge_move: move = edge_move else: move = text_move edge_cursor = edge_cursor + move text_cursor = text_cursor + move return (next_node_cursor, next_text_cursor, node_cursor, edge_cursor) def _length(self, node): if node == self._root: return 0 elif node._first_child == None: return len(self._s) - node._begin else: return node._end - node._begin def _first_char(self, node): return self._s[node._begin] # # This is a helper function for the longest_common_substring to perform a depth first search # For each node, we can imagine that it represents the set of suffixes that is descendant # leaf nodes does. # # We would like to know, for each node, the set of suffixes contains all suffixes that # start with each DNA. The prefix represented by the node is then a candidate for the longest # common substring. # # To compute that set of DNAs, we conceptually requires nodes to return what DNA do they have # but if we do so, all nodes must combine all the answer. And the combination time would take # time proportional to the number of children. That's not good. Instead, we can let the children # fill in the blanks. If we hand the same blank paper to all children and each of them mark on # it, then the combination is done implicitly. The time required to spend on the nodes is not # dependent of the number of children, but just on the number of DNAs, that makes the algorithm # O(NK), where N is the total length of the combined DNAs and K is the number of DNAs. # def longest_common_substring_find(tree, node, length, index, blanks, answer): (begin, end) = tree.get_edge(node) child = node.get_child() if child == None: begin = begin - length found = 0 for i in range(0, len(index)): if begin &lt;= index[i]: found = i break blanks[found] = True else: my_blanks = [False] * len(blanks) while not (child == None): longest_common_substring_find(tree, child, length + end - begin, index, my_blanks, answer) child = child.get_sibling() good = True for i in range(0, len(blanks)): blanks[i] = my_blanks[i] or blanks[i] good = good and my_blanks[i] if good: begin = begin - length length = end - begin if answer["max"] &lt; length: answer["max"] = length answer["begin"] = begin answer["end"] = end # # To find the longest common substring of a collection of texts # We concatenate the text together, using lowercase letters (which we know cannot be DNA characters) # to separate them and build a suffix tree. The longest common substring must be a common prefix # of all suffixes, so we will use the longest_common_substring_find to perform a depth first search # for the answer # def longest_common_substring(texts): separator = 'a' count = 0 tree = suffix_tree() index = [] all = "" for text in texts: for c in text: tree.append(c) count = count + 1 all = all + text + separator index.append(count) tree.append(separator) count = count + 1 separator = chr(ord(separator) + 1) answer = {} answer["max"] = -1 longest_common_substring_find(tree, tree.get_root(), 0, index, [False] * len(texts), answer) print(all[answer["begin"]:answer["end"]]) data = [] for line in stdin: data.append(line.strip()) data.append("&gt;") records = [] label = None dna = "" for line in data: if line[0] == '&gt;': if label != None: records.append(dna) label = line[1:] dna = "" else: dna = dna + line longest_common_substring(records) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T21:20:32.723", "Id": "225486", "Score": "2", "Tags": [ "python", "performance", "programming-challenge", "strings", "bioinformatics" ], "Title": "Rosalind - Finding a Shared Motif" }
225486
<p>I’m trying to target three words in a h1 for the organization name using to wrap each word and a unique ID to style each word via css. </p> <p>It looks like this:</p> <pre><code>&lt;h1 id=“orgName”&gt; &lt;span&gt; &lt;span id=“firstWord”&gt;The&lt;/span&gt; &lt;span id=“secondWord”&gt;Community&lt;/span&gt; &lt;span id=“thirdWord”&gt;Space&lt;/span&gt; &lt;/span&gt; &lt;/h1&gt; </code></pre> <p>However by using span and an ID for each work in the h1, I am causing the screen reader to pause after each word instead of speaking the organization name as a whole. Does anyone have any ideas to solve this issue?</p>
[]
[ { "body": "<p>You could try using a formating tag such as <code>&lt;b&gt;</code> or <code>&lt;i&gt;</code> instead of <code>&lt;span&gt;</code>.</p>\n\n<pre><code>&lt;h1 id=\"orgName\"&gt; \n &lt;span&gt;\n &lt;b id=\"firstWord\"&gt;The&lt;/b&gt;\n &lt;b id=\"secondWord\"&gt;Community&lt;/b&gt; \n &lt;b id=\"thirdWord\"&gt;Space&lt;/b&gt; \n &lt;/span&gt;\n&lt;/h1&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-14T11:48:38.773", "Id": "226111", "ParentId": "225489", "Score": "1" } } ]
{ "AcceptedAnswerId": "226111", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T22:27:40.627", "Id": "225489", "Score": "2", "Tags": [ "html", "css" ], "Title": "HTML and CSS word styling and screen reader usability" }
225489