body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I asked my <a href="https://stackoverflow.com/questions/68279814/vb-net-adding-items-to-a-reply-keyboard-for-telegram-bot">original question</a> and based on the answers got a version working. Essentially, I created a reply keyboard from the available product codes in my database table, with one button per row. What I want to know now is how to have more than one button per row. I would ideally like to have two or three buttons per row. My real problem is I cannot get my head around the Lists syntax, so I'd like some advice please.</p> <p>Here is a working piece of the code:</p> <pre><code>Select case lcase(Cmd) ' Various other case statements not shown Case &quot;products&quot;, &quot;product&quot;, &quot;items&quot; 'New KeyboardButton()() {New KeyboardButton() {New KeyboardButton(&quot;/pd 001&quot;), New KeyboardButton(&quot;/pd 002&quot;)}, New KeyboardButton() {New KeyboardButton(&quot;/pd 003&quot;), New KeyboardButton(&quot;/pd 004&quot;)}} Dim keyboardButtons As New List(Of KeyboardButton()) Bot.SendChatAction(message.Chat.Id, &quot;typing&quot;) MsgText = &quot;Our available __Products__&quot; &amp; vbCrLf mySQL = &quot;select * from products;&quot; Dim cs As String = &quot;URI=file:&quot; &amp; DBName Using con As New SQLiteConnection(cs) con.Open() Dim dr As SQLiteDataReader Using DBcmd As New SQLiteCommand(con) DBcmd.CommandText = mySQL dr = DBcmd.ExecuteReader() While dr.Read() MsgText &amp;= String.Format(&quot;*{0}* [{1}]({3}), Price: ${2}&quot;, dr(&quot;Code&quot;), Replace(dr(&quot;ProdName&quot;), &quot;-&quot;, &quot; &quot;), dr(&quot;Price&quot;), dr(&quot;ProdURL&quot;)) &amp; vbCrLf keyboardButtons.Add({New KeyboardButton($&quot;/pd {dr(&quot;Code&quot;)}&quot;)}) ' This is the line of interest End While End Using con.Close() End Using MsgText &amp;= vbCrLf &amp; &quot;Type '/pd *code*' to view a specific product *Note* Don't forget the *space* between /pd and the code&quot; &amp; vbCrLf MsgText &amp;= &quot;Please visit [our website](&quot; &amp; ConfigWebsite &amp; &quot;) for more information&quot; Dim keyboard As New ReplyKeyboardMarkup With {.Keyboard = keyboardButtons.ToArray()} keyboard.OneTimeKeyboard = True keyboard.ResizeKeyboard = True Bot.SendMessage(message.Chat.Id, MsgText, &quot;MarkdownV2&quot;,,, replyMarkup:=keyboard) Case Else ' etc End Select </code></pre> <p>Update: Here is a piece of code which adds a complete keyboard in one foul sweep:</p> <pre><code>Dim keyboard = New ReplyKeyboardMarkup With { .Keyboard = New KeyboardButton()() {New KeyboardButton() {New KeyboardButton(&quot;/pd 001&quot;), New KeyboardButton(&quot;/pd 002&quot;)}, New KeyboardButton() {New KeyboardButton(&quot;/pd 003&quot;)}}, .ResizeKeyboard = True } </code></pre> <p>Two buttons in the first row and one in the second.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-11T00:09:31.560", "Id": "521240", "Score": "0", "body": "We can't help with this part of the question: `What I want to know now is how to have more than one button per row. `" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T01:09:32.230", "Id": "521271", "Score": "0", "body": "That’s a pity. Thank you anyway" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-10T21:14:09.077", "Id": "263940", "Score": "0", "Tags": [ "vb.net", "telegram" ], "Title": "Building an array of KeyboardButton objects in a ReplyKeyBoardMarkup for a Telegram Bot" }
263940
<p>I'm reading on how to write proper testing suites <a href="https://martinfowler.com/bliki/PageObject.html" rel="nofollow noreferrer">here</a>. So I'm trying to follow the selenium example in the <a href="https://github.com/SeleniumHQ/selenium/wiki/PageObjects" rel="nofollow noreferrer">docs</a> which is in Java; I'm trying to translate it to Python since my app is written in Python.</p> <p>So I translated the example like so:</p> <pre><code>class LoginPage(unittest.TestCase): FE_URL = os.getenv('FE_URL') SERVER_URL = os.getenv('SERVER_URL') def __init__(self, driver): self.selenium = driver def find_button_by_text(self, text): buttons = self.selenium.find_elements_by_tag_name(&quot;button&quot;) for btn in buttons: if text in btn.get_attribute(&quot;innerHTML&quot;): return btn def login_page(self): self.selenium.get(self.FE_URL) WebDriverWait(self.selenium, MAX_WAIT).until( EC.presence_of_element_located((By.CLASS_NAME, &quot;login&quot;)) ) return self.selenium def type_username(self, username): username_locator = self.selenium.find_element_by_name(&quot;user[email]&quot;) username_locator.send_keys(username) return self.selenium def type_password(self, password): password_locator = self.selenium.find_element_by_name(&quot;user[password]&quot;) password_locator.send_keys(password) return self.selenium def submit_login(self): login_locator = self.find_button_by_text(&quot;Continue&quot;) login_locator.click() return self.selenium def submit_login_expecting_failure(self): self.login_page() self.submit_login() return self.selenium def login_as(self, username, password): login_page = self.login_page() self.type_username(username) self.type_password(password) return self.submit_login() </code></pre> <p>and then the actual test is here:</p> <pre><code>class MyTest(unittest.TestCase): USER_NAME = os.getenv('USER_NAME') PASSWORD = os.getenv('PASSWORD') @classmethod def setUpClass(cls): super(MyTest, cls).setUpClass() cls.selenium = WebDriver() # cls.selenium = webdriver.Firefox() cls.wait = WebDriverWait(cls.selenium, MAX_WAIT) @classmethod def tearDownClass(cls): cls.selenium.quit() super(MyTest, cls).tearDownClass() def test_login(self): login_page = LoginPage(self.selenium) main_page = login_page.login_as(self.USER_NAME, self.PASSWORD) WebDriverWait(main_page, MAX_WAIT).until( EC.presence_of_element_located((By.LINK_TEXT, &quot;Create alert&quot;)) ) def test_failed_login(self): login_page = LoginPage(self.selenium) page = login_page.submit_login_expecting_failure() alert = WebDriverWait(page, MAX_WAIT).until( EC.visibility_of_element_located((By.CLASS_NAME, &quot;alert-danger&quot;)) ) self.assertIn(&quot;Invalid Email or Password&quot;, alert.text) if __name__ == &quot;__main__&quot;: unittest.main() </code></pre> <p>The test works. Did I understand this correctly that the driver is setup in the actual test class and not in the <code>LoginPage</code>?</p> <p>Did I hide the actual mechanics of the test correctly? I am using <code>WebDriverWait</code> in the <code>LoginPage</code> class to wait till the page is loaded. I see this as kind of an assert replacement but I am not sure how else to wait for the page to have finished loading.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-11T13:35:04.967", "Id": "521256", "Score": "1", "body": "Do `FE_URL` and `SERVER_URL` take values that point to a publicly-accessible server you can share with us for the purposes of testing?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-11T16:22:11.103", "Id": "521260", "Score": "0", "body": "those are only localhost values, as in `http://localhost:3000` and `http://localhost:3001` I put them in env variables cause I thought this is how you are supposed to do it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-11T16:32:33.627", "Id": "521261", "Score": "1", "body": "No that's fine, you've done the right thing. It just means that I can't test your code for you." } ]
[ { "body": "<p>I think the biggest miss here is that <code>LoginPage</code>, though it is perhaps fine as a test utility class, is clearly not a <code>TestCase</code> and should not inherit from that.</p>\n<p>This loop:</p>\n<pre><code> buttons = self.selenium.find_elements_by_tag_name(&quot;button&quot;)\n for btn in buttons:\n if text in btn.get_attribute(&quot;innerHTML&quot;):\n return btn\n</code></pre>\n<p>should not be needed, and you should be able to write a single selector that accomplishes the same thing. Without access to your DOM I don't know what that's going to be, precisely.</p>\n<p>Your pattern of <code>return self.selenium</code> isn't particularly useful, since <code>MyTest</code> already has a reference to its own <code>self.selenium</code>; so all of those functions can just be <code>None</code>-returns.</p>\n<p>For Python 3 you should no longer be passing parameters into <code>super()</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-11T14:25:05.593", "Id": "263949", "ParentId": "263941", "Score": "2" } } ]
{ "AcceptedAnswerId": "263949", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-11T01:45:19.100", "Id": "263941", "Score": "1", "Tags": [ "python-3.x", "selenium", "integration-testing" ], "Title": "Simple login test, translated from java to python" }
263941
<p>Below is the Rabin Karp implementation. I am not so sure about it, and there is no where that I can check whether this code really works or not. It will most helpful for extra set of eyes if whether this gives correct output or not. The code finds the substring (in code it is, pattern) from the string given (in code it is, text). If the substring is found it will return true, otherwise false.</p> <pre><code>public class RabinKarpSubstring { // Check if text contains pattern. public boolean isSubstring (String pattern, String text) { if (pattern.length() &gt; text.length()) return false; int prime = 31; int MOD = 1000000009; long hashPattern = 0; long[] primePower = new long[text.length()]; long[] hashText = new long[text.length() + 1]; primePower[0] = 1; for (int i = 1; i &lt; text.length(); i++) { primePower[i] = (primePower[i - 1] * prime) % MOD; } for (int i = 0; i &lt; text.length(); i++) { hashText[i + 1] = (hashText[i] + ((text.charAt(i) - 'a' + 1) * primePower[i])) % MOD; } for (int i = 0; i &lt; pattern.length(); i++) { hashPattern = (hashPattern + ((pattern.charAt(i) - 'a' + 1) * primePower[i])) % MOD; } for (int i = 0; i &lt; (text.length() - pattern.length() + 1); i++) { long currHash = (hashText[i + pattern.length()] + MOD - hashText[i]) % MOD; if (currHash == (hashPattern * primePower[i] % MOD)) { return true; } } return false; } public static void main(String[] args) { System.out.println(new RabinKarpSubstring().isSubstring(&quot;aab&quot;, &quot;aaaab&quot;)); } } </code></pre> <p>Please do share if anymore information is to added. Thank you.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-11T14:59:11.577", "Id": "521257", "Score": "1", "body": "Just a suggestion, add additional test to main that both pass and fail have expected values for the pass and fail and test some edge cases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-11T15:09:52.147", "Id": "521258", "Score": "0", "body": "@pacmaninbw Sure, I will do that." } ]
[ { "body": "<h2>An important omission</h2>\n<p>Consider this snippet:</p>\n<blockquote>\n<pre><code>if (currHash == (hashPattern * primePower[i] % MOD)) {\n return true;\n}\n</code></pre>\n</blockquote>\n<p>It returns true when the hashes match. But hashes are not unique, they cannot be, there are fewer of them than there are strings. So there should be a proper string comparison here, to distinguish false positives from true positives.</p>\n<p>False positives are not only a problem for huge strings. As a specific example, using the hash you're using, &quot;zdxudvc&quot; and &quot;gulbina&quot; collide. Finding that was a nice puzzle.</p>\n<p>To put it another way: Rabin-Karp reduces the expected number of string comparisons (relative to the naive substring search), but does not remove the need for them entirely.</p>\n<h2>Inefficient design</h2>\n<p>While you didn't put a <a href=\"/questions/tagged/performance\" class=\"post-tag\" title=\"show questions tagged &#39;performance&#39;\" rel=\"tag\">performance</a> tag, I will comment on this anyway, after all the point of Rabin-Karp is to be fast (otherwise you could use a naive substring search).</p>\n<p>Building a large array of prime powers, as well as a large array of hashes, is unnecessary and inefficient. These can be computed on the fly. That saves not only the large allocations (larger than the input string!) but also, if a match is found, it saves computing these things for the part of the string after the match.</p>\n<p>Using a prime for <code>MOD</code> is common, but not necessary. A sufficient condition is that <code>MOD</code> and <code>prime</code> are relatively prime. Not all such choices are good choices, for example <code>prime</code> has better not be 1, but there are many reasonable choices, some of which have advantages. For example, choosing <code>MOD</code> equal to 2<sup>32</sup> means that the modulo step is implicit and (for any power of two <code>MOD</code>) you can stop using <code>long</code> because premature wrapping is no longer a problem. There are various analyses of whether a prime <code>MOD</code> is good or not. A popular argument is that it causes fewer hash collisions. That may be true, but that's not really the question: the question is whether that's worth it compared to the cost of having non-trivial modulo reductions. I don't think it is, but try it, experiment.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-11T16:43:13.263", "Id": "521263", "Score": "0", "body": "Thank you so much, @harold. This answer really solved many of my doubts and I welcome the performance suggestion and will surely experiment." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-11T16:34:02.250", "Id": "263955", "ParentId": "263948", "Score": "0" } } ]
{ "AcceptedAnswerId": "263955", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-11T13:47:00.637", "Id": "263948", "Score": "0", "Tags": [ "java", "strings" ], "Title": "Rabin karp substring search" }
263948
<p>UPDATES:</p> <p>I'm looking for an answer that can answer the questions listed in the post. Moreover, this answer will not only continue my way of thinking, but also give feedback based on it. It's just like a conversation.</p> <p>For example: As to question 1.1. It's better to create <code>andy_cfg</code> to handle everything about <code>andy.ini</code> only if these considerations are met..., or you're doing good with this architecture so far.</p> <p>Then give insight on each consideration.</p> <hr /> <p>There are two source files <code>andy_web.c</code> and <code>andy_cfg.c</code>.</p> <p><code>andy_web.c</code> manages things related to Web pages in the form of program, called <code>andy_web.cgi</code> and is invoked by <code>lighttpd</code>.</p> <p>In brief, if <code>get=setting</code> is received, <code>andy_web.cgi</code> will take height and weight from andy's config file by calling functions in <code>andy_cfg.c</code>, and show them in pages; if <code>post=setting</code> is received, <code>andy_web.cgi</code> will get height and weight from <code>lighttpd</code> and set them to the config file also by calling functions in <code>andy_cfg.c</code>.</p> <pre><code>/*web_api.h*/ #ifndef WEB_API_H #define WEB_API_H #define MAX_NAME_LEN 128 #define MAX_VALUE_LEN 128 struct web_http_nv { char name[MAX_NAME_LEN]; char value[MAX_VALUE_LEN]; }; #define MAX_NAME_VALUE_LEN 512 typedef struct web_t web_t; struct web_t { struct web_http_nv nameval[MAX_NAME_VALUE_LEN]; /* (name, value) pair from web */ int nv_ct; /* (name, value) pair count */ }; void web_get(web_t* web); /* get (name, value) pair from web */ #endif /*andy_web.c*/ #include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; #include &quot;web_api.h&quot; #include &quot;andy_cfg.h&quot; #define MIN_HEIGHT 150 #define MAX_HEIGHT 250 #define MIN_WEIGHT 50 #define MAX_WEIGHT 150 void printMsg(char *msg); //forward declaration static andy_config_t* andy_config = NULL; static web_t web = {0}; static void andy_web_page_show(void); static int andy_web_page_setting_check_then_save(char Msg[], uint16_t MsgSize); int main(void) { andy_config = andy_config_init(180, 80); if (ANDY_CFG_FAILED == andy_config) { return -1; } web_get(&amp;web); const uint8_t METHOD = web.nv_ct - 1; if (!strcmp(web.nameval[METHOD].name, &quot;get&quot;)) { if (!strcmp(web.nameval[METHOD].value, &quot;setting&quot;)) { andy_web_page_show(); } goto DONE; } char Msg[100] = {0}; if (!strcmp(web.nameval[METHOD].name, &quot;post&quot;)) { if (!strcmp(web.nameval[METHOD].value, &quot;setting&quot;)) { if (andy_web_page_setting_check_then_save(Msg, sizeof(Msg)) == -1) { goto SETTING_CHECK_ERROR; } } andy_web_page_show(); goto DONE; } SETTING_CHECK_ERROR: printMsg(Msg); DONE: andy_config_close(andy_config); return 0; } static void andy_web_page_show(void) { printf(&quot;Content-Type: text/html\n\n&quot;); printf(&quot;&lt;html&gt;\n&quot;); printf(&quot;&lt;head&gt;\n&quot;); printf(&quot;&lt;meta http-equiv=\&quot;Content-Type\&quot; content=\&quot;text/html;\&quot; /&gt;\n&quot;); printf(&quot;&lt;title&gt;andy Setting&lt;/title&gt;\n&quot;); printf(&quot;&lt;/head&gt;\n&quot;); printf(&quot;&lt;body&gt;\n&quot;); printf(&quot;&lt;fieldset&gt;\n&quot;); printf(&quot;&lt;legend&gt;andy Setting&lt;/legend&gt;\n&quot;); printf(&quot;&lt;form name=\&quot;andyPage\&quot; method=\&quot;post\&quot; action=\&quot;/cgi-bin/andy_web.cgi\&quot; &gt;\n&quot;); printf(&quot; &lt;table id=\&quot;table1\&quot; border=\&quot;0\&quot; cellpadding=\&quot;1\&quot; cellspacing=\&quot;1\&quot;&gt;\n&quot;); uint16_t height = 0; if (andy_config_retrieve_height(andy_config, &amp;height) != -1) { printf(&quot; &lt;tr&gt;\n&quot;); printf(&quot; &lt;td height=\&quot;20\&quot; width=\&quot;150\&quot; style=\&quot;padding-left:10px\&quot;&gt;andy height&lt;/td&gt;\n&quot;); printf(&quot; &lt;td height=\&quot;20\&quot; &gt;&lt;input type=\&quot;text\&quot; name=\&quot;height\&quot; style=\&quot;width: 100;\&quot; value=\&quot;%d\&quot; /&gt;(%d~%d)&lt;/td&gt;\n&quot;, height, MIN_HEIGHT, MAX_HEIGHT); printf(&quot; &lt;/tr&gt;\n&quot;); } uint16_t weight = 0; if (andy_config_retrieve_weight(andy_config, &amp;weight) != -1) { printf(&quot; &lt;tr&gt;\n&quot;); printf(&quot; &lt;td height=\&quot;20\&quot; width=\&quot;150\&quot; style=\&quot;padding-left:10px\&quot;&gt;andy weight&lt;/td&gt;\n&quot;); printf(&quot; &lt;td height=\&quot;20\&quot; &gt;&lt;input type=\&quot;text\&quot; name=\&quot;weight\&quot; style=\&quot;width: 100;\&quot; value=\&quot;%d\&quot; /&gt;(%d~%d)&lt;/td&gt;\n&quot;, weight, MIN_WEIGHT, MAX_WEIGHT); printf(&quot; &lt;/tr&gt;\n&quot;); } printf(&quot; &lt;/table&gt;\n&quot;); printf(&quot; &lt;p align=\&quot;center\&quot;&gt;\n&quot;); printf(&quot; &lt;input type=\&quot;submit\&quot; value=\&quot; Update \&quot; /&gt;\n&quot;); printf(&quot; &lt;input type=\&quot;hidden\&quot; name=\&quot;post\&quot; value=\&quot;setting\&quot; /&gt;\n&quot;); printf(&quot; &lt;/p&gt;\n&quot;); printf(&quot;&lt;/form&gt;\n&quot;); printf(&quot;&lt;/body&gt;\n&quot;); printf(&quot;&lt;/html&gt;\n&quot;); } static int andy_web_page_setting_check_then_save(char Msg[], uint16_t MsgSize) { int count = 0; for (; count &lt; web.nv_ct-1; count++) { if (!strcmp(web.nameval[count].name, &quot;height&quot;)) { uint16_t height = atoi(web.nameval[count].value); if ((height &lt; MIN_HEIGHT) || (height &gt;= MAX_HEIGHT)) { snprintf(Msg, MsgSize, &quot;height &lt;%d&gt; should be between %d and %d&quot;, height, MIN_HEIGHT, MAX_HEIGHT); return -1; } andy_config_set_height(andy_config, height); } else if (!strcmp(web.nameval[count].name, &quot;weight&quot;)) { uint16_t weight = atoi(web.nameval[count].value); if ((weight &lt; MIN_WEIGHT) || (weight &gt;= MAX_WEIGHT)) { snprintf(Msg, MsgSize, &quot;weight &lt;%d&gt; should be between %d and %d&quot;, weight, MIN_WEIGHT, MAX_WEIGHT); return -1; } andy_config_set_weight(andy_config, weight); } else { } } andy_config_save(andy_config); return 0; } </code></pre> <p><code>andy_cfg.c</code> manages things related to the config file in the form of functions that are called by <code>andy_web.c</code>.</p> <p>Function names beginning with <code>iniparser</code>, such as <code>iniparser_load</code>, are offered by <a href="https://github.com/ndevilla/iniparser" rel="nofollow noreferrer">iniparser</a> which basically parses ini files and offer abilities to read/write text files in C level.</p> <pre><code>/*andy_cfg.h*/ #ifndef ANDY_CFG_H #define ANDY_CFG_H #include &lt;stdint.h&gt; typedef struct andy_config_t andy_config_t; #define ANDY_CFG_FAILED (andy_config_t*)NULL andy_config_t* andy_config_init(uint16_t height, uint16_t weight); void andy_config_close(andy_config_t* me); void andy_config_save(andy_config_t* me); void andy_config_set_height(andy_config_t* me, uint16_t height); void andy_config_set_weight(andy_config_t* me, uint16_t weight); int andy_config_retrieve_height(andy_config_t* me, uint16_t* height); int andy_config_retrieve_weight(andy_config_t* me, uint16_t* weight); #endif /*andy_cfg.c*/ #include &lt;stdbool.h&gt; #include &quot;iniparser.h&quot; #include &quot;andy_cfg.h&quot; #define ANDY_STARTUP_DIR &quot;/mnt/jffs2/cfg/&quot; #define ANDY_RUNNING_DIR &quot;/var/&quot; #define ANDY_CFG_FILE &quot;andy.ini&quot; bool file_is_existing(const char* file_path); //forward declaration andy_config_t* andy_config_init(uint16_t height, uint16_t weight) { if (!file_is_existing(ANDY_STARTUP_DIR&quot;&quot;ANDY_CFG_FILE)) { FILE* andy_startup_file = fopen(ANDY_STARTUP_DIR&quot;&quot;ANDY_CFG_FILE, &quot;w&quot;); if (NULL == andy_startup_file) { return ANDY_CFG_FAILED; } fprintf(andy_startup_file, &quot;\n&quot; &quot;[Info]\n&quot; &quot;\n&quot; &quot;height = %d ; 150 ~ 250\n&quot; &quot;weight = %d ; 50 ~ 150\n&quot; &quot;\n&quot;, height, weight); fclose(andy_startup_file); } dictionary* andy_running_config = iniparser_load(ANDY_STARTUP_DIR&quot;&quot;ANDY_CFG_FILE); if (NULL == andy_running_config) { return ANDY_CFG_FAILED; } return (andy_config_t*)andy_running_config; } void andy_config_close(andy_config_t* me) { if (NULL != me) { andy_config_save(me); iniparser_freedict((dictionary*)me); } } void andy_config_save(andy_config_t* me) { FILE* andy_startup_file = fopen(ANDY_STARTUP_DIR&quot;&quot;ANDY_CFG_FILE, &quot;w&quot;); iniparser_dump_ini((dictionary*)me, andy_startup_file); fclose(andy_startup_file); } void andy_config_set_height(andy_config_t* me, uint16_t height) { char str[10] = {0}; snprintf(str, sizeof(str), &quot;%d&quot;, height); iniparser_set((dictionary*)me, &quot;Info:height&quot;, str); } void andy_config_set_weight(andy_config_t* me, uint16_t weight) { char str[10] = {0}; snprintf(str, sizeof(str), &quot;%d&quot;, weight); iniparser_set((dictionary*)me, &quot;Info:weight&quot;, str); } int andy_config_retrieve_height(andy_config_t* me, uint16_t* height) { int ret = iniparser_getint((dictionary*)me, &quot;Info:height&quot;, -1); if (ret == -1) { return -1; } *height = (uint16_t)ret; return 0; } int andy_config_retrieve_weight(andy_config_t* me, uint16_t* weight) { int ret = iniparser_getint((dictionary*)me, &quot;Info:weight&quot;, -1); if (ret == -1) { return -1; } *weight = (uint16_t)ret; return 0; } </code></pre> <p>Now that I've covered the code, I want to point out some of my perspective about the code.</p> <ol> <li><code>andy_web.cgi</code> should only deal with and aware of nothing else but Web matters.</li> </ol> <p>1.1. Would it be a good choice for <code>andy_web.cgi</code> that creating a program <code>andy_cfg</code> that deals with everything about <code>andy.ini</code> and to retrieve/save data from/to it through IPC? If so, under what considerations you will take this approach?</p> <p>Or, one can create a program <code>cfg</code> that handles config files not only for andy but everyone. However, this way will not go well because <code>cfg</code> will include so many header files such as <code>andy_cfg.h</code>, <code>amy_cfg.h</code>, <code>benson_cfg.h</code>, and end up with maintenance issues.</p> <p>I've seen code somewhere that seems to be designed to solve this maintenance issues. Basically there's one callback function, and all of a sudden it's like the relationship is upside down between caller and callee. The code might look like</p> <pre><code>/*cfg.c*/ typedef void(*register_function_t)(void); void cfg_register_set(char* function_name, register_function_t callback_function) { /*Object which wants to use config feature will call this function to register this feature*/ } void cfg_init(void) { /*After registration, all cfg files will be handled in some way.*/ } </code></pre> <p>1.2 How the above code works? Is there other common practices to deal with this kind of maintenance problem? Please tell me in detail.</p> <ol start="2"> <li><code>andy_cfg.c</code> seems to violate DRY (don't repeat yourself).</li> </ol> <p>This way will end up with so many source files such like <code>andy_cfg.c</code>, <code>amy_cfg.c</code>, <code>benson_cfg.c</code>, etc. All of these codes have everything in common except for the function names that provide literally the same functionality. For example, <code>amy_cfg.h</code> will be like</p> <pre><code>/*amy_cfg.h*/ #ifndef AMY_CFG_H #define AMY_CFG_H #include &lt;stdint.h&gt; typedef struct amy_config_t amy_config_t; #define AMY_CFG_FAILED (amy_config_t*)NULL amy_config_t* amy_config_init(uint16_t height, uint16_t weight); void amy_config_close(amy_config_t* me); void amy_config_save(amy_config_t* me); void amy_config_set_height(amy_config_t* me, uint16_t height); void amy_config_set_weight(amy_config_t* me, uint16_t weight); int amy_config_retrieve_height(amy_config_t* me, uint16_t* height); int amy_config_retrieve_weight(amy_config_t* me, uint16_t* weight); #endif /*amy_cfg.c*/ #include &lt;stdbool.h&gt; #include &quot;iniparser.h&quot; #include &quot;amy_cfg.h&quot; #define AMY_STARTUP_DIR &quot;/mnt/jffs2/cfg/&quot; #define AMY_RUNNING_DIR &quot;/var/&quot; #define AMY_CFG_FILE &quot;amy.ini&quot; bool file_is_existing(const char* file_path); //forward declaration amy_config_t* amy_config_init(uint16_t height, uint16_t weight) { if (!file_is_existing(AMY_STARTUP_DIR&quot;&quot;AMY_CFG_FILE)) { FILE* amy_startup_file = fopen(AMY_STARTUP_DIR&quot;&quot;AMY_CFG_FILE, &quot;w&quot;); if (NULL == amy_startup_file) { return AMY_CFG_FAILED; } fprintf(amy_startup_file, &quot;\n&quot; &quot;[Info]\n&quot; &quot;\n&quot; &quot;height = %d ; 150 ~ 250\n&quot; &quot;weight = %d ; 50 ~ 150\n&quot; &quot;\n&quot;, height, weight); fclose(amy_startup_file); } dictionary* amy_running_config = iniparser_load(AMY_STARTUP_DIR&quot;&quot;AMY_CFG_FILE); if (NULL == amy_running_config) { return AMY_CFG_FAILED; } return (amy_config_t*)amy_running_config; } void amy_config_close(amy_config_t* me) { if (NULL != me) { amy_config_save(me); iniparser_freedict((dictionary*)me); } } void amy_config_save(amy_config_t* me) { FILE* amy_startup_file = fopen(AMY_STARTUP_DIR&quot;&quot;AMY_CFG_FILE, &quot;w&quot;); iniparser_dump_ini((dictionary*)me, amy_startup_file); fclose(amy_startup_file); } void amy_config_set_height(amy_config_t* me, uint16_t height) { char str[10] = {0}; snprintf(str, sizeof(str), &quot;%d&quot;, height); iniparser_set((dictionary*)me, &quot;Info:height&quot;, str); } void amy_config_set_weight(amy_config_t* me, uint16_t weight) { char str[10] = {0}; snprintf(str, sizeof(str), &quot;%d&quot;, weight); iniparser_set((dictionary*)me, &quot;Info:weight&quot;, str); } int amy_config_retrieve_height(amy_config_t* me, uint16_t* height) { int ret = iniparser_getint((dictionary*)me, &quot;Info:height&quot;, -1); if (ret == -1) { return -1; } *height = (uint16_t)ret; return 0; } int amy_config_retrieve_weight(amy_config_t* me, uint16_t* weight) { int ret = iniparser_getint((dictionary*)me, &quot;Info:weight&quot;, -1); if (ret == -1) { return -1; } *weight = (uint16_t)ret; return 0; } </code></pre> <p>My instinct told me that I should write type-general functions for <code>iniparser</code>, so that I can reuse it. Unfortunately, easier said than done.</p> <p>2.1 Is writing type-general functions for <code>iniparser</code>, in order to solve DRY problem, a good choice in C? Is there other common practices?</p> <p>There once was another way that came into my mind, but I was not sure that it would be practicable.</p> <p>What if I wrapped <code>iniparser</code> as a program and let other programmers to specify arguments on command line? In other words, one can create config file for everyone by typing <code>iniparser someone.ini height=180 weight=80</code> on the command line, without having to create <code>someone_cfg.c</code> repeatedly.</p> <p>Also, for the command line, adding new attribute is much easier than a function approach. For example, what if age attribute came around? For command-line approach, one just type <code>iniparser someone.ini height=180 weight=80 age=32</code>; for function approach, one has to add <code>void someone_cfg_set_age(someone_cfg_t* me, uint8_t age);</code>, to re-compile source file, and to re-link program.</p> <p>All <code>iniparser</code> does is just to put arguments on the command line in a file. Simple and straightforward.</p> <p>However, this approach not only shifts the learning curve of <code>iniparser</code> from the function level to the program level, but it is only applicable to programmers who know scripts. Not to mention that the program itself may have bugs!</p> <p>2.2 Is this really a good approach? Is there other common practices?</p> <ol start="3"> <li><code>andy_web.c</code> should not know details about config file.</li> </ol> <p>What if config files were handled in binary files instead of text files? The code would have to re-compile and re-link. Fortunately, this problem can be solved by creating a program <code>andy_cfg</code> that is described in 1.1.</p> <p>I spent several hours for this post. Please share your comment in any way! Thank you.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T00:19:37.580", "Id": "521270", "Score": "2", "body": "How would `andy_cfg.c, amy_cfg.c, benson_cfg.c,` differ from each other? Sharing `andy_cfg.h` (specifically a definition of `andy_config_t`), and a hypothetical `amy_cfg.h` will seriously help to address your concerns." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T03:39:15.273", "Id": "521273", "Score": "0", "body": "@vnp added! Thank you for your comments." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T07:51:27.203", "Id": "521424", "Score": "1", "body": "Where `MAX_NAME_LEN, MAX_VALUE_LEN` defined? Try compiling what is posted. You have a lot here with many questions (11+). Perhaps review a subset of code or focus the review?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T08:29:49.047", "Id": "521430", "Score": "0", "body": "@chux-ReinstateMonica I apologize for my impatience. Now the source code is able to compile except for functions `file_is_existing` to check whether file is existing or not , `web_get` to get (name, value) pair from web, and `printMsg` to print message on `stdout`." } ]
[ { "body": "<h1 id=\"make-your-code-more-generic-x3hb\">Make your code more generic</h1>\n<p>What if it's not only Andy, Amy and Benson, but you want to store the height and weight of a thousand people? Maybe some share the same first name? You can imagine that this would result in a terrible mess. The first thing to do is to write your code in a generic way, so it can handle any number of persons without having to duplicate code in any way. Indeed, follow the DRY principle as much as possible.</p>\n<p>Anything that currently has &quot;andy&quot; in its name should be replaced with something that is generic. That includes files like <code>andy_web.c</code>, and structures like <code>andy_config_t</code>. That means you have to find some way to pass the name &quot;Andy&quot; as a variable. For example:</p>\n<pre><code>struct person_config_t {\n const char *name;\n uint16_t height;\n uint16_t weight;\n};\n</code></pre>\n<p>You also have to pass this in the HTML form. For example:</p>\n<pre><code>static void web_page_show(const char *name)\n{\n printf(&quot;Content-Type: text/html\\n\\n&quot;);\n ...\n printf(&quot; &lt;input type=\\&quot;hidden\\&quot; name=\\&quot;name\\&quot; value=\\&quot;%s\\&quot;/&gt;\\n&quot;,\n html_quote(name));\n ...\n}\n</code></pre>\n<p>This allows you to read back the name of the person in <code>main()</code>, and use that to open the right configuration file. Please make sure you sanitize the name before using it; someone could set the name field to &quot;../../../etc/passwd&quot; for example.</p>\n<h1 id=\"use-a-proper-database-9c1u\">Use a proper database</h1>\n<p>INI files are great to store configuration, but that is about it. If you want to store and manipulate data for multiple people, you should start using a proper database. This might sound scary, but there are many simple, light-weight databases that you can use. The most well-known one is <a href=\"https://www.sqlite.org/index.html\" rel=\"nofollow noreferrer\">SQLite</a>, and this sounds like a good fit for your project. With SQLite, there is no need to run a database server; everything is just stored in a single file, so in that respect it is not much different from an INI file.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T02:49:18.960", "Id": "521827", "Score": "0", "body": "Speaking of genericity, could you list the differences between function approach that you provided in your answer and program approach, and give reasons when a person should use which one? E.g. In ___ situation you should consider using function approach rather than program approach, because ___. I personally hope answer will answer the questions listed in post." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T11:00:28.240", "Id": "264113", "ParentId": "263953", "Score": "3" } }, { "body": "<p>Here are a number of things that may help you improve your program.</p>\n<h2>Fix the bug</h2>\n<p>If the ini file does not exist, the <code>andy_config_init()</code> function will write a tag <code>&quot;wieght&quot;</code> to the file and because of the spelling error, the weight field will never be displayed. Computers are not very tolerant of spelling errors; you shouldn't be either, even in comments which have a number of errors such as &quot;declartion&quot; instead of &quot;declaration&quot; and in function names that have &quot;retrive&quot; instead of &quot;retrieve&quot;. Fixing the first error makes your program run properly; fixing the other spelling errors will make it easier for others to read and understand your code.</p>\n<h2>Use a database</h2>\n<p>The other review has already addressed this, but using a database such as <a href=\"https://www.sqlite.org/index.html\" rel=\"nofollow noreferrer\">SQLite</a> is a far better and more durable choice than the current implementation. Another possibility might be <a href=\"https://redis.io/\" rel=\"nofollow noreferrer\">redis</a> and hash sets.</p>\n<h2>Don't hardcode file names and directories</h2>\n<p>Instead of putting runtime data in an <code>.ini</code> file, use an <code>.ini</code> file for configuration such as the startup directory name and the name of the database.</p>\n<h2>Use <code>const</code> where practical</h2>\n<p>The <code>MIN_WEIGHT</code> and related constants don't have a type, but need to be able to fit into a <code>uint16_t</code> according to the logic of the code. Instead of writing them as macros, then, I'd suggest using <code>const</code>:</p>\n<pre><code>const uint16_t min_weight = 50;\n</code></pre>\n<p>Now it has a type and if the constant doesn't fit into a <code>uint16_t</code>, the compiler should warn you at compile time rather than manifesting some mysterious bug at runtime.</p>\n<h2>Hold the spaghetti</h2>\n<p>Code with convoluted control flow is often derisively called &quot;spaghetti code.&quot; One sign of such code is the use of <code>goto</code>. The code currently has this rather tortured control flow:</p>\n<pre><code> if (!strcmp(web.nameval[METHOD].name, &quot;get&quot;))\n {\n if (!strcmp(web.nameval[METHOD].value, &quot;setting&quot;))\n {\n andy_web_page_show();\n }\n \n goto DONE;\n }\n \n char Msg[100] = {0};\n if (!strcmp(web.nameval[METHOD].name, &quot;post&quot;))\n {\n if (!strcmp(web.nameval[METHOD].value, &quot;setting&quot;))\n {\n if (andy_web_page_setting_check_then_save(Msg, sizeof(Msg)) == -1)\n {\n goto SETTING_CHECK_ERROR;\n }\n }\n \n andy_web_page_show();\n \n goto DONE;\n }\n \nSETTING_CHECK_ERROR:\n \n printMsg(Msg);\n\nDONE:\n\n andy_config_close(andy_config);\n return 0;\n</code></pre>\n<p>There are a lot of problems with this, but the main one is that it's hard to follow. What should happen if &quot;name&quot; is neither &quot;post&quot; nor &quot;get&quot;? What actually happens is that <code>printMsg()</code> gets called with an empty message, but that doesn't really seem right. Also if &quot;name&quot; is &quot;get&quot;, do we really need to check if it's also &quot;post&quot;? If it matches &quot;get&quot; but not &quot;settings&quot; we don't call <code>andy_web_page_show()</code> but if we match &quot;post&quot; but not &quot;settings&quot; it does. This seems very inconsistent and random. Here's how I would rewrite it:</p>\n<p>First, notice that the nested <code>if</code> statements are really just checking for a particular <code>name</code> and <code>value</code> Let's isolate that to a function called <code>matches_name_value()</code></p>\n<pre><code>bool matches_name_value(const struct web_http_nv *nv, const char* name, const char* value) {\n return strcmp(nv-&gt;name, name) == 0 &amp;&amp; strcmp(nv-&gt;value, value) == 0;\n}\n</code></pre>\n<p>Now we can use this and greatly simplify:</p>\n<pre><code>char Msg[100] = {0};\nif (matches_name_value(&amp;web.nameval[METHOD], &quot;get&quot;, &quot;setting&quot;)) {\n andy_web_page_show();\n} else if (matches_name_value(&amp;web.nameval[METHOD], &quot;post&quot;, &quot;setting&quot;)) {\n if (andy_web_page_setting_check_then_save(Msg, sizeof(Msg)) == -1) {\n printMsg(Msg);\n } else {\n andy_web_page_show();\n }\n}\nandy_config_close(andy_config);\n</code></pre>\n<h2>Write better HTML</h2>\n<p>In the output, I'd strongly suggest adding a character encoding to be compliant with modern standards. Also, the code emits a <code>&lt;fieldset&gt;</code> and <code>&lt;legend&gt;</code> outside the <code>&lt;form&gt;</code> where they should instead be inside.</p>\n<h2>Consider separating CSS</h2>\n<p>Right now a lot of the bulk of the code output is in formatting which would probably be better suited to relegate to a separate css file. That makes the code cleaner and also makes it possible to customize the look of the output without modifying the CGI code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-24T13:59:51.947", "Id": "266355", "ParentId": "263953", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-11T15:59:58.703", "Id": "263953", "Score": "4", "Tags": [ "c", "generics", "dependency-injection", "configuration", "cgi" ], "Title": "CGI script that reads or writes its height and weight configuration" }
263953
<p>I'm building a simple webpage that allow users to find the intersection of different category lists on a wiki (<a href="https://imslp.org/wiki/Main_Page" rel="nofollow noreferrer">imslp.org</a>) since the site itself does not offer this functionality. I have a simple HTML form that asks users to paste in two URLs and a PHP script that retrieves information from the two wiki pages and produces a set of results that match both categories.</p> <p>The code works, but I want to make sure I'm not opening myself or users up to any security vulnerabilities before sharing. Does the following seem secure?</p> <p>Here's the HTML form:</p> <pre><code>&lt;form method=&quot;GET&quot; id=&quot;webform&quot; name=&quot;webform&quot; action=&quot;search.php&quot;&gt; &lt;label for=&quot;people_url&quot;&gt;Other people URL:&lt;/label&gt; &lt;input type=&quot;text&quot; id=&quot;people_url&quot; name=&quot;people_url&quot; size=&quot;100&quot;&gt; &lt;label for=&quot;pieces_url&quot;&gt;Pieces URL:&lt;/label&gt; &lt;input type=&quot;text&quot; id=&quot;pieces_url&quot; name=&quot;pieces_url&quot; size=&quot;100&quot;&gt; &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt; &lt;/form&gt; </code></pre> <p>And here's the PHP script:</p> <pre><code>&lt;?php function validate_URL($url) { $url_converted = htmlspecialchars($url, ENT_QUOTES, &quot;UTF-8&quot;); if (!filter_var($url_converted, FILTER_VALIDATE_URL)) { echo 'This is not a valid URL: ' . $url_converted; return false; } else { return true; } } function get_IMSLP_category_list($url) { $results_string = file_get_contents($url); $start = strpos($results_string, ':{&quot;') + 1; $results_string = substr($results_string, $start); $end = strpos($results_string, '}') + 1; $results_string = substr($results_string, 0, $end); $results_dict = json_decode($results_string); $results_list = []; foreach ($results_dict as $letter =&gt; $letter_list) { foreach ($letter_list as $result) { array_push($results_list, explode('|', $result)[0]); } } return $results_list; } function parse_IMSLP_url($url) { parse_str(parse_url($url, PHP_URL_QUERY), $parsed_query); if (empty($parsed_query)) { $main_category = substr(parse_url($url, PHP_URL_PATH), 15); } else { $main_category = substr($parsed_query['title'], 9); } $query_display_string = $main_category; $restrictions = []; $exclusions = []; if (array_key_exists('intersect', $parsed_query)) { $intersection_categories = explode('**', $parsed_query['intersect']); foreach ($intersection_categories as $category) { if ($category != '') { if (substr($category, 0, 1) != '-') { array_push($restrictions, $category); } else { array_push($exclusions, $category); } } } } return [$main_category, $restrictions, $exclusions, $query_display_string]; } function find_intersection($input) { $main_category = $input[0]; $restrictions = $input[1]; $exclusions = $input[2]; $built_url = 'https://imslp.org/index.php?title=Category:' . $main_category; if ((!empty($restrictions)) or (!empty($exclusions))) { $combined_intersections = array_merge($restrictions, $exclusions); $built_url = $built_url . '&amp;intersect=' . implode('**', $combined_intersections); } $list = get_IMSLP_category_list($built_url); return $list; } $process_cross_referencing = True; $people_url = $_GET[&quot;people_url&quot;]; if (!validate_url($people_url)) { $process_cross_referencing = False; } $pieces_url = $_GET[&quot;pieces_url&quot;]; if (!validate_url($pieces_url)) { $process_cross_referencing = False; } if ($process_cross_referencing) { $parsed_people = parse_IMSLP_url($people_url); $people_list = find_intersection($parsed_people); $parsed_pieces = parse_IMSLP_url($pieces_url); $pieces_list = find_intersection($parsed_pieces); $results_links = []; foreach ($pieces_list as $piece) { $composer_start = strrpos($piece, '(') + 1; $composer_length = strrpos($piece, ')') - $composer_start; $composer = substr($piece, $composer_start, $composer_length); if (in_array($composer, $people_list)) { array_push($results_links, $piece); } } var_dump($results_links); } </code></pre> <p>User submits URLs with form. A typical URL would look something like this:</p> <p><code>https://imslp.org/index.php?title=Category:Female_people&amp;intersect=Composers**-German_people</code></p> <p>The PHP script retrieves URL strings using <code>$_GET</code> and validates them with <code>validate_URL()</code>. If the URL comes back valid, the script parses the URLs using <code>parse_IMSLP_url</code>. It then rebuilds the URLs to match a template and retrieves the results from the wiki using <code>find_intersection()</code> and <code>get_IMSLP_category_list()</code>. Finally, the results from both searches are cross-referenced.</p> <p>Does it look like I might be opening myself up to any security loopholes here? (I'm pretty new to PHP, so any other suggestions would be equally welcome.)</p>
[]
[ { "body": "<ul>\n<li><p>In <code>validate_URL()</code> I recommend that you only call <code>htmlspecialchars()</code> when echoing. <a href=\"https://stackoverflow.com/q/4882307/2943403\">https://stackoverflow.com/q/4882307/2943403</a> That said, I don't recommend that you echo anything from inside your function -- use the boolean return values to dictate <em>if</em> a validation error should be displayed.</p>\n<pre><code>function validate_URL(string $url): bool\n{\n return (bool) filter_var($url, FILTER_VALIDATE_URL);\n}\n</code></pre>\n<p>The function becomes so small, that it you are effectively replacing a native function so I would recommend not declaring the function at all.</p>\n</li>\n<li><p>In <code>get_IMSLP_category_list()</code>, I am seeing some classic misuse of <code>strpos()</code>. If you do not explicitly check for a boolean <code>false</code> return value, then you risk getting incorrect results where <code>0</code> and <code>false</code> will collide. More importantly, why are you conducting string surgery like this at all? I don't know what your input data looks like, but if it is some sort of formatted string, there is a fair chances that regex will make your code far more readable/comprehensible. If the incoming data is a json string, then you should decode it straight away and access what you need, directly, without regex. I can only advise on improvements to this function after knowing exactly what the data looks like and how it might vary.</p>\n</li>\n<li><p>In <code>parse_IMSLP_url()</code>, <code>empty()</code> is an inappropriate call when you are guaranteed that the variable is going to be declared. You probably only need to make a functionless falsey check <code>if (!$variable) {</code>. Don't declare single-use variables. Don't declare redundant or unnecessary variables. Don't repeat yourself. Only use <code>array_push()</code> when you want to add multiple elements to an array at one time. Don't return redundant data from your function. (sorry so negative)</p>\n<pre><code>function parse_IMSLP_url(string $url): array\n{\n parse_str(parse_url($url, PHP_URL_QUERY), $parsed_query);\n\n $main_category = $parsed_query\n ? substr($parsed_query['title'], 9)\n : substr(parse_url($url, PHP_URL_PATH), 15);\n\n $restrictions = [];\n $exclusions = [];\n\n if (array_key_exists('intersect', $parsed_query)) {\n foreach (explode('**', $parsed_query['intersect']) as $category) {\n if ($category != '') {\n if ($category[0] !== '-') {\n $restrictions[] = $category;\n } else {\n $exclusions[] = $category;\n }\n }\n }\n }\n return [$main_category, $restrictions, $exclusions];\n}\n</code></pre>\n</li>\n<li><p>In <code>find_intersection()</code>, you know that there will be 3 incoming elements, so instead, just pass the three elements as arguments and spare yourself the declarations in the function body. <code>$restrictions</code> and <code>$exclusions</code> are guaranteed so empty is inappropriate.</p>\n<pre><code>function find_intersection(string $main_category, array $restrictions, array $exclusions): array\n{\n return get_IMSLP_category_list(\n sprintf(\n 'https://imslp.org/index.php?title=Category:%s%s',\n $main_category,\n $restrictions || $exclusions\n ? '&amp;intersect=' . implode('**', array_merge($restrictions, $exclusions))\n : ''\n )\n );\n}\n</code></pre>\n</li>\n<li><p>As for the rest of the code... Use fewer variables as mentioned previously. Avoid string surgery via multiple cuts. I'm showing a regex pattern to extract the composer string, but if I knew the format of these strings, I might be able to provide a better pattern.</p>\n<pre><code>foreach (['people_url', 'pieces_url'] as $url) {\n if (!filter_var($url, FILTER_VALIDATE_URL)) {\n exit('Invalid URL: ' . htmlspecialchars($_GET[$url], ENT_QUOTES, &quot;UTF-8&quot;));\n }\n}\n\n$people_list = find_intersection(...parse_IMSLP_url($_GET['people_url']));\n$pieces_list = find_intersection(...parse_IMSLP_url($_GET['pieces_url']));\n\n$links = [];\nforeach ($pieces_list as $piece) {\n if (preg_match('~.*\\(\\K[^()]+(?=\\))~', $piece, $composer) &amp;&amp; in_array($composer[0], $people_list)) {\n $links[] = $piece;\n }\n}\nvar_export($links);\n</code></pre>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T14:44:14.670", "Id": "264016", "ParentId": "263954", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-11T16:28:36.247", "Id": "263954", "Score": "0", "Tags": [ "php", "security" ], "Title": "Simple web page to enhance browsing of IMSLP music collections" }
263954
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/263767/231235">A recursive_transform template function for the binary operation cases in C++</a>. Thanks for <a href="https://codereview.stackexchange.com/a/263849/231235">G. Sliepen's answer</a>. Based on the mentioned suggestion, I am attempting to improve the extendibility of <code>recursive_transform</code> template function for the multiple parameters cases.</p> <ul> <li><p><strong><code>recursive_invoke_result</code> template struct and <code>recursive_variadic_invoke_result</code> template struct</strong></p> <p><code>recursive_invoke_result</code> struct is updated with integrating <code>unwrap_level</code> parameter instead of using <code>std::invocable</code> in order to make the logic of recursion be consistent. The <code>recursive_invoke_result</code> struct is focus on the result type of invoking functions with unary input and the <code>recursive_variadic_invoke_result</code> struct deals with the result type of invoking functions with multiple inputs.</p> </li> <li><p><strong><code>recursive_transform</code> template function for the multiple parameters cases</strong></p> <p>The main part of this post. The multiple parameterized lambda for recursive transform is supported.</p> <p>For example, the following code can be compiled.</p> <pre><code>std::vector&lt;std::string&gt; test_vector1{ &quot;1&quot;, &quot;4&quot;, &quot;7&quot; }; std::vector&lt;std::string&gt; test_vector2{ &quot;2&quot;, &quot;5&quot;, &quot;8&quot; }; std::vector&lt;std::string&gt; test_vector3{ &quot;3&quot;, &quot;6&quot;, &quot;9&quot; }; std::vector&lt;std::string&gt; test_vector4{ &quot;a&quot;, &quot;b&quot;, &quot;c&quot; }; auto output = recursive_transform&lt;1&gt;( [](auto element1, auto element2, auto element3, auto element4) { return element1 + element2 + element3 + element4; }, test_vector1, test_vector2, test_vector3, test_vector4); for (auto&amp;&amp; element : output) { std::cout &lt;&lt; element &lt;&lt; std::endl; } </code></pre> <p>The <code>output</code> in the above code is a <code>std::vector&lt;std::string&gt;</code>. The console output:</p> <pre><code>123a 456b 789c </code></pre> </li> </ul> <p><strong>The experimental implementation</strong></p> <ul> <li><p><code>recursive_invoke_result</code> template struct implementation: <code>recursive_invoke_result</code> struct here integrating <code>unwrap_level</code> parameter. <code>struct recursive_invoke_result&lt;0, F, T&gt;</code> is a kind of <a href="https://en.wikipedia.org/wiki/Partial_template_specialization" rel="nofollow noreferrer">partial template specialization</a> which plays the role of recursion termination condition. Whether <code>typename T</code> is a range or not, the <code>type</code> just comes from <code>std::invoke_result_t&lt;F, T&gt;</code> if <code>unwrap_level</code> is 0.</p> <pre><code>// recursive_invoke_result_t implementation template&lt;std::size_t, typename, typename&gt; struct recursive_invoke_result { }; template&lt;typename T, typename F&gt; struct recursive_invoke_result&lt;0, F, T&gt; { using type = std::invoke_result_t&lt;F, T&gt;; }; template&lt;std::size_t unwrap_level, typename F, template&lt;typename...&gt; typename Container, typename... Ts&gt; requires (std::ranges::input_range&lt;Container&lt;Ts...&gt;&gt; &amp;&amp; requires { typename recursive_invoke_result&lt;unwrap_level - 1, F, std::ranges::range_value_t&lt;Container&lt;Ts...&gt;&gt;&gt;::type; }) struct recursive_invoke_result&lt;unwrap_level, F, Container&lt;Ts...&gt;&gt; { using type = Container&lt;typename recursive_invoke_result&lt;unwrap_level - 1, F, std::ranges::range_value_t&lt;Container&lt;Ts...&gt;&gt;&gt;::type&gt;; }; template&lt;std::size_t unwrap_level, typename F, typename T&gt; using recursive_invoke_result_t = typename recursive_invoke_result&lt;unwrap_level, F, T&gt;::type; </code></pre> </li> <li><p><code>recursive_variadic_invoke_result</code> template struct implementation: <code>recursive_variadic_invoke_result</code> struct deals with the result type of invoking functions with multiple inputs.</p> <pre><code>// recursive_variadic_invoke_result_t implementation template&lt;std::size_t, typename, typename, typename...&gt; struct recursive_variadic_invoke_result { }; template&lt;typename F, class...Ts1, template&lt;class...&gt;class Container1, typename... Ts&gt; struct recursive_variadic_invoke_result&lt;0, F, Container1&lt;Ts1...&gt;, Ts...&gt; { using type = std::invoke_result_t&lt;F, Container1&lt;Ts1...&gt;, Ts...&gt;; }; template&lt;typename F, class...Ts1, template&lt;class...&gt;class Container1, typename... Ts&gt; struct recursive_variadic_invoke_result&lt;1, F, Container1&lt;Ts1...&gt;, Ts...&gt; { using type = Container1&lt;std::invoke_result_t&lt;F, std::ranges::range_value_t&lt;Container1&lt;Ts1...&gt;&gt;, std::ranges::range_value_t&lt;Ts&gt;...&gt;&gt;; }; template&lt;std::size_t unwrap_level, typename F, class...Ts1, template&lt;class...&gt;class Container1, typename... Ts&gt; requires ( std::ranges::input_range&lt;Container1&lt;Ts1...&gt;&gt; &amp;&amp; requires { typename recursive_variadic_invoke_result&lt; unwrap_level - 1, F, std::ranges::range_value_t&lt;Container1&lt;Ts1...&gt;&gt;, std::ranges::range_value_t&lt;Ts&gt;...&gt;::type; }) // The rest arguments are ranges struct recursive_variadic_invoke_result&lt;unwrap_level, F, Container1&lt;Ts1...&gt;, Ts...&gt; { using type = Container1&lt; typename recursive_variadic_invoke_result&lt; unwrap_level - 1, F, std::ranges::range_value_t&lt;Container1&lt;Ts1...&gt;&gt;, std::ranges::range_value_t&lt;Ts&gt;... &gt;::type&gt;; }; template&lt;std::size_t unwrap_level, typename F, typename T1, typename... Ts&gt; using recursive_variadic_invoke_result_t = typename recursive_variadic_invoke_result&lt;unwrap_level, F, T1, Ts...&gt;::type; </code></pre> </li> <li><p><code>transform</code> function for any <span class="math-container">\$n\$</span>-ary function: from <a href="https://codereview.stackexchange.com/a/263849/231235">G. Sliepen's answer</a></p> <pre><code>template&lt;typename OutputIt, typename NAryOperation, typename InputIt, typename... InputIts&gt; OutputIt transform(OutputIt d_first, NAryOperation op, InputIt first, InputIt last, InputIts... rest) { while (first != last) { *d_first++ = op(*first++, (*rest++)...); } return d_first; } </code></pre> </li> <li><p>The first <code>recursive_transform</code> template function overloading: dealing with unary input transform cases.</p> <pre><code>// recursive_transform implementation (the version with unwrap_level) template&lt;std::size_t unwrap_level = 1, class T, class F&gt; constexpr auto recursive_transform(const F&amp; f, const T&amp; input) { if constexpr (unwrap_level &gt; 0) { recursive_invoke_result_t&lt;unwrap_level, F, T&gt; output{}; std::ranges::transform( std::ranges::cbegin(input), std::ranges::cend(input), std::inserter(output, std::ranges::end(output)), [&amp;f](auto&amp;&amp; element) { return recursive_transform&lt;unwrap_level - 1&gt;(f, element); } ); return output; } else { return f(input); } } </code></pre> </li> <li><p>The second <code>recursive_transform</code> template function overloading: handling the cases with multiple input function.</p> <pre><code>// recursive_transform for the multiple parameters cases (the version with unwrap_level) template&lt;std::size_t unwrap_level = 1, class F, class Arg1, class... Args&gt; constexpr auto recursive_transform(const F&amp; f, const Arg1&amp; arg1, const Args&amp;... args) { if constexpr (unwrap_level &gt; 0) { recursive_variadic_invoke_result_t&lt;unwrap_level, F, Arg1, Args...&gt; output{}; transform( std::inserter(output, std::ranges::end(output)), [&amp;f](auto&amp;&amp; element1, auto&amp;&amp;... elements) { return recursive_transform&lt;unwrap_level - 1&gt;(f, element1, elements...); }, std::ranges::cbegin(arg1), std::ranges::cend(arg1), std::ranges::cbegin(args)... ); return output; } else { return f(arg1, args...); } } </code></pre> </li> </ul> <p><strong>The testing code</strong></p> <p>In the following Godbolt link, the testing code is divide into three parts: <code>unary_test_cases</code>, <code>binary_test_cases</code> and <code>ternary_test_cases</code>.</p> <p><a href="https://godbolt.org/z/hs3v3Yoj8" rel="nofollow noreferrer">A Godbolt link is here.</a></p> <p><code>unary_test_cases</code> and <code>binary_test_cases</code> are similar to the previous posts.</p> <p>Let's check <code>ternary_test_cases</code>:</p> <pre><code>void ternary_test_cases() { std::cout &lt;&lt; &quot;*****ternary_test_cases*****&quot; &lt;&lt; std::endl; // non-nested input test, lambda function applied on input directly int test_number = 3; std::cout &lt;&lt; recursive_transform&lt;0&gt;( [](auto&amp;&amp; element1, auto&amp;&amp; element2, auto&amp;&amp; element3) { return element1 + element2 + element3; }, test_number, test_number, test_number) &lt;&lt; std::endl; // nested input test, lambda function applied on input directly std::vector&lt;int&gt; test_vector = { 1, 2, 3 }; std::cout &lt;&lt; recursive_transform&lt;0&gt;([](auto element1, auto element2, auto element3) { return element1.size() + element2.size() + element3.size(); }, test_vector, test_vector, test_vector) &lt;&lt; std::endl; // std::vector&lt;int&gt; -&gt; std::vector&lt;std::string&gt; auto recursive_transform_result = recursive_transform&lt;1&gt;( [](int element1, int element2, int element3)-&gt;std::string { return std::to_string(element1 + element2 + element3); }, test_vector, test_vector, test_vector ); // For testing std::cout &lt;&lt; &quot;std::vector&lt;int&gt; -&gt; std::vector&lt;std::string&gt;: &quot; + recursive_transform_result.at(1) &lt;&lt; std::endl; // recursive_transform_result.at(0) is a std::string // std::vector&lt;string&gt; -&gt; std::vector&lt;int&gt; std::cout &lt;&lt; &quot;std::vector&lt;string&gt; -&gt; std::vector&lt;int&gt;: &quot; &lt;&lt; recursive_transform&lt;1&gt;( [](std::string element1, std::string element2, std::string element3) { return std::atoi((element1 + element2 + element3).c_str()); }, recursive_transform_result, recursive_transform_result, recursive_transform_result).at(0) + 1 &lt;&lt; std::endl; // std::string element to int // std::vector&lt;std::vector&lt;int&gt;&gt; -&gt; std::vector&lt;std::vector&lt;std::string&gt;&gt; std::vector&lt;decltype(test_vector)&gt; test_vector2 = { test_vector, test_vector, test_vector }; auto recursive_transform_result2 = recursive_transform&lt;2&gt;( [](int element1, int element2, int element3) { return std::to_string(element1) + std::to_string(element2) + std::to_string(element3); }, test_vector2, test_vector2, test_vector2 ); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result2.at(0).at(0) &lt;&lt; std::endl; // recursive_transform_result.at(0).at(0) is also a std::string // std::deque&lt;int&gt; -&gt; std::deque&lt;std::string&gt; std::deque&lt;int&gt; test_deque; test_deque.push_back(1); test_deque.push_back(1); test_deque.push_back(1); auto recursive_transform_result3 = recursive_transform&lt;1&gt;( [](int element1, int element2, int element3) { return std::to_string(element1) + std::to_string(element2) + std::to_string(element3); }, test_deque, test_deque, test_deque); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result3.at(0) &lt;&lt; std::endl; // std::deque&lt;std::deque&lt;int&gt;&gt; -&gt; std::deque&lt;std::deque&lt;std::string&gt;&gt; std::deque&lt;decltype(test_deque)&gt; test_deque2; test_deque2.push_back(test_deque); test_deque2.push_back(test_deque); test_deque2.push_back(test_deque); auto recursive_transform_result4 = recursive_transform&lt;2&gt;( [](int element1, int element2, int element3) { return std::to_string(element1) + std::to_string(element2) + std::to_string(element3); }, test_deque2, test_deque2, test_deque2); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result4.at(0).at(0) &lt;&lt; std::endl; // std::list&lt;int&gt; -&gt; std::list&lt;std::string&gt; std::list&lt;int&gt; test_list = { 1, 2, 3, 4 }; auto recursive_transform_result5 = recursive_transform&lt;1&gt;( [](int element1, int element2, int element3) { return std::to_string(element1) + std::to_string(element2) + std::to_string(element3); }, test_list, test_list, test_list); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result5.front() &lt;&lt; std::endl; // std::list&lt;std::list&lt;int&gt;&gt; -&gt; std::list&lt;std::list&lt;std::string&gt;&gt; std::list&lt;std::list&lt;int&gt;&gt; test_list2 = { test_list, test_list, test_list, test_list }; auto recursive_transform_result6 = recursive_transform&lt;2&gt;( [](int element1, int element2, int element3) { return std::to_string(element1) + std::to_string(element2) + std::to_string(element3); }, test_list2, test_list2, test_list2); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result6.front().front() &lt;&lt; std::endl; return; } </code></pre> <p>The output of the testing code above:</p> <pre><code>*****ternary_test_cases***** 9 9 std::vector&lt;int&gt; -&gt; std::vector&lt;std::string&gt;: 6 std::vector&lt;string&gt; -&gt; std::vector&lt;int&gt;: 334 string: 111 string: 111 string: 111 string: 111 string: 111 </code></pre> <p><strong>Other details</strong></p> <p>The different container types can be used simultaneously as the parameters of <code>recursive_transform</code>, such as the following example.</p> <pre><code>std::list&lt;std::string&gt; data1{ &quot;1&quot;, &quot;4&quot;, &quot;7&quot; }; std::vector&lt;std::string&gt; data2{ &quot;2&quot;, &quot;5&quot;, &quot;8&quot; }; std::list&lt;std::string&gt; data3{ &quot;3&quot;, &quot;6&quot;, &quot;9&quot; }; std::list&lt;std::string&gt; data4{ &quot;a&quot;, &quot;b&quot;, &quot;c&quot; }; auto output = recursive_transform&lt;1&gt;( [](auto element1, auto element2, auto element3, auto element4) { return element1 + element2 + element3 + element4; }, data1, data2, data3, data4); std::cout &lt;&lt; typeid(output).name() &lt;&lt; std::endl; for (auto&amp;&amp; element : output) { std::cout &lt;&lt; element &lt;&lt; std::endl; } </code></pre> <p>However, the container type of the output (in the case of output is ranges) follows the first input range parameter. Therefore, the type of the container of <code>output</code> is <code>std::list&lt;&gt;</code>.</p> <p>The output of the testing code above (from clang):</p> <pre><code>NSt7__cxx114listINS_12basic_stringIcSt11char_traitsIcESaIcEEESaIS5_EEE 123a 456b 789c </code></pre> <p>All suggestions are welcome.</p> <p>The summary information:</p> <ul> <li><p>Which question it is a follow-up to?</p> <p><a href="https://codereview.stackexchange.com/q/263767/231235">A recursive_transform template function for the binary operation cases in C++</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <p>I am attempting to improve the extendibility of <code>recursive_transform</code> template function for the multiple parameters cases in this post.</p> </li> <li><p>Why a new review is being asked for?</p> <p>If there is any possible improvement, please let me know.</p> </li> </ul>
[]
[ { "body": "<h1>Unnecessary special-casing of unary functions</h1>\n<p>You don't need to make unitary functions a special case. Parameter packs can be empty after all. You can just delete the unary version of <code>recursive_transform()</code>, and the rest of the code will compile and run just fine.</p>\n<h1>Unnecessary specialiation for <code>unwrap_level</code> 0</h1>\n<p>The specialization of <code>recursive_variadic_invoke_result</code> with an <code>unwrap_level</code> of 0 is never used and can be removed.</p>\n<h1>Avoid using <code>std::endl</code></h1>\n<p><a href=\"https://stackoverflow.com/questions/213907/stdendl-vs-n\">Avoid <code>std::endl</code> and use <code>'\\n'</code> instead.</a> The former is equivalent to the latter, but it also forces the output to be flushed, but this is often unnecessary and reduces performance.</p>\n<h1>Simplify <code>recursive_print()</code></h1>\n<p>Not part of the code you included in your question, but it was in the godbolt link you sent. There are two things that can be simplified here. First, make the version that doesn't recurse anymore just take care of printing individual values:</p>\n<pre><code>template&lt;typename T&gt;\nconstexpr void recursive_print(const T&amp; input, const int level = 0)\n{\n std::cout &lt;&lt; std::string(level, ' ') &lt;&lt; input &lt;&lt; '\\n';\n}\n</code></pre>\n<p>Then the recursing version can work on any <code>std::ranges::input_range</code>, not just the nested ones. Also, use <code>std::ranges::for_each()</code> to print each element; <code>std::ranges::transform()</code> is the wrong algorithm to use since we don't need to modify anything. So:</p>\n<pre><code>template&lt;std::ranges::input_range Range&gt;\nconstexpr void recursive_print(const Range&amp; input, const int level = 0)\n{\n std::cout &lt;&lt; std::string(level, ' ') &lt;&lt; &quot;Level &quot; &lt;&lt; level &lt;&lt; &quot;:&quot; &lt;&lt; std::endl;\n std::ranges::for_each(input, [level](auto&amp;&amp; element) {\n recursive_print(element, level + 1);\n });\n}\n</code></pre>\n<p>Or just use a range-<code>for</code>, there is no real need to use an algorithm here.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T17:15:07.737", "Id": "263988", "ParentId": "263956", "Score": "1" } } ]
{ "AcceptedAnswerId": "263988", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-11T17:02:45.233", "Id": "263956", "Score": "2", "Tags": [ "c++", "recursion", "template", "lambda", "c++20" ], "Title": "A recursive_transform template function for the multiple parameters cases in C++" }
263956
<p>This is my code for download file process. The codes is working fine but would like some code review. Any comment will be appreciated especially on exception handling part. Should I just need one try catch at <code>DownloadFileProcess</code> method or every private method also need a try catch? And if private method also have try catch, is that the right way to throw it back to its parent so that it is testable?</p> <p>This is IDownloadService.cs</p> <pre><code>public interface IDownloadService { Task DownloadFileProcess(); } </code></pre> <p>This is DownloadController.cs</p> <pre><code>[HttpGet] [Route(&quot;DownloadFile&quot;)] public IActionResult DownloadDowJonesFileList(string cronExpression = &quot;0&quot;) { try { if (cronExpression == &quot;0&quot;) { BackgroundJob.Enqueue&lt;IDownloadService&gt;(x =&gt; x.DownloadFileProcess()); return Ok(&quot;Background job started.&quot;); } RecurringJob.AddOrUpdate&lt;IDownloadService&gt;(x =&gt; x.DownloadFileProcess(), cronExpression, TimeZoneInfo.Local); string response = string.Format(&quot;Job update &gt; cronExpression={0}&quot;, cronExpression); return Ok(response); } catch (Exception ex) { _logger.LogError(ex.Message); return Problem(ex.Message); } } </code></pre> <p>This is DownloadService.cs</p> <pre><code>public async Task DownloadFileProcess() { try { FileProcessLog fileToDownload = GetFileToDownload(); if (fileToDownload == null) return; await DownloadFileToDirectory(fileToDownload); } catch (Exception ex) { _logger.LogError(0, ex, ex.Message); throw new Exception(ex.Message); } } private FileProcessLog GetFileToDownload() =&gt; _myContext.FileProcessLogs .Where(d =&gt; d.FileStatus == FileStatus.NEW) .OrderBy(f =&gt; f.FileDate) .FirstOrDefault(); private async Task DownloadFileToDirectory(FileProcessLog fileProcessLog) { await UpdateDownloadStatusDowloading(fileProcessLog); try { var downloadFileUrl = _webURL + fileProcessLog.FileName; var destinationFilePath = Path.GetFullPath(_downloadPath + fileProcessLog.FileName); using (var client = new HttpClientDownloadWithProgress(downloadFileUrl, destinationFilePath, _username, _password)) { client.ProgressChanged += async (totalFileSize, totalBytesDownloaded, progressPercentage, fileName) =&gt; { if (progressPercentage == 100) { await UpdateDownloadStatusDownloaded(fileProcessLog, totalFileSize); return; // process one file per request. } }; await client.StartDownload(); } } catch (Exception ex) { _logger.LogError(0, ex, ex.Message); await UpdateDownloadStatusError(fileProcessLog); throw ex; } } private async Task UpdateDownloadStatusError(FileProcessLog fileProcessLog) { fileProcessLog.FileStatus = FileStatus.ERROR; fileProcessLog.UpdatedDate = DateTime.Now; await _myContext.SaveChangesAsync(); _logger.LogInformation($&quot;Downloaded {fileProcessLog.FileName} error status at {DateTime.Now}&quot;); } </code></pre> <p>Some codes and method removed for brevity.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T13:30:08.253", "Id": "521297", "Score": "0", "body": "Okay, I have updated" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T06:52:48.227", "Id": "521421", "Score": "1", "body": "Is `HttpClientDownloadWithProgress` class a custom one? If so, could you please share with us?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T02:01:36.900", "Id": "521496", "Score": "0", "body": "@PeterCsala yes it a custom class which I got it from the second answer from - https://stackoverflow.com/questions/20661652/progress-bar-with-httpclient" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T07:37:02.463", "Id": "521512", "Score": "1", "body": "Sorry, but I don't get it, why do need this event driven approach? You are only interested about completion of download (`progressPercentage == 100`)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T08:47:27.850", "Id": "521514", "Score": "0", "body": "Previously, I store the download progress in the database. After that, I choose to do so. But after that, I haven't modify the code accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T09:00:23.233", "Id": "521515", "Score": "1", "body": "Just to make it clear: are you interested about the download progress at all? or do you need to know only about the completion fact?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T09:30:01.363", "Id": "521516", "Score": "0", "body": "Right now, I no longer need the download progress." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T09:46:04.263", "Id": "521517", "Score": "1", "body": "Then you could use the built-in `HttpClient`." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-11T21:52:56.780", "Id": "263961", "Score": "0", "Tags": [ "c#", "asp.net-core", "asp.net-web-api", "entity-framework-core" ], "Title": "Download File Service" }
263961
<p>I want to create a database which gives an admin user ability to create schedule for other users to book from. This is second edition of this database schema.</p> <p>I would like to know if there are any structure / logic issues with this schema. What would you change and why or if you see any potential problems regarding its original purpose.</p> <p>What would you use for storing price? I know that FLOAT and DOUBLE are not precise datatypes (estimate) There fore we should not use them to store price. So we can choice from DECIMAL ora INT.</p> <p>Decimal seems to be the good choice however I have seen some payment gateways to force to use INT to store their translation values (so if the price was 11,99 you send to their API 1199)</p> <p>10.4.19-MariaDB</p> <pre><code>-- TABLE Services -- CREATE TABLE Services( id INT AUTO_INCREMENT PRIMARY KEY, service VARCHAR(255) NOT NULL, length_in_min INT NOT NULL DEFAULT 20, capacity INT NOT NULL DEFAULT 1 ); INSERT INTO Services (service, length_in_min, capacity) VALUES ('ANY', 20, 1), -- if ANY allow for all service apointments ('USG', 30, 1), -- if USG allow aonly USG apointments ('VISION', 10, 1); -- if VISION allow aonly VISION apointments SELECT * FROM Services; -- TABLE Staff -- CREATE TABLE Staff( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL, phone VARCHAR(255) NOT NULL ); INSERT INTO Staff (name, email, phone) VALUES (&quot;dr Lee&quot;, &quot;somedr@email.com&quot;, &quot;888 888 888&quot;); SELECT * FROM Staff; -- TABLE Locations -- CREATE TABLE Locations( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL, room VARCHAR (255) DEFAULT 'Main', address1 VARCHAR(255) NOT NULL, address2 VARCHAR(255) NOT NULL, post VARCHAR(6) NOT NULL ); INSERT INTO Locations (name, address1, address2, post) VALUES (&quot;Pet Clinick&quot;, &quot;Sezam Streen 17&quot;, &quot;London&quot;, &quot;06-100&quot;); SELECT * FROM Locations; -- TABLE Schedules -- CREATE TABLE Schedules( id INT AUTO_INCREMENT PRIMARY KEY, day INT NOT NULL, CONSTRAINT chk_if_days_in_range CHECK(day BETWEEN 1 AND 7), location_id INT NOT NULL REFERENCES Locations(id), staff_id INT NOT NULL REFERENCES Staff(id), open TIME NOT NULL, close TIME NOT NULL, CONSTRAINT chk_open_close_order CHECK(close &gt; open), created_at TIMESTAMP DEFAULT NOW(), modified_at TIMESTAMP DEFAULT NOW(), CONSTRAINT chk_edit_timestamp_order CHECK(modified_at &gt;= created_at), starts_at DATETIME NOT NULL DEFAULT NOW(), ends_at DATETIME NOT NULL DEFAULT '9999-01-01 00:00:00', CONSTRAINT chk_booking_datetime_order CHECK(ends_at &gt;= starts_at) ); INSERT INTO Schedules (staff_id, location_id, day, open, close) VALUES (1, 1, 1, '10:00:00', '18:00:00'), (1, 1, 3, '08:30:00', '16:00:00'), (1, 1, 4, '08:30:00', '16:00:00') ; SELECT id as shedule_id, day, open, close, starts_at, ends_at FROM Schedules; -- TABLE Schedules_Service -- CREATE TABLE Schedules_Service( id INT AUTO_INCREMENT PRIMARY KEY, service_id INT NOT NULL REFERENCES Services(id) ON DELETE CASCADE ON UPDATE CASCADE, schedules_id INT NOT NULL REFERENCES Schedules(id) ON DELETE CASCADE ON UPDATE CASCADE, limit_per_shedule INT NOT NULL DEFAULT 999, price DECIMAL(10,2) NOT NULL ); INSERT INTO Schedules_Service (service_id, schedules_id, price, limit_per_shedule) VALUES (1, 1, 60.00, 10), (2, 1, 60.00, 10) ; -- TABLE Clients -- CREATE TABLE Clients( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL, phone VARCHAR(255) NOT NULL, legals BOOLEAN DEFAULT TRUE ); INSERT INTO Clients (name, email, phone) VALUES (&quot;Wiktor&quot;, &quot;some@email.com&quot;, &quot;000 000 000&quot;), (&quot;John&quot;, &quot;john@email.com&quot;, &quot;111 111 111&quot;) ; SELECT * FROM Clients; -- TABLE Appointments -- CREATE TABLE Appointments( id INT AUTO_INCREMENT PRIMARY KEY, service_id INT NOT NULL REFERENCES Services(id) ON DELETE CASCADE ON UPDATE CASCADE, client_id INT NOT NULL REFERENCES Clients(id) ON DELETE CASCADE ON UPDATE CASCADE, -- shedule_id ? Schedule id ? created_at TIMESTAMP DEFAULT NOW(), modified_at TIMESTAMP DEFAULT NOW(), starts_at DATETIME NOT NULL, ends_at DATETIME NOT NULL, approved_by_client BOOLEAN NOT NULL DEFAULT FALSE ); </code></pre>
[]
[ { "body": "<ul>\n<li>Your <code>-- TABLE Services</code> comment is redundant and can be deleted, along with others of its kind</li>\n<li>Your pseudo-inline syntax used to name your constraints is.. fine I guess? I don't usually place much importance on naming constraints, but this is one way to do it</li>\n<li>You used to have <code>on delete</code> and <code>on cascade</code> clauses everywhere. That was the right thing to do, and omitting them is somewhat risky. In MariaDB the default is not cascade as you were using, but rather <a href=\"https://mariadb.com/kb/en/create-table/#foreign-key\" rel=\"nofollow noreferrer\">restrict</a>. This is a reasonable default (more reasonable IMO than Postgres whose default is &quot;no action&quot;), but it is <em>not</em> equivalent to what you were using in the foreign keys of your first question. Aside: PostgreSQL puts a <a href=\"https://www.postgresql.org/docs/current/features.html\" rel=\"nofollow noreferrer\">great deal of effort into being standards-compliant</a>, so I would expect that its implementation is more standard - but I have not verified this.</li>\n<li>The spelling of &quot;schedule&quot; has not changed in the last 48 hours.</li>\n<li>Just as in the last question, you still must not hard-code IDs. Do not hard-code 1 for your staff ID, or pass any other numeric values for IDs as literals like this. <strong>This is guaranteed to break idempotence and validity of your DML under a variety of common situations.</strong> This goes beyond standards adherence and best-practices to being straightforwardly incorrect, and the solutions are trivial enough: either select based on the other columns that you know e.g. staff name, or somewhat more robustly, use a <code>returning</code> clause in your <code>insert</code> to just give you the ID you want, and put it in a variable.</li>\n<li>I'm pleased to see that you used decimal for a monetary quantity.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T16:08:19.827", "Id": "521318", "Score": "0", "body": "Reinderien thank you for your contribution I do appreciate your help. \n\nAny comments in database will be removed at the very end of structuring this database, when It will be close to production ready.\n\nRegrading 5th point. The hardcoding IDs are only for quick demo purpose. I do not intend to use it this way in production. I am aware that I need to query the table to get the ID before making an insert to another table as fk.\n\nI have also seen the INT to be used to store the price data. Wasn't sure which approach to should i choose." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T16:13:35.033", "Id": "521319", "Score": "0", "body": "I understand the urge to make a quick demo, but: whether this is for school, work or open-source contribution, you want to show your best self. Demonstrating correct use of auto-generated columns is very important, so \"easy and temporarily very wrong\" is not a good replacement for \"easy and always right\"." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T14:20:20.793", "Id": "263980", "ParentId": "263965", "Score": "1" } }, { "body": "<h2>Edit II - based on Reinderien user suggestions</h2>\nSchema UPDATE\n<ul>\n<li>spelling of &quot;schedule&quot;</li>\n<li>guidelines on how to properly INSERT foreign key ID to a Table</li>\n</ul>\n<p>+ small tweaks adding UNIQUE to some tables (Clients.email and Services.name) to use those columns to SELECT unique id.</p>\n<p><strong>See general visualisation</strong> <a href=\"https://dbdiagram.io/d/60ec831e4ed9be1c05c9306f\" rel=\"nofollow noreferrer\">[here]</a>\n<a href=\"https://i.stack.imgur.com/PgOht.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PgOht.png\" alt=\"enter image description here\" /></a></p>\n<p>Ps. Should I still need <code>id INT AUTO_INCREMENT PRIMARY KEY</code> if I can use his <code>email</code> as a way retrieve unique data row?</p>\n<p>The database look now as fallow:</p>\n<pre><code>CREATE TABLE Services(\n id INT AUTO_INCREMENT PRIMARY KEY,\n name VARCHAR(255) NOT NULL UNIQUE,\n length_in_min INT NOT NULL DEFAULT 20,\n capacity INT NOT NULL DEFAULT 1\n);\n\nINSERT INTO Services (name, length_in_min, capacity) \nVALUES \n ('ANY', 20, 1), -- allow any type appointment\n ('USG', 30, 1), -- allow only USG type appointments\n ('VISION', 10, 1)-- allow only VISION type appointments\n;\n\nSELECT * FROM Services;\n\nCREATE TABLE Staff(\n id INT AUTO_INCREMENT PRIMARY KEY,\n title VARCHAR(255) NOT NULL,\n name VARCHAR(255) NOT NULL,\n surname VARCHAR(255) NOT NULL,\n spec VARCHAR(255) NOT NULL,\n dob YEAR NOT NULL,\n email VARCHAR(255) NOT NULL,\n phone VARCHAR(255) NOT NULL\n);\n\nINSERT INTO Staff (title, name, surname, spec, dob, email, phone) \nVALUES\n ('dr', 'John', 'Lee', 'vet', '1988-01-01', 'somedr@email.com', '888 888 888');\n\nSELECT * FROM Staff;\n\nCREATE TABLE Locations(\n id INT AUTO_INCREMENT PRIMARY KEY,\n name VARCHAR(255) NOT NULL,\n room VARCHAR (255) DEFAULT NULL,\n address1 VARCHAR(255) NOT NULL,\n address2 VARCHAR(255) NOT NULL,\n post VARCHAR(6) NOT NULL\n);\n\nINSERT INTO Locations (name, address1, address2, post) \nVALUES\n ('Pet Clinick', 'Sezam Streen 17', 'London', '06-100');\n\nSELECT * FROM Locations;\n\nCREATE TABLE Schedules(\n id INT AUTO_INCREMENT PRIMARY KEY,\n day INT NOT NULL,\n CHECK(day BETWEEN 1 AND 7),\n location_id INT NOT NULL REFERENCES Locations(id),\n staff_id INT NOT NULL REFERENCES Staff(id),\n open TIME NOT NULL,\n close TIME NOT NULL,\n CHECK(close &gt; open),\n created_at TIMESTAMP DEFAULT NOW(),\n modified_at TIMESTAMP DEFAULT NOW() ON UPDATE NOW(),\n CHECK(modified_at &gt;= created_at),\n starts_at DATETIME NOT NULL DEFAULT NOW(),\n ends_at DATETIME NOT NULL DEFAULT '9999-01-01 00:00:00', \n CHECK(ends_at &gt;= starts_at)\n);\n\nINSERT INTO Schedules (staff_id, location_id, day, open, close) \nVALUES\n (\n (SELECT id FROM Staff st WHERE st.name = 'John' AND st.surname = 'Lee' AND spec = 'vet'),\n (SELECT id FROM Locations l WHERE l.name = '' and l.room = 'Main'), \n 1, \n '10:00:00', \n '18:00:00'\n ), -- query others the same way\n (1, 1, 2, '10:00:00', '18:00:00'),\n (1, 1, 3, '10:00:00', '18:00:00'),\n (1, 1, 4, '10:00:00', '18:00:00'),\n (1, 1, 5, '10:00:00', '18:00:00'),\n (1, 1, 6, '08:30:00', '16:00:00'),\n (1, 1, 7, '08:30:00', '16:00:00')\n;\n\nSELECT id as schedule_id, day, open, close, starts_at, ends_at FROM Schedules;\n\nCREATE TABLE Schedules_Service(\n id INT AUTO_INCREMENT PRIMARY KEY,\n service_id INT NOT NULL REFERENCES Services(id)\n ON DELETE CASCADE ON UPDATE CASCADE,\n schedules_id INT NOT NULL REFERENCES Schedules(id)\n ON DELETE CASCADE ON UPDATE CASCADE,\n limit_per_schedule INT NOT NULL DEFAULT 999,\n price DECIMAL(10,2) NOT NULL\n);\n\nINSERT INTO Schedules_Service (service_id, schedules_id, price, limit_per_schedule)\nVALUES\n (\n (SELECT id FROM Services WHERE name = 'ANY'),\n (SELECT id FROM Schedules WHERE id = 1),\n 60.00,\n 10\n ), -- query others the same way\n (2, 1, 60.00, 10)\n;\n\nCREATE TABLE Clients(\n id INT AUTO_INCREMENT PRIMARY KEY,\n name VARCHAR(255) NOT NULL,\n email VARCHAR(255) NOT NULL UNIQUE,\n phone VARCHAR(255) NOT NULL,\n legals BOOLEAN DEFAULT TRUE\n);\n\nINSERT INTO Clients (name, email, phone) \nVALUES \n ('Wiktor', 'some@email.com', '000 000 000'),\n ('John', 'john@email.com', '111 111 111')\n;\n\nSELECT * FROM Clients;\n\nCREATE TABLE Appointments(\n id INT AUTO_INCREMENT PRIMARY KEY,\n service_id INT NOT NULL REFERENCES Services(id)\n ON DELETE CASCADE ON UPDATE CASCADE,\n client_id INT NOT NULL REFERENCES Clients(id)\n ON DELETE CASCADE ON UPDATE CASCADE,\n -- schedule_id ? Schedule id ?\n created_at TIMESTAMP DEFAULT NOW(),\n modified_at TIMESTAMP DEFAULT NOW(),\n starts_at DATETIME NOT NULL,\n ends_at DATETIME NOT NULL,\n approved_by_client BOOLEAN NOT NULL DEFAULT FALSE\n -- UNIQUE KEY make_booking_unique (starts_at, ends_at, ...)\n);\n\nINSERT INTO Appointments (client_id, service_id, starts_at, ends_at) \nVALUES \n ( \n (SELECT id FROM Clients WHERE email = 'some@email.com'), \n (SELECT id FROM Services WHERE name = 'USG'), \n '2021-07-10 11:00:00', \n '2021-07-10 11:30:00'\n ), -- query others the same way\n (1, 2, '2021-07-10 12:00:00', '2021-07-10 12:30:00'), -- 2 is USG name\n (1, 2, '2021-07-10 13:00:00', '2021-07-10 13:30:00'), -- 2 is USG name\n (1, 1, '2021-07-10 13:30:00', '2021-07-10 14:00:00') -- 1 is any name\n;\n\nSELECT id, starts_at, ends_at FROM Appointments ORDER BY starts_at;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T17:04:50.137", "Id": "263987", "ParentId": "263965", "Score": "0" } }, { "body": "<h2 id=\"reserved-keywords\">Reserved keywords</h2>\n<p>Be careful with overly generic keywords, there is a good chance that they are reserved keywords.\nName, Open, Close are <a href=\"https://dev.mysql.com/doc/refman/8.0/en/keywords.html#keywords-8-0-detailed-O\" rel=\"nofollow noreferrer\">reserved keywords</a> in MySQL.</p>\n<p>Accordingly, I suggest that you you rename some objects from 'name' to for example: location_name, staff_name.</p>\n<h2 id=\"varchar\">VARCHAR</h2>\n<p>VARCHAR (255) sounds like a default value suggested by a design tool. For an E-mail address the need for 255 characters is dubious. For a phone number this is definitely oversized. Even in international format I don't think it would exceed 20 characters.</p>\n<p>Think about the UI and what kind of values you are willing to accept, even while keeping room for flexibility. Then model your database along reasonable, real-world expectations.</p>\n<p>This &quot;design&quot; choice may (or may not have) an impact on performance, depending on a number of factors. Discussion: <a href=\"https://stackoverflow.com/a/262476\">Are there disadvantages to using a generic varchar(255) for all text-based fields?</a> and <a href=\"https://dba.stackexchange.com/a/76470/203569\">MySQL - varchar length and performance</a>.</p>\n<h2 id=\"case\">Case</h2>\n<p>I advise that you use full <strong>lower case</strong> for all object names. Keep in mind that on Linux systems, the filesystem is usually <strong>case-sensitive</strong> and that applies to objects such as tables.</p>\n<h2 id=\"indexes\">Indexes</h2>\n<p>What about indexes ? If your tables keep on growing, queries are going to be take longer and longer because they are not optimized in any way. Think about the JOINs, and what fields you are going to do lookups against.</p>\n<h2 id=\"unique\">UNIQUE</h2>\n<p>You have a UNIQUE constraint on the E-mail address, which makes sense. However, in the real world, you might find yourself in a situation where two people (eg spouses) share the same E-mail address. So is this a good idea ? This may be an edge case but I would relax the requirement. The point is that the address could be a search criterion but not the sole customer identifier.</p>\n<h2 id=\"misc\">Misc.</h2>\n<p>In the table clients, it would make sense to split the name in two distinct columns: family name, surname, even if that table is clearly minimalist. For instance, you might want to search/sort on family name only. Also, the front-end UI will probably use a form or some kind of datagrid with columns to render the data, and separating the two fields makes sense. Not doing so could be a source of <strong>ambiguity</strong>, because the distinction between surname and family name may not always be clear.</p>\n<h2 id=\"datetime\">Datetime</h2>\n<p>In table Staff, you defined the field dob as:</p>\n<pre><code> dob YEAR NOT NULL\n</code></pre>\n<p>This not consistent with your insert example ('1988-01-01'). You could simply use the <a href=\"https://dev.mysql.com/doc/refman/8.0/en/datetime.html\" rel=\"nofollow noreferrer\">DATE</a> datatype.</p>\n<p>Regarding the choice of datatypes: table Appointments uses both TIMESTAMP and DATETIME but they are not equivalent. Check the link above for details. Be aware that TIMESTAMP has the <strong>2K38</strong> problem:</p>\n<blockquote>\n<p>TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19\n03:14:07' UTC.</p>\n</blockquote>\n<p>So any program that relies on it is not future-proof. I recommend that you use datetime and for auto-updading last changed time: <a href=\"https://dev.mysql.com/doc/refman/8.0/en/timestamp-initialization.html\" rel=\"nofollow noreferrer\">Automatic Initialization and Updating for TIMESTAMP and DATETIME</a></p>\n<p>What is the justification for:</p>\n<pre><code>ends_at DATETIME NOT NULL DEFAULT '9999-01-01 00:00:00'\n</code></pre>\n<p>in table Schedules ? Just let it null by default, then your program will know the event is open-ended.</p>\n<p>Last but not least, assuming that you are based in the US and taking into account the possibility that your program could be deployed at multiple locations nationwide (even in a remote future), you might want to consider using <a href=\"https://dev.mysql.com/doc/refman/8.0/en/time-zone-support.html\" rel=\"nofollow noreferrer\">timezone-aware datatimes</a>. While this adds initial complexity this also provides flexibility and adaptability. After all a datetime without context is meaningless.</p>\n<h2 id=\"number-formatting\">Number formatting</h2>\n<p>In that same table you store a phone number like: '888 888 888'.\nRecommendation: store numbers without spaces or artificial characters. Let your program handle the formatting of numbers. I would maybe add the country code in case you have foreign customers. Or you could decide to store all numbers in international format eg: +18004567890.</p>\n<p>In table Locations:</p>\n<pre><code>post VARCHAR(6) NOT NULL\n</code></pre>\n<p>Is this the zip code ? Then unsigned int zero fill is a possible option. But this is only good for US addresses. For a British postcode this would be a bit short.</p>\n<h2 id=\"charset\">Charset</h2>\n<p>What is the charset you are using ? Will your application handle accented characters smoothly ? Will client José Peños be saved to the database without glitches ?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T19:53:43.680", "Id": "521329", "Score": "0", "body": "Per https://mariadb.com/kb/en/identifier-names/ reserved words can be escaped, which is an alternative to renaming." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T19:56:19.550", "Id": "521330", "Score": "0", "body": "Re. _Just let [ends_at] null by default_ - there are some contexts in which a far-future date will simplify queries over having a nullable column. For instance, if you're doing a naive comparison of the current date to `ends_at`, the expression would evaluate to `false` in the far-future case and `null` in the nullable case, requiring a separate coalesce." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T19:59:26.797", "Id": "521331", "Score": "0", "body": "Re. _it would make sense to split the name in two distinct columns: family name, surname, even if that table is clearly minimalist_ - this is deeply problematic. It's an understandable reflex for people used to Western culture where names have clear first and last components, but there are many cultures where this is not remotely true. Even if the database were written to serve one well-known country such as Canada where that's the norm, there are many humans outside of the norm that come from other places. The single-string name field is sensible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T20:09:33.383", "Id": "521332", "Score": "0", "body": "read e.g. https://www.uxbooth.com/articles/creating-more-inclusive-and-culturally-sensitive-forms/" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T19:51:49.790", "Id": "263991", "ParentId": "263965", "Score": "2" } }, { "body": "<h2>Edit III - based on Anonymous user suggestions: </h2>\n+ escaped reserved keywords<br>\n+ tables are named now lower case<br>\n+ changed YEAR to DATE<br>\n+ used shorter VARCHAR (to avoid large temp tables - thanks for that)<br><br>\n+ moved some stuff from schedules to services_schedules<br>\n<p>+ added conditional insert based on existence in schedule table and no existence in appointments table (under development)<br>\n- other in progress</p>\n<p>if you would like to propose some changes you can do it on GitHub <a href=\"https://github.com/DevWL/Appointment-DB/blob/main/appointemnt%20scheema.sql\" rel=\"nofollow noreferrer\">here</a></p>\n<pre><code>DROP DATABASE IF EXISTS bookings;\nCREATE DATABASE bookings CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;\n\nUSE bookings;\n\nCREATE TABLE services(\n id INT AUTO_INCREMENT PRIMARY KEY,\n `name` VARCHAR(30) NOT NULL UNIQUE,\n length_in_min INT NOT NULL DEFAULT 20,\n capacity INT NOT NULL DEFAULT 1\n);\n\nINSERT INTO services (`name`, length_in_min, capacity) \nVALUES \n ('ANY', 20, 1), -- allow any type appointment\n ('USG', 30, 1), -- allow only USG type appointments\n ('VISION', 10, 1)-- allow only VISION type appointments\n;\n\nSELECT * FROM services;\n\nCREATE TABLE staff(\n id INT AUTO_INCREMENT PRIMARY KEY,\n title VARCHAR(20) NOT NULL,\n `name` VARCHAR(30) NOT NULL,\n surname VARCHAR(60) NOT NULL,\n spec VARCHAR(60) NOT NULL,\n dob DATE NOT NULL,\n email VARCHAR(50) NOT NULL,\n phone VARCHAR(16) NOT NULL\n);\n\nINSERT INTO staff (title, `name`, surname, spec, dob, email, phone) \nVALUES\n ('dr', 'John', 'Lee', 'vet', '1988-01-01', 'somedr@email.com', '888 888 888')\n;\n\nSELECT * FROM staff;\n\nCREATE TABLE locations(\n id INT AUTO_INCREMENT PRIMARY KEY,\n `name` VARCHAR(30) NOT NULL,\n room VARCHAR (20) DEFAULT NULL,\n address1 VARCHAR(50) NOT NULL,\n address2 VARCHAR(50) NOT NULL,\n post VARCHAR(8) NOT NULL\n);\n\nINSERT INTO locations (`name`, address1, address2, post) \nVALUES\n ('Pet Clinick', 'Sezam Streen 17', 'London', '06-100')\n;\n\nSELECT * FROM locations;\n\nCREATE TABLE schedules(\n id INT AUTO_INCREMENT PRIMARY KEY,\n `day` INT NOT NULL,\n CHECK(`day` BETWEEN 1 AND 7),\n location_id INT NOT NULL REFERENCES locations(id),\n `open` TIME NOT NULL,\n `close` TIME NOT NULL,\n CHECK(close &gt; open),\n created_at TIMESTAMP DEFAULT NOW(),\n modified_at TIMESTAMP DEFAULT NOW() ON UPDATE NOW(),\n CHECK(modified_at &gt;= created_at),\n starts_at DATETIME NOT NULL DEFAULT NOW(),\n ends_at DATETIME DEFAULT NULL,\n CHECK(ends_at &gt;= starts_at)\n);\n\nINSERT INTO schedules (location_id, `day`, `open`, `close`, starts_at) \nVALUES\n (\n (SELECT id FROM locations lo WHERE lo.name = 'Pet Clinick'), \n 1, \n '10:00:00', \n '18:00:00',\n '2021-01-01 00:00:00'\n ), -- query others the same way\n (1, 2, '10:00:00', '18:00:00', '2021-01-01 00:00:00'),\n (1, 3, '10:00:00', '18:00:00', '2021-01-01 00:00:00'),\n (1, 4, '10:00:00', '18:00:00', '2021-01-01 00:00:00'),\n (1, 5, '10:00:00', '18:00:00', '2021-01-01 00:00:00'),\n (1, 6, '08:30:00', '16:00:00', '2021-01-01 00:00:00'),\n (1, 7, '08:30:00', '16:00:00', '2021-01-01 00:00:00')\n;\n\nSELECT sc.id, sc.day, sc.open, sc.close, sc.starts_at, sc.ends_at FROM schedules sc;\n\nCREATE TABLE schedules_service(\n id INT AUTO_INCREMENT PRIMARY KEY,\n staff_id INT NOT NULL REFERENCES staff(id),\n service_id INT NOT NULL REFERENCES services(id)\n ON DELETE CASCADE ON UPDATE CASCADE,\n schedules_id INT NOT NULL REFERENCES schedules(id)\n ON DELETE CASCADE ON UPDATE CASCADE,\n starts_at TIME NOT NULL,\n ends_at TIME NOT NULL\n CHECK(ends_at &gt;= starts_at),\n limit_per_schedule INT NOT NULL DEFAULT 999,\n price DECIMAL(10,2) NOT NULL\n);\n\nINSERT INTO schedules_service (staff_id, service_id, schedules_id, starts_at, ends_at, price, limit_per_schedule)\nVALUES\n (\n (SELECT id FROM staff st WHERE st.name = 'John' AND st.surname = 'Lee' AND spec = 'vet'),\n (SELECT id FROM services s WHERE s.name = 'USG'),\n (SELECT id FROM schedules s WHERE s.day = 1),\n '12:00:00',\n '12:30:00',\n 60.00,\n 10\n ), -- query others the same way\n (1, 2, 2,'13:00:00', '13:30:00', 60.00, 10)\n;\n\nCREATE TABLE clients(\n id INT AUTO_INCREMENT PRIMARY KEY,\n `name` VARCHAR(30) NOT NULL,\n email VARCHAR(60) NOT NULL UNIQUE,\n phone VARCHAR(16) NOT NULL,\n legals BOOLEAN DEFAULT TRUE\n);\n\nINSERT INTO clients (`name`, email, phone) \nVALUES \n ('Wiktor', 'some@email.com', '000 000 000'),\n ('John', 'john@email.com', '111 111 111')\n;\n\nSELECT * FROM clients;\n\nCREATE TABLE appointments(\n id INT AUTO_INCREMENT PRIMARY KEY,\n service_id INT NOT NULL REFERENCES services(id)\n ON DELETE CASCADE ON UPDATE CASCADE,\n client_id INT NOT NULL REFERENCES clients(id)\n ON DELETE CASCADE ON UPDATE CASCADE,\n -- schedule_id ? Schedule id ?\n created_at TIMESTAMP DEFAULT NOW(),\n modified_at TIMESTAMP DEFAULT NOW() ON UPDATE NOW(),\n CHECK(modified_at &gt;= created_at),\n starts_at DATETIME NOT NULL,\n ends_at DATETIME NOT NULL,\n approved_by_client BOOLEAN NOT NULL DEFAULT FALSE\n -- UNIQUE KEY make_booking_unique (starts_at, ends_at)\n);\n\n-- INSERT INTO appointments (client_id, service_id, starts_at, ends_at) \n-- VALUES \n-- ( \n-- (SELECT id FROM clients WHERE email = 'some@email.com'), \n-- (SELECT id FROM services WHERE name = 'USG'), \n-- '2021-07-10 11:00:00', \n-- '2021-07-10 11:30:00'\n-- ), -- query others the same way\n-- (1, 2, '2021-07-10 12:00:00', '2021-07-10 12:30:00'), -- 2 is USG name\n-- (1, 2, '2021-07-10 13:00:00', '2021-07-10 13:30:00'), -- 2 is USG name\n-- (1, 1, '2021-07-10 13:30:00', '2021-07-10 14:00:00') -- 1 is any name\n-- ;\n\nSET @s := '2021-07-12 12:00:00';\nSET @e := '2021-07-12 12:30:00';\n\nSELECT( WEEKDAY(@s));\nSELECT(TIME(@s));\nSELECT * FROM schedules sc LEFT JOIN schedules_service ss ON ss.schedules_id = sc.id;\n\nSELECT ss.id, sc.day FROM schedules sc LEFT JOIN schedules_service ss ON ss.schedules_id = sc.id\n WHERE \n WEEKDAY(@s) + 1 = sc.day \n AND TIME(@s) = ss.starts_at \n AND TIME(@e) = ss.ends_at;\n\nINSERT INTO appointments\n (client_id, service_id, starts_at, ends_at) \n SELECT \n (SELECT id FROM clients c WHERE c.email = 'some@email.com'),\n (SELECT id FROM services s WHERE s.name = 'ANY'),\n @s, \n @e\n WHERE NOT EXISTS -- search for colisions if there is colision row returned no insert will be run\n (\n SELECT id FROM appointments\n WHERE \n (starts_at &lt;= @s AND @s &lt; ends_at)\n OR (starts_at &lt; @e AND @e &lt;= ends_at)\n OR (@s &lt;= starts_at AND starts_at &lt; @e)\n LIMIT 1 \n )\n AND EXISTS -- see if this timeslot is available for bookings\n (\n SELECT ss.id, sc.day FROM schedules sc LEFT JOIN schedules_service ss ON ss.schedules_id = sc.id\n WHERE \n (service_id = (SELECT id FROM services s WHERE s.name = 'USG') OR service_id = (SELECT id FROM services s WHERE s.name = 'ANY'))\n AND WEEKDAY(@s) + 1 = sc.day\n AND @s &gt;= sc.starts_at \n AND TIME(@s) = ss.starts_at \n AND TIME(@e) = ss.ends_at\n )\n AND (1=1) -- CHECK FOR HOLIDAYS AND OFF DAYS\n;\n \nSELECT a.id, c.name, s.name, a.starts_at, a.ends_at FROM appointments a LEFT JOIN services s ON a.service_id = s.id LEFT JOIN clients c ON a.client_id = c.id;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T03:11:06.367", "Id": "264036", "ParentId": "263965", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T02:20:47.067", "Id": "263965", "Score": "0", "Tags": [ "sql", "mysql", "database" ], "Title": "Appointment database - design II" }
263965
<p>Playing around with the google API.</p> <p>I have written demo applications to use the google gmail API. But what I am actually looking for is a review of the C++ wrappers for Authentication (OAuth2) and an initial GMail wrapper. Want input before I start going any further.</p> <p>Please take your time to point out all even the slightest issues you have the code (my skin is thick). <strong>BUT</strong> also interested in if anybody can think of better ways to design the interfaces. How would you expect to use objects from Google (we don't have to map REST API to class method I would like to design a system were interacting with the objects at the code level is intuative).</p> <h2 id="curlhelper.h-536e">CurlHelper.h</h2> <pre><code>#ifndef THROSANVIL_CURL_CURLHELPER_H #define THROSANVIL_CURL_CURLHELPER_H #include &lt;curl/curl.h&gt; #include &lt;memory&gt; #include &lt;functional&gt; #include &lt;string&gt; namespace ThorsAnvil::Curl { using CurlDeleter = std::function&lt;void(CURL*)&gt;; using CurlHDeleter= std::function&lt;void(curl_slist*)&gt;; class CurlUniquePtr: public std::unique_ptr&lt;CURL, CurlDeleter&gt; { public: CurlUniquePtr(std::string const&amp; url) : std::unique_ptr&lt;CURL, CurlDeleter&gt;{curl_easy_init(), [](CURL* c){curl_easy_cleanup(c);}} { if (get() == nullptr) { throw std::runtime_error(&quot;Failed to Create Curl Handle&quot;); } if (curl_easy_setopt(get(), CURLOPT_URL, url.c_str()) != CURLE_OK) { throw std::runtime_error(&quot;Could not set a valid URL&quot;); } } operator CURL*() { return get(); } }; class CurlHeaderUniquePtr: public std::unique_ptr&lt;curl_slist, CurlHDeleter&gt; { public: CurlHeaderUniquePtr(std::initializer_list&lt;std::string&gt; const&amp; list = std::initializer_list&lt;std::string&gt;{}) : std::unique_ptr&lt;curl_slist, CurlHDeleter&gt;{nullptr, [](curl_slist* s){curl_slist_free_all(s);}} { for (auto const&amp; head: list) { append(head); } } void append(std::string const&amp; header) { curl_slist* tmp = curl_slist_append(get(), header.c_str()); if (tmp) { release(); reset(tmp); } } }; } #endif </code></pre> <h2 id="credentials.h-tzmn">Credentials.h</h2> <pre><code>#ifndef THORSANVIL_GOOGLE_CREDENTIALS_H #define THORSANVIL_GOOGLE_CREDENTIALS_H #include &quot;CurlHelper.h&quot; #include &quot;ThorSerialize/Traits.h&quot; #include &quot;ThorSerialize/SerUtil.h&quot; #include &quot;ThorSerialize/JsonThor.h&quot; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;fstream&gt; #include &lt;sstream&gt; extern &quot;C&quot; size_t outputToStream(char* ptr, size_t size, size_t nmemb, void* userdata) { std::iostream&amp; stream = *(reinterpret_cast&lt;std::iostream*&gt;(userdata)); stream.write(ptr, size * nmemb); return size * nmemb; } extern &quot;C&quot; size_t dropHeaders(char* ptr, size_t size, size_t nmemb, void* userdata) { // Drop and ignore headers. // Otherwise they clutter the standard output. return size * nmemb; } namespace ThorsAnvil::Google { struct ServiceAccount { std::string client_id; std::string project_id; std::string auth_uri; std::string token_uri; std::string auth_provider_x509_cert_url; std::string client_secret; std::vector&lt;std::string&gt; redirect_uris; }; struct ApplicaionInfo { ServiceAccount installed; ApplicaionInfo(std::istream&amp; stream) { namespace TAS=ThorsAnvil::Serialize; stream &gt;&gt; TAS::jsonImporter(*this, TAS::ParserInterface::ParserConfig{TAS::JsonParser::ParseType::Strict, false}); } std::string getManualAuthURL(std::string const&amp; scope) { // Find URL std::size_t uriIndix = 0; for (;uriIndix &lt; installed.redirect_uris.size(); ++uriIndix) { if (installed.redirect_uris[uriIndix].substr(0,4) == &quot;urn:&quot;) { break; } } if (uriIndix &gt;= installed.redirect_uris.size()) { throw std::runtime_error(&quot;Failed to find URN&quot;); } std::stringstream oauth2URLStream; oauth2URLStream &lt;&lt; &quot;https://accounts.google.com/o/oauth2/v2/auth&quot; &lt;&lt; &quot;?client_id=&quot; &lt;&lt; installed.client_id &lt;&lt; &quot;&amp;redirect_uri=&quot; &lt;&lt; installed.redirect_uris[uriIndix] &lt;&lt; &quot;&amp;response_type=code&quot; &lt;&lt; &quot;&amp;scope=&quot; &lt;&lt; scope; return oauth2URLStream.str(); } void createCredentialFile(std::string const&amp; credFileName, std::string const&amp; token) { namespace TAC=ThorsAnvil::Curl; namespace TAS=ThorsAnvil::Serialize; // Find URL std::size_t uriIndix = 0; for (;uriIndix &lt; installed.redirect_uris.size(); ++uriIndix) { if (installed.redirect_uris[uriIndix].substr(0,4) == &quot;urn:&quot;) { break; } } if (uriIndix &gt;= installed.redirect_uris.size()) { throw std::runtime_error(&quot;Failed to find URN&quot;); } // Convert token into OAuth2 credentials // Part 1: Build Request std::stringstream requestBodyStream; requestBodyStream &lt;&lt; &quot;client_id=&quot; + installed.client_id &lt;&lt; &quot;&amp;client_secret=&quot; + installed.client_secret &lt;&lt; &quot;&amp;grant_type=authorization_code&quot; &lt;&lt; &quot;&amp;redirect_uri=&quot; + installed.redirect_uris[uriIndix] &lt;&lt; &quot;&amp;code=&quot; + token; // Open a scope so we can create an output file stream to credStore. // Closed at the end of this scope. std::string requestBody = requestBodyStream.str(); std::fstream credStore(credFileName, std::ios_base::out); // Part 2: Send request to OAuth server TAC::CurlUniquePtr curl(&quot;https://oauth2.googleapis.com/token&quot;); TAC::CurlHeaderUniquePtr headerList{{&quot;Content-Type: application/x-www-form-urlencoded&quot;}}; curl_easy_setopt(curl, CURLOPT_POST, 1L); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerList.get()); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, requestBody.c_str()); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, requestBody.size()); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, outputToStream); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &amp;static_cast&lt;std::iostream&amp;&gt;(credStore)); curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, dropHeaders); CURLcode code = curl_easy_perform(curl); if (code != CURLE_OK) { throw std::runtime_error(&quot;Failed to get OAuth2 credentials&quot;); } } }; struct OAuth2Creds { std::string access_token; std::size_t expires_in; std::string refresh_token; std::string scope; std::string token_type; OAuth2Creds(std::istream&amp; stream) { namespace TAS=ThorsAnvil::Serialize; stream &gt;&gt; TAS::jsonImporter(*this, TAS::ParserInterface::ParserConfig{TAS::JsonParser::ParseType::Strict, false}); } void refresh(ApplicaionInfo&amp; application) { namespace TAC=ThorsAnvil::Curl; namespace TAS=ThorsAnvil::Serialize; TAC::CurlUniquePtr refreshRequest(&quot;https://oauth2.googleapis.com//token&quot;); curl_easy_setopt(refreshRequest, CURLOPT_POST, 1L); std::stringstream bodyStream; bodyStream &lt;&lt; &quot;client_id=&quot; &lt;&lt; application.installed.client_id &lt;&lt; &quot;&amp;client_secret=&quot; &lt;&lt; application.installed.client_secret &lt;&lt; &quot;&amp;refresh_token=&quot; &lt;&lt; refresh_token &lt;&lt; &quot;&amp;grant_type=refresh_token&quot;; std::string body(std::move(bodyStream.str())); curl_easy_setopt(refreshRequest, CURLOPT_POSTFIELDS, body.c_str()); curl_easy_setopt(refreshRequest, CURLOPT_POSTFIELDSIZE, body.size()); std::stringstream stream; curl_easy_setopt(refreshRequest, CURLOPT_WRITEFUNCTION, outputToStream); curl_easy_setopt(refreshRequest, CURLOPT_WRITEDATA, &amp;static_cast&lt;std::iostream&amp;&gt;(stream)); CURLcode code = curl_easy_perform(refreshRequest); if (code != CURLE_OK) { throw std::runtime_error(&quot;Failed to refresh OAuth2 credentials&quot;); } }; } ThorsAnvil_MakeTrait(ThorsAnvil::Google::OAuth2Creds, access_token, expires_in, refresh_token, scope, token_type); ThorsAnvil_MakeTrait(ThorsAnvil::Google::ServiceAccount, client_id, project_id, auth_uri, token_uri, auth_provider_x509_cert_url, client_secret, redirect_uris); ThorsAnvil_MakeTrait(ThorsAnvil::Google::ApplicaionInfo, installed); #endif </code></pre> <h2 id="googlemail.h-o6y1">GoogleMail.h</h2> <pre><code>#ifndef THORSANVIL_GOOGLE_MAIL_H #define THORSANVIL_GOOGLE_MAIL_H #include &quot;ThorSerialize/Traits.h&quot; #include &quot;ThorSerialize/SerUtil.h&quot; #include &quot;ThorSerialize/JsonThor.h&quot; #include &lt;string&gt; #include &lt;vector&gt; namespace ThorsAnvil::Google { struct Header { std::string name; std::string value; }; struct MessagePartBody { std::string attachmentId; std::size_t size; std::string data; }; struct MessagePart { using Headers = std::vector&lt;Header&gt;; using MessageParts = std::vector&lt;MessagePart&gt;; std::string partId; std::string mimeType; std::string filename; Headers headers; MessagePartBody body; MessageParts parts; }; struct Message { using Labels = std::vector&lt;std::string&gt;; std::string id; std::string threadId; Labels labelIds; std::string snippet; MessagePart payload; std::size_t sizeEstimate; std::string raw; }; struct Draft { std::string id; Message message; }; } ThorsAnvil_MakeTrait(ThorsAnvil::Google::Header, name, value); ThorsAnvil_MakeTrait(ThorsAnvil::Google::MessagePartBody, attachmentId, size, data); ThorsAnvil_MakeTrait(ThorsAnvil::Google::MessagePart, partId, mimeType, filename, headers, body, parts); ThorsAnvil_MakeTrait(ThorsAnvil::Google::Message, id, threadId, labelIds, snippet, payload, sizeEstimate, raw); ThorsAnvil_MakeTrait(ThorsAnvil::Google::Draft, id, message); #endif </code></pre> <h2 id="auth.cpp-ulwa">auth.cpp</h2> <pre><code>#include &quot;Credentials.h&quot; #include &quot;CurlHelper.h&quot; #include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;iterator&gt; namespace TAG=ThorsAnvil::Google; namespace TAC=ThorsAnvil::Curl; void printIntructions() { std::cout &lt;&lt; R&quot;Instructions( First Run: You need to manually authorize with Google to get an OAuth2 token. If you already have an Account/Application/OAuth2 tokens set up you can reuse them These instructions assume you have not set up anything yet and are starting fresh feel free to skip instructions that you have already completed before Step 0: Set up a google developer account A: https://console.cloud.google.com/ B: Sign in with your normal google credentials Step 1: Create an Application in Google console A: Open: https://console.cloud.google.com/home/dashboard B: Click on the Burger top left C: From the DropDown Menu Select: 'IAM &amp; Admin/Create a Project' C1: Name the App Click Create. Step 2: Create OAuth2 Credential A: Click on the Burger top left B: From the DropDown Menu Select: 'APIs &amp; Services/Credentials' C: Click the button '+ Create Credentials' D: From the DropDown Menu Select: 'OAuth client ID' D1: Make the 'Application Type' a 'Desktop app' D2: Enter the Application Name D2: Click 'Create' D3: This brings you back to the 'Credentials Screen' D4: Clock the 'Download Arrow (on the right) next to your OAuth2 Client Step 3: Locate the Key File. A: Step 3 should have downloaded a file your computer. B: Locate this file and put it somewhere safe and note the absolute address of this file C: Enter the Full path of this file below when asked Step 4: Enable API A: Click on the Burger top left B: From the DropDown Menu Select: 'APIs &amp; Services/Library' C: Search for the API you want (gmail) D: Select the API. Then Click 'Enable' Step 5: Decide the scope of you application A: Goto https://developers.google.com/identity/protocols/oauth2/scopes B: Locate the scope you want to give this application: (https://www.googleapis.com/auth/gmail.compose) C: Enter this value blow when asked )Instructions&quot;; } void oauth2() { std::ifstream credStore(&quot;creds.json&quot;); if (!credStore) { printIntructions(); // Get the Key File std::cout &lt;&lt; &quot;\n\nPlease enter path of key file\n&quot;; std::string keyFilePath; std::getline(std::cin, keyFilePath); std::ifstream keyFileStream(keyFilePath); TAG::ApplicaionInfo keyFile(keyFileStream); // Get the Scope Info std::cout &lt;&lt; &quot;\n\nPlease enter the scope for the OAuth2 token\n&quot;; std::string scope; std::getline(std::cin, scope); // Request the user authorize the App. std::string oauth2URL = keyFile.getManualAuthURL(scope); std::cout &lt;&lt; &quot;\n\nPlease authorize this application\n&quot; &lt;&lt; &quot;Open the following URL in a browser and follow the instructions.\n&quot; &lt;&lt; &quot;Once complete copy and paste the token into the string below.\n&quot; &lt;&lt; &quot;\n&quot; &lt;&lt; &quot;Open: &quot; &lt;&lt; oauth2URL &lt;&lt; &quot;\n&quot;; // Get Temp Token: std::cout &lt;&lt; &quot;\n\nPlease input token generated by OAuth2\n&quot;; std::string token; std::getline(std::cin, token); keyFile.createCredentialFile(&quot;creds.json&quot;, token); // Now that we have downloaded the creds. // Try to open the file again. So we can attempt to load it. credStore.open(&quot;creds.json&quot;); if (!credStore) { throw std::runtime_error(&quot;Failed to open creds.json&quot;); } } // If this loads without an exception we have some credentials. TAG::OAuth2Creds oathCreds(credStore); } int main() { try { oauth2(); } catch(std::exception const&amp; e) { std::cout &lt;&lt; &quot;Error: &quot; &lt;&lt; e.what() &lt;&lt; &quot;\n&quot;; throw; } } </code></pre> <h2 id="mail.cpp-qgvk">mail.cpp</h2> <pre><code>#include &quot;GoogleMail.h&quot; #include &quot;Credentials.h&quot; #include &quot;CurlHelper.h&quot; #include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;iterator&gt; namespace TAC=ThorsAnvil::Curl; namespace TAG=ThorsAnvil::Google; namespace TAS=ThorsAnvil::Serialize; extern &quot;C&quot; size_t headerCallback(char *ptr, size_t size, size_t nmemb, void *userdata) { return size * nmemb; } extern &quot;C&quot; size_t writeCallback(char *ptr, size_t size, size_t nmemb, void *userdata) { return size * nmemb; } void mail() { using namespace std::string_literals; std::ifstream keyFileStream(&quot;KeyFile.json&quot;); // Same as the one used in auth TAG::ApplicaionInfo keyFile(keyFileStream); std::ifstream credStream(&quot;creds.json&quot;); TAG::OAuth2Creds oathCreds(credStream); oathCreds.refresh(keyFile); const std::string createDraft=&quot;https://gmail.googleapis.com/gmail/v1/users/me/drafts&quot;; TAG::Draft draft; draft.message.snippet = &quot;Test&quot;; draft.message.payload.body.data = &quot;VGhpcyBpcyBhIHRlc3QgZS1tYWls&quot;; // base64 of &quot;This is a test e-mail&quot;; std::stringstream bodyStream; bodyStream &lt;&lt; TAS::jsonExporter(draft, TAS::PrinterInterface::OutputType::Stream); std::string body(std::move(bodyStream.str())); TAC::CurlUniquePtr curl(createDraft); TAC::CurlHeaderUniquePtr headerList({&quot;Content-Type: application/json; charset=UTF-8&quot;, &quot;Authorization: &quot;s + oathCreds.token_type + &quot; &quot; + oathCreds.access_token }); curl_easy_setopt(curl, CURLOPT_POST, 1); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body.c_str()); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, body.size()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerList.get()); curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, headerCallback); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeCallback); CURLcode code = curl_easy_perform(curl); std::cerr &lt;&lt; &quot;Code: &quot; &lt;&lt; code &lt;&lt; &quot;\n&quot;; } int main() { try { mail(); } catch(char const* msg) { std::cout &lt;&lt; &quot;Error: &quot; &lt;&lt; msg &lt;&lt; &quot;\n&quot;; } } </code></pre> <h2 id="makefile-nyap">Makefile</h2> <pre><code>CXXFLAGS += -std=c++17 -I/usr/local/include CXXFLAGS += -L/usr/local/lib -lcurl -lThorSerialize17 -lThorsLogging17 </code></pre> <h2 id="building-kvoo">Building</h2> <p>ThorsSerializer and curl are needed for this code. They can both be retrieved with brew.</p> <pre><code>&gt; brew install thors_serializer &gt; brew install curl </code></pre> <p>Brew is available for <a href="https://brew.sh/" rel="nofollow noreferrer">mac</a> <a href="https://docs.brew.sh/Homebrew-on-Linux" rel="nofollow noreferrer">Linux</a> and even <a href="https://docs.brew.sh/Homebrew-on-Linux" rel="nofollow noreferrer">Windows!</a></p> <p>Then you can build with:</p> <pre><code>&gt; make auth &gt; make mail </code></pre> <p>To use. Runt <code>./auth</code> to create the credentials file (only need to do this once). Then you can run <code>./mail</code> to create a draft e-mail. I'll add sending mail later.</p>
[]
[ { "body": "<p>Spelling:</p>\n<ul>\n<li><code>ApplicaionInfo</code> -&gt; <code>ApplicationInfo</code></li>\n<li><code>uriIndix</code> -&gt; <code>uriIndex</code></li>\n</ul>\n<hr />\n<p><code>class CurlUniquePtr: public std::unique_ptr&lt;CURL, CurlDeleter&gt;</code></p>\n<p><code>class CurlHeaderUniquePtr: public std::unique_ptr&lt;curl_slist, CurlHDeleter&gt;</code></p>\n<p>A bit dodgy. We shouldn't really inherit from <code>std::unique_ptr</code> and we don't need its full interface. So we could just have a <code>std::unique_ptr</code> member variable inside the class.</p>\n<p>Alternatively we could typedef the pointer type, and write the 3 functions we need as free functions, something like:</p>\n<pre><code>using CurlUniquePtr = std::unique_ptr&lt;CURL, std::function&lt;void(CURL*)&gt;&gt;;\n\nCurlUniquePtr initCurl()\n{\n auto curl = curl_easy_init();\n\n if (!curl)\n throw std::runtime_error(&quot;curl_easy_init() failed&quot;);\n \n return { curlUniquePtr, [] (CURL* c) { return curl_easy_cleanup(c); } };\n}\n\nusing CurlSlistPtr = std::unique_ptr&lt;curl_slist, std::function&lt;void(curl_slist*)&gt;&gt;;\n\nCurlSlistPtr curlSlistInit(std::initializer_list&lt;std::string&gt; list)\n{\n auto slist = CurlSlistPtr();\n\n for (auto const&amp; s : list)\n curlSlistAppend(slist, s);\n\n return slist;\n}\n\nvoid curlSlistAppend(CurlSlistPtr&amp; slist, std::string const&amp; s)\n{\n auto added = curl_slist_append(slist.get(), s.c_str());\n\n if (!added)\n throw std::runtime_error(&quot;curl_slist_append() failed&quot;);\n \n slist.release();\n slist.reset(added);\n\n return slist;\n}\n</code></pre>\n<p>Note: We should probably check the return value of <code>curl_slist_append()</code> instead of silently failing.</p>\n<hr />\n<pre><code> // Find URL\n std::size_t uriIndix = 0;\n for (;uriIndix &lt; installed.redirect_uris.size(); ++uriIndix) {\n if (installed.redirect_uris[uriIndix].substr(0,4) == &quot;urn:&quot;) {\n break;\n }\n }\n if (uriIndix &gt;= installed.redirect_uris.size()) {\n throw std::runtime_error(&quot;Failed to find URN&quot;);\n }\n</code></pre>\n<p>Finding the URN is repeated and could be abstracted into a function. Consider using <code>std::find_if</code> instead of a plain for-loop, e.g.:</p>\n<pre><code>std::vector&lt;std::string&gt;::const_iterator findUrn(std::vector&lt;std::string&gt; const&amp; uris)\n{\n return std::find_if(uris.begin(), uris.end(),\n [] (std::string const&amp; uri) { return uri.starts_with(&quot;urn:&quot;); });\n}\n\n...\n\n auto uri = findUrn(installed.redirect_uris);\n\n if (uri == uris.end())\n throw std::runtime_error(&quot;Failed to find URI&quot;);\n</code></pre>\n<hr />\n<p><code>curl_easy_setopt(...)</code></p>\n<p>Might be worth checking the return values of all these calls (or wrapping it in a function).</p>\n<hr />\n<pre><code>extern &quot;C&quot; size_t outputToStream(char* ptr, size_t size, size_t nmemb, void* userdata)\n{\n std::iostream&amp; stream = *(reinterpret_cast&lt;std::iostream*&gt;(userdata));\n stream.write(ptr, size * nmemb);\n return size * nmemb;\n}\n</code></pre>\n<p><code>static_cast</code> should work fine here, no need to <code>reinterpret_cast</code>.</p>\n<pre><code> curl_easy_setopt(curl, CURLOPT_WRITEDATA, &amp;static_cast&lt;std::iostream&amp;&gt;(credStore));\n</code></pre>\n<p>Not really fond of the manual cast to base pointer. But I guess wrapping <code>curl_easy_setopt</code> in a type-safe layer isn't something we want to do. (Then again, we're not using that much of the library, so it might be worth it).</p>\n<p>It might be preferable to use a lambda for the write function instead of a free-function... <a href=\"https://stackoverflow.com/questions/29596948/lambda-to-curl-callback-function\">but that seems to have its own complications</a>.</p>\n<hr />\n<p>Some comments re. <code>Credentials.h</code> and <code>GoogleMail.h</code>.</p>\n<ul>\n<li><p>It might be more flexible to separate fetching the credentials from the server from writing the &quot;creds.json&quot; file (even if we can do both at once with curl).</p>\n<p>(As a side note, we should probably have more error handling here - checking that the file is open, and the writes succeeded, etc.)</p>\n</li>\n<li><p>Not fond of typedefs like <code>using Headers = std::vector&lt;Header&gt;;</code>. It obscures the type of the container.</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T15:42:20.863", "Id": "521309", "Score": "1", "body": "Spelling. The nerve of a language like English to deviate from Martin Standard form. Thanks, I missed those." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T15:42:43.843", "Id": "521310", "Score": "0", "body": "Yep should have used composition on those wrappers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T15:43:32.967", "Id": "521311", "Score": "0", "body": "Silent failure, my favorite. Fixing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T15:45:08.453", "Id": "521312", "Score": "0", "body": "Remove cut paste code. Absolutely. Fixing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T15:46:11.240", "Id": "521313", "Score": "0", "body": "Check C error codes (man I hate C for this, it makes the code so ugly)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T15:50:03.040", "Id": "521314", "Score": "0", "body": "First one I disagree with. `reinterpret_cast<>()` is the better option here. Its note that `static_cast<>()` will not work; it's that when casting from `void*` you really want people to review the cast (or where the data comes from) with a bit more attention, so you are marking for greater scrutiny by using `reinterpret_cast<>()`. This makes people pay attention and go what are you doing that you need reinterpret_cast." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T15:52:53.413", "Id": "521315", "Score": "0", "body": "Can't use `lambda` when working with C code. C libraries can technically only call functions with C linkage (in C++ you need to declare them as `extern \"C\"`). Though some people use static member functions or try and use lambdas this is only going to work if you get lucky and the calling convention used by the compiler for static and lambdas matches the ABI for C linkage functions (which on some compilers it does). But there is no guarantees. So for C libraries you should always pass C functions if you want portability." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T15:54:59.010", "Id": "521316", "Score": "0", "body": "Would love a critique of the interfaces in `Credentials.h` or suggestions on the interface for classes in `GoogleMail.h`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T20:11:51.180", "Id": "521333", "Score": "0", "body": "Added a couple of comments. I'm not familiar with OAuth or Google's API, so can't really say much." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T20:28:55.510", "Id": "521335", "Score": "0", "body": "Thanks I appreciate the time. All input is good input. If people say thinkg I don't agree with; at least it makes me sit and think about why/if I agree and come to some conclusion that I can articulate to myself. But either way, it usually means I need to write more documentation." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T10:06:57.850", "Id": "263971", "ParentId": "263969", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T07:49:10.047", "Id": "263969", "Score": "4", "Tags": [ "c++", "google-api" ], "Title": "Google API Wrapper" }
263969
<p>I am an experienced developer, but new to the react and the javascript world. I am trying to create a resizeable sidebar in react(Please see the full code and demo <a href="https://codesandbox.io/s/react-resizable-sidebar-kz9de" rel="nofollow noreferrer">here</a>) for a personal project. Although it seems to be working I am not sure if this is correct. Here is the main part of the code.</p> <p>I would like some feedback on:</p> <ol> <li>If this code is idiomatically correct? Like the use of useEffect, useState, and useRef.</li> <li>I am not sure how the <code>resizeSidebar</code> function is correctly resizing despite the asynchronous nature of <code>setSidebarWidth</code></li> </ol> <pre><code>import React from &quot;react&quot;; import { useState, useEffect, useRef } from &quot;react&quot;; import &quot;./App.css&quot;; function App() { const sidebarRef = useRef(null); const resizerRef = useRef(null); const prevX = useRef(null); const [sidebarWidth, setSidebarWidth] = useState(268); const [isTracking, setIsTracking] = useState(false); const resizeSidebar = (mouseMoveEvent) =&gt; { if (prevX &amp;&amp; prevX.current) { let delta = mouseMoveEvent.clientX - prevX.current; setSidebarWidth(sidebarRef.current.getBoundingClientRect().width + delta); prevX.current = mouseMoveEvent.clientX; } }; const stopResize = (event) =&gt; { window.removeEventListener(&quot;mousemove&quot;, resizeSidebar); window.removeEventListener(&quot;mouseup&quot;, stopResize); setIsTracking(false); }; const startResizing = (mouseDownEvent) =&gt; { prevX.current = mouseDownEvent.clientX; window.addEventListener(&quot;mousemove&quot;, resizeSidebar); window.addEventListener(&quot;mouseup&quot;, stopResize); }; useEffect(() =&gt; { if (!isTracking) prevX.current = null; }, [isTracking]); /*useEffect(() =&gt; { }, [sidebarWidth])*/ useEffect(() =&gt; { const resizer = resizerRef.current; resizer.addEventListener(&quot;mousedown&quot;, startResizing); setIsTracking(true); }, []); return ( &lt;div className=&quot;app-container&quot;&gt; &lt;div ref={sidebarRef} className=&quot;app-sidebar&quot; style={{ width: sidebarWidth }} &gt; &lt;div className=&quot;app-sidebar-content&quot;&gt;&lt;/div&gt; &lt;div ref={resizerRef} className=&quot;app-sidebar-resizer&quot;&gt;&lt;/div&gt; &lt;/div&gt; &lt;div className=&quot;app-frame&quot;&gt;&lt;/div&gt; &lt;/div&gt; ); } export default App; </code></pre> <p>Here is a link to sandbox: <a href="https://codesandbox.io/s/react-resizable-sidebar-kz9de" rel="nofollow noreferrer">https://codesandbox.io/s/react-resizable-sidebar-kz9de</a></p>
[]
[ { "body": "<p>Your questions:</p>\n<ol>\n<li>Yes, but you need to add some useCallbacks. See below</li>\n<li>AFAIK, react renders instantly when you set state (for now), but you shouldn't rely on it. For one thing, multiple setState's will be batched together if in the same click listener (and even more places in react 18). Also, with the upcoming concurrent mode we'll get partial renders which will complicate things.</li>\n</ol>\n<p>It's a bit buggy:</p>\n<ul>\n<li>Moving the mouse to the right moves the line faster than the mouse. The opposite to the left. It happens when box-sizing is set to content-box, as the getBoundingClientRect().width accounts for borders and padding, while the width you set with content-box does not. Can be fixed by explicitly setting box-sizing to border-box, or as suggested below.</li>\n<li>Sometimes I can't resize. It seems to try to drag the parent div, which disables the mousemove event. Fixed by adding an onMouseDown on the parent (app-sidebar) and e.preventDefault()</li>\n</ul>\n<p>Code issues</p>\n<ul>\n<li>useEffect has a dependency on startResizing which isn't listed. You should get an eslint warning about this.</li>\n<li>since startResizing should be used as dependency to useEffect, you must wrap it with useCallback to avoid creating a new useEffect every time.\nThe same goes for stopResize and resizeSidebar</li>\n<li>isTracking seems to not be used. You can just set prevX.current to null instead of tracking false. You can remove the useEffect as well.</li>\n<li>you can get rid of prevX entirely and calculate width with <code>setSidebarWidth(mouseMoveEvent.clientX - sidebarRef.current.getBoundingClientRect().left)</code> (this bypasses the content-box issue)</li>\n<li>You don't need the resizeRef to add the mousedown listener. Just add onMouseDown directly to the element</li>\n<li>With global listeners it's a good idea to put them into a useEffect with a cleanup function. That way you can be sure that everything is cleaned up. It would also help convince me that you don't have multiple event listeners active at the same time. Seems to work out ok in this example though.</li>\n</ul>\n<p>Nitpicks</p>\n<ul>\n<li>Delete commented code</li>\n<li>div's with no content don't need an end tag. Close them with /&gt;</li>\n<li>inside resizeSidebar you can use const for delta</li>\n</ul>\n<p>Here's some of these ideas:</p>\n<pre><code>const sidebarRef = useRef(null)\nconst [isResizing, setIsResizing] = useState(false)\nconst [sidebarWidth, setSidebarWidth] = useState(268)\n\nconst startResizing = React.useCallback((mouseDownEvent) =&gt; {\n setIsResizing(true)\n}, [])\n\nconst stopResizing = React.useCallback(() =&gt; {\n setIsResizing(false)\n}, [])\n\nconst resize = React.useCallback((mouseMoveEvent) =&gt; {\n if (isResizing) {\n setSidebarWidth(mouseMoveEvent.clientX - sidebarRef.current.getBoundingClientRect().left)\n }\n}, [isResizing])\n\nReact.useEffect(() =&gt; {\n window.addEventListener(&quot;mousemove&quot;, resize)\n window.addEventListener(&quot;mouseup&quot;, stopResizing)\n return () =&gt; {\n window.removeEventListener(&quot;mousemove&quot;, resize)\n window.removeEventListener(&quot;mouseup&quot;, stopResizing)\n }\n}, [resize, stopResizing])\n\nreturn (\n &lt;div className=&quot;app-container&quot;&gt;\n &lt;div\n ref={sidebarRef}\n className=&quot;app-sidebar&quot;\n style={{ width: sidebarWidth }}\n onMouseDown={e =&gt; e.preventDefault()}\n &gt;\n &lt;div className=&quot;app-sidebar-content&quot; /&gt;\n &lt;div\n className=&quot;app-sidebar-resizer&quot;\n onMouseDown={startResizing}\n /&gt;\n &lt;/div&gt;\n &lt;div className=&quot;app-frame&quot; /&gt;\n &lt;/div&gt;\n)\n</code></pre>\n<p>You could also replace isResizing with a ref to avoid running the effect everytime the user starts/stops resizing, but doesn't matter much.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T18:24:09.197", "Id": "264125", "ParentId": "263970", "Score": "1" } } ]
{ "AcceptedAnswerId": "264125", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T08:28:53.540", "Id": "263970", "Score": "2", "Tags": [ "javascript", "react.js" ], "Title": "React-based resizable sidebar" }
263970
<p>I have been trying to optimize this:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const NUMBERS = [2, 2, 2, 2, 2, 4, 5, 5, 5, 5, 5, 5, 5, 5, 9]; const getMode = (arr) =&gt; arr .sort( (a, b) =&gt; arr.reduce((acu, cur) =&gt; (cur === a ? (acu += 1) : cur)) - arr.reduce((acu, cur) =&gt; (cur === b ? (acu += 1) : cur)) ) .pop(); console.log(getMode(NUMBERS));</code></pre> </div> </div> </p> <p>I had thought about this too:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const NUMBERS = [2, 2, 2, 2, 2, 4, 5, 5, 5, 5, 5, 5, 5, 5, 9]; const mode = (arr) =&gt; arr .sort( (a, b) =&gt; arr.filter((v) =&gt; v === a).length - arr.filter((v) =&gt; v === b).length ) .pop(); console.log(mode(NUMBERS))</code></pre> </div> </div> </p> <p>What do you think can be improved?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T13:37:28.040", "Id": "521298", "Score": "1", "body": "To clarify, what do you mean by “mode”? The statistical zero-th moment of a distribution?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T13:39:10.523", "Id": "521299", "Score": "0", "body": "The element that is repeated the most in the array" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T14:16:22.313", "Id": "521301", "Score": "1", "body": "You've said \"trying to optimize\". Did you profile the code? What did you get? Anyway, it should be clear that sorting to get the maximum is a bad idea." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T09:18:06.443", "Id": "521352", "Score": "0", "body": "Do you want to improve speed or memory usage?" } ]
[ { "body": "<p>In order to improve the performance, you can reduce the complexity of the code.</p>\n<p>Currently, the complexity of your approaches is <strong>O(n² log(n))</strong> as the <code>sort</code> function is <strong>O(n log(n))</strong> and in each iteration, you are using <code>filter</code> or <code>reduce</code> which has a complexity of <strong>O(n)</strong>.</p>\n<p>I can suggest one approach where you don't need to sort the elements and so the complexity of the method will be <strong>O(n)</strong> if using <a href=\"https://v8.dev/\" rel=\"nofollow noreferrer\">V8</a> JavaScript Engine (<a href=\"https://stackoverflow.com/questions/33611509/es6-map-and-set-complexity-v8-implementation\">for more information</a>) otherwise <strong>O(n log(n))</strong>. Check out this approach:</p>\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 NUMBERS = [2, 2, 2, 2, 2, 4, 5, 5, 5, 5, 5, 5, 5, 5, 9];\n\nconst getMode = (arr) =&gt; {\n\n let [maxFreq, result] = [-1, -1];\n \n arr.reduce((acu, cur) =&gt; {\n acu.set(cur, (acu.has(cur) ? acu.get(cur) : 0)+1)\n return acu;\n }, new Map())\n .forEach((value, key) =&gt; {\n if(value &gt; maxFreq){\n maxFreq = value;\n result = key;\n }\n });\n \n return result;\n \n }\n\nconsole.log(getMode(NUMBERS))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T14:22:47.630", "Id": "521303", "Score": "0", "body": "Yeah... @PavloSlavynskyy... thanks for correcting!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T15:02:47.520", "Id": "521306", "Score": "2", "body": "@PavloSlavynskyy according to this (https://stackoverflow.com/questions/33611509/es6-map-and-set-complexity-v8-implementation) discussion in V8 JavaScript Engine the time complexity of retrieval and lookup is O(1)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T14:12:18.420", "Id": "263979", "ParentId": "263975", "Score": "2" } }, { "body": "<p>I have modified the answer of the HandsomeCoder.</p>\n<p>This is actually O(n) because object access is O(1)</p>\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 NUMBERS = [2, 2, 2, 2, 2, 4, 5, 5, 5, 5, 5, 5, 5, 5, 9];\n\nfunction getMode(array) {\n function buildFrequencyMap(array) {\n return array.reduce((acu, number) =&gt; {\n acu[number] = acu[number] !== undefined ? acu[number] + 1 : 0\n return acu;\n }, {})\n }\n\n function maxFrequency(frequencyMap) {\n let maxFreq = -1, result = -1\n\n Object.entries(frequencyMap).forEach(([key, value]) =&gt; {\n if(value &gt; maxFreq){\n maxFreq = value;\n result = key;\n }\n });\n\n return result\n }\n\n const frequencyMap = buildFrequencyMap(array)\n\n return maxFrequency(frequencyMap);\n}\n\nconsole.log(getMode(NUMBERS))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T14:33:28.020", "Id": "263981", "ParentId": "263975", "Score": "0" } }, { "body": "<h2>Sort!</h2>\n<p>Never use a sort to get a max or min. Sort is only used to order all items in the array.</p>\n<p>If you want a max in an array you can use <code>Math.max(...[1,2,3,4,5,6,5,4,3,2])</code> expresses 6.</p>\n<p>If you need an associated value linked to a max or min you will need to iterate manually storing the max and associated data as and when you find new values.</p>\n<h2>Rewrite</h2>\n<p>The example tests the count of values against a max <code>max</code> and store both the max count and the value <code>maxVal</code> of the counted value</p>\n<p>To count values it uses a map which uses a hash map and is <span class=\"math-container\">\\$O(1)\\$</span> for lookups which will make the function <span class=\"math-container\">\\$O(n)\\$</span></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function getMode(data) {\n var max = -Infinity, maxVal, counts = new Map(), c;\n for (const v of data) {\n c = ++(counts.get(v) ?? (counts.set(v, c = {count: 0}), c)).count;\n [max, maxVal] = c &gt; max ? [c, v] : [max, maxVal];\n }\n return maxVal;\n}\n\nconsole.log(getMode([2, 2, 2, 2, 2, 4, 5, 5, 5, 5, 5, 5, 5, 5, 9]))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>You could also check if max is greater than (n / 2) and exit as if the count is over half the items the value must be the most frequent.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T15:31:16.010", "Id": "263985", "ParentId": "263975", "Score": "1" } } ]
{ "AcceptedAnswerId": "263979", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T13:34:57.873", "Id": "263975", "Score": "0", "Tags": [ "javascript", "comparative-review", "mathematics" ], "Title": "Get the Most frequent element in an array" }
263975
<p>I have a simple SDK in Python for internal use. It's basically 150~200 lines of code of simple API calls wrapped around nicely that is comfortable for us to use.</p> <p>It holds a few clients with methods (and each method wraps some API calls).</p> <p>So a proper usage would be:</p> <pre><code>from datatube.datatube import Datatube client = Datatube() client.do_stuff(...) </code></pre> <p>Currently it expects 3 environment variables - two for authentication purposes (these are the secret ones) and one for the environment (dev/stg/prod). I want to change the environment variable to be passed on as an argument (seems better). So:</p> <pre><code>from datatube.datatube import Datatube client = Datatube('stg') client.do_stuff(...) </code></pre> <p>Inside <code>Datatube</code> I'll take the correct config based on the environment. Currently I have:</p> <pre><code>class BaseConfig: pass class DevelopmentConfig(BaseConfig): DATATUBE_URL = 'https://..' class StagingConfig(BaseConfig): DATATUBE_URL = 'https://..' class ProductionConfig(BaseConfig): DATATUBE_URL = 'https://..' def get_config(env: str): env = env.lower() if env == 'dev': return DevelopmentConfig() if env == 'stg': return StagingConfig() elif env == 'prod': return ProductionConfig() else: raise KeyError(f&quot;unsupported env: {env}. supported environments: dev/stg/prod&quot;) </code></pre> <p>If I'll use type annotation on <code>get_config</code> like:</p> <p><code>def get_config(env: str) -&gt; BaseConfig</code></p> <p>Then the IDE won't like it (I guess because <code>BaseConfig</code> is empty, but I don't know how to do it nicely - isn't an abstract class kind of an overkill?)</p> <p>Any recommendations would be helpful.</p> <p>Using Python 3.9</p>
[]
[ { "body": "<p>Class inheritance is overkill here. Just use dataclass instances:</p>\n<pre><code>from dataclasses import dataclass\n\n\n@dataclass\nclass Config:\n DATATUBE_URL: str\n\n\nENVIRONMENTS = {\n 'dev': Config(\n DATATUBE_URL='https://..',\n ),\n 'stg': Config(\n DATATUBE_URL='https://..',\n ),\n 'prd': Config(\n DATATUBE_URL='https://..',\n ),\n}\n\n\ndef get_config(env_name: str) -&gt; Config:\n env = ENVIRONMENTS.get(env_name.lower())\n if env is None:\n raise KeyError(\n f&quot;unsupported env: {env_name}. supported environments: &quot; +\n ', '.join(ENVIRONMENTS.keys()))\n return env\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T18:27:51.110", "Id": "263989", "ParentId": "263982", "Score": "3" } } ]
{ "AcceptedAnswerId": "263989", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T14:44:30.443", "Id": "263982", "Score": "0", "Tags": [ "python", "python-3.x", "configuration" ], "Title": "Config for each environment (for a simple Python SDK)" }
263982
<p>I started with this script which is written in boto2 which I want to migrate to boto3, Below is a potion of the script that is used to automatically publish to S3 in my pipeline.</p> <pre><code>def upload_file(self, details, ttl='259200'): startTime = datetime.now() initialHash = details[:2] if initialHash == &quot;zz&quot;: initialHash = &quot;ad&quot; local_file = os.path.join(overrideStorePath, &quot;files&quot;, initialHash, details[2:]) k = boto.s3.key.Key(self.bucket) k.key = self.prefix + remoteStorePath + '/' + details[:2] + '/' + details[2:] k.set_metadata('Cache-Control', 'max-age=' + ttl) k.set_contents_from_filename(local_file) i = self.uploadTrack[&quot;i&quot;] + 1 self.uploadTrack[&quot;i&quot;] += 1 total = self.uploadTrack[&quot;total&quot;] p = int(100 * i / total) self.myprint(&quot;Uploaded '{}' : {} of {} : {}% in {} : {} kb&quot;.format(k.name, str(i), str(total), str(p), str(datetime.now() - startTime), str(os.path.getsize(local_file) / 1024))) return True </code></pre> <p>I want to replicate this upload using boto3, So far I have this</p> <pre><code>session = boto3.Session( aws_access_key_id= &quot;%ACCESS_KEY%&quot;, aws_secret_access_key= &quot;%SECRET_KEY%&quot; ) self.s3conn2 = session.resource(&quot;s3&quot;) self.bucket2 = self.s3conn2.bucket('%aws_bucket%') def upload_file(self, details, ttl='259200'): startTime = datetime.now() initialHash = details[:2] if initialHash == &quot;zz&quot;: initialHash = &quot;ad&quot; local_file = os.path.join(overrideStorePath, &quot;files&quot;, initialHash, details[2:]) k = session.resource('s3') key = self.prefix + remoteStorePath + '/' + details[:2] + '/' + details[2:] k.put(Metadata={'Cache-Control', 'max-age=' + ttl}) k.Bucket(self.bucket).upload_file(local_file, key) i = self.uploadTrack[&quot;i&quot;] + 1 self.uploadTrack[&quot;i&quot;] += 1 total = self.uploadTrack[&quot;total&quot;] p = int(100 * i / total) self.myprint(&quot;Uploaded '{}' : {} of {} : {}% in {} : {} kb&quot;.format(k.name, str(i), str(total), str(p), str(datetime.now() - startTime), str(os.path.getsize(local_file) / 1024))) return True </code></pre> <p>Is this the correct way of using s3 upload, metadata and keys with boto3? I want to make sure as the docs are quite vague on this subject. Thanks :)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T18:45:13.847", "Id": "521328", "Score": "1", "body": "Welcome to CodeReview! Please format you code properly (e.g. indentation after `def method:`). Readability will be first aspect in most reviews ️" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T20:45:07.293", "Id": "521336", "Score": "0", "body": "I took a guess at what you actually want your indentation to be." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T13:26:17.077", "Id": "521365", "Score": "0", "body": "You've... reverted the indentation back to a version that will not interpret in Python. If you copy and paste this into an interpreter, what happens? Code that doesn't run is off-topic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T13:27:23.770", "Id": "521366", "Score": "0", "body": "Adding to this: you've included what's almost certainly a method without showing the whole class. This is insufficient review context." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T01:47:10.950", "Id": "521413", "Score": "0", "body": "Are you using Python 3?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T15:11:18.443", "Id": "263983", "Score": "0", "Tags": [ "python", "amazon-web-services" ], "Title": "Uploading multiple S3 Objects with metadata and keys with Boto3" }
263983
<p>I have an application that subscribes to a topic in GCP and when there is some messages over there it downloads them and sends them to a queue on ActiveMQ.</p> <p>In order to make this process fast I am using exeutorService and launching multiple threads for sending messages to active mq. since that the subscription is supposed to be an ongoing task Iam putting the code in a while(true) loop.</p> <p>I am searching for an elegant way to shutdown the executorService when the subscription is empty (no data in the topic) for like 2 or 3 minutes. and then of course it starts again when there is some new data.</p> <p>the following will be my idea which I don't like. Iam looking for a more elegant way of doing that.</p> <pre><code> @Service @Slf4j public class PubSubSubscriberService { private static final int EMPTY_SUBSCRIPTION_COUNTER = 4; private static final Logger businessLogger = LoggerFactory.getLogger(&quot;BusinessLogger&quot;); private Queue&lt;PubsubMessage&gt; messages = new ConcurrentLinkedQueue&lt;&gt;(); public void pullMessagesAndSendToBroker(CompositeConfigurationElement cce) { var patchSize = cce.getSubscriber().getPatchSize(); var nThreads = cce.getSubscriber().getSendingParallelThreads(); var scheduledTasks = 0; var subscribeCounter = 0; ThreadPoolExecutor threadPoolExecutor = null; while (true) { try { if (subscribeCounter &lt; EMPTY_SUBSCRIPTION_COUNTER) { log.info(&quot;Creating Executor Service for uploading to broker with a thread pool of Size: &quot; + nThreads); threadPoolExecutor = getThreadPoolExecutor(nThreads); } var subscriber = this.getSubscriber(cce); this.startSubscriber(subscriber, cce); this.checkActivity(threadPoolExecutor, subscribeCounter++); // send patches of {{ messagesPerIteration }} while (this.messages.size() &gt; patchSize) { if (poolIsReady(threadPoolExecutor, nThreads)) { UploadTask task = new UploadTask(this.messages, cce, cf, patchSize); threadPoolExecutor.submit(task); scheduledTasks ++; } subscribeCounter = 0; } // send the rest if (this.messages.size() &gt; 0) { UploadTask task = new UploadTask(this.messages, cce, cf, patchSize); threadPoolExecutor.submit(task); scheduledTasks ++; subscribeCounter = 0; } if (scheduledTasks &gt; 0) { businessLogger.info(&quot;Scheduled &quot; + scheduledTasks + &quot; upload tasks of size upto: &quot; + patchSize + &quot;, preparing to start subscribing for 30 more sec&quot;) ; scheduledTasks = 0; } } catch ( Exception e) { e.printStackTrace(); businessLogger.error(e.getMessage()); } } } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T15:14:17.413", "Id": "263984", "Score": "2", "Tags": [ "java", "multithreading", "spring" ], "Title": "How to check gcp pupsub empty/inactitve subscribtion" }
263984
<p>I am working on a basic Array rotate code for a Hacker Rank challenge. The code is complete and passes all test cases, except for 2 which it times out on. I was wondering if there is a way to make this code more efficient. Thank you in advance.</p> <pre><code>class Result { /* * Complete the 'rotLeft' function below. * * The function is expected to return an INTEGER_ARRAY. * The function accepts following parameters: * 1. INTEGER_ARRAY a - List Array * 2. INTEGER d - Number of times to be retated */ public static List&lt;Integer&gt; rotLeft(List&lt;Integer&gt; a, int d) { // Write your code here int lowestVal; int size = a.size()-1; for (int x = 0; x &lt; d; x++) { lowestVal = a.get(0); for (int i = 0; i &lt; size; i++) { a.set(i, a.get(i+1)); } a.set(size, lowestVal); } return a; } </code></pre> <p>}</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T20:27:57.440", "Id": "521334", "Score": "0", "body": "From the comments in the code, your function should returns an array and I, but instead your code is using lists as parameter and return value. Are the comments wrong ? Please include in your question a link to the challenge and a description of it." } ]
[ { "body": "<p>Is it a list or an array you are to work with? They are not exactly equivalent. If the data is an array, you can perhaps use System.arrayCopy() in your solution.</p>\n<p>Do you have to rotate in place or can the result be a new array (or list)?</p>\n<p>If you are rotating more than one place, you should be able to do so in one go, rather than multiple single-place rotations, which will improve performance significantly.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T20:43:37.320", "Id": "263992", "ParentId": "263990", "Score": "0" } }, { "body": "<p>You should not need to do this yourself. Consider</p>\n<pre><code>d %= a.size();\nif (d == 0) {\n return a;\n}\n\nList&lt;Integer&gt; results = new ArrayList&lt;&gt;();\nresults.addAll(a.subList(d, a.size()));\nresults.addAll(a.subList(0, d));\n\nreturn results;\n</code></pre>\n<p>If <code>d</code> is initially 0, it will rotate in constant time. This is the same as your function.</p>\n<p>If <code>d</code> becomes 0 (when <code>d</code> is a multiple of <code>a.size()</code>), it will still rotate in constant time. Whereas your function will rotate <code>d</code> times to get back the original list.</p>\n<p>If <code>d</code> is 1, this will copy each element of the list once. This is the same as your function.</p>\n<p>If <code>d</code> is greater than 1 and not evenly divisible by <code>a.size()</code>, this will copy each element of the list once. Whereas your function will copy each element <code>d</code> times. So <code>d * a.size()</code> copies. This is a particularly large improvement when <code>d</code> is greater than <code>a.size()</code>.</p>\n<p>Behind the scenes, this does the same work as one of your <code>for</code> loops. But you don't have to operate it manually. And you don't have to nest with another <code>for</code> loop.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T00:59:05.643", "Id": "521340", "Score": "0", "body": "Thank you this was very helpful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T09:10:11.737", "Id": "521351", "Score": "1", "body": "Careful, this solution modifies the original list. `subList` returns a view and not a copy. Better would be: `List<Integer> results = new ArrayList<>(a.subList(d, a.size()));`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T00:51:44.283", "Id": "263997", "ParentId": "263990", "Score": "1" } }, { "body": "<p>The term &quot;list array&quot; is inapproriate (it's generally understood to mean an array of lists).</p>\n<p>What you're doing is rotating left (by a distance of 1) d times, while it would be more elegant (and efficient) to rotate left (by a distance of d) just 1 time.\nAlso, in the process you're changing your input (parameter a). That's not always evil, but it is in your case since the lack of mentioning that (in the documentation of the function) makes callers not expect that.</p>\n<p>Here's an nicer version using high-level calls only:</p>\n<pre><code>public static List&lt;Integer&gt; rotLeft(List&lt;Integer&gt; a, int d) {\n d %= a.size();\n if (d &lt; 0) d += a.size();\n List&lt;Integer&gt; newPrefix = a.subList(d, a.size());\n List&lt;Integer&gt; newPostfix = a.subList(0, d);\n List&lt;Integer&gt; result = new ArrayList&lt;&gt;(a.size());\n result.addAll(newPrefix);\n result.addAll(newPostfix);\n return result;\n}\n</code></pre>\n<p>If creating newPrefix and newPostfix seems inefficient: there're just views so don't worry about that.</p>\n<p>PS: returning <code>a</code> itself (rather than a copy) if <code>d==0</code> may seem like a good idea, but it is inadvisable unless you're in complete control of your callers. If there are external callers they'd be able to mess up your original list at any time.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T12:17:31.033", "Id": "264007", "ParentId": "263990", "Score": "0" } } ]
{ "AcceptedAnswerId": "263997", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T18:28:31.770", "Id": "263990", "Score": "1", "Tags": [ "java", "performance", "array" ], "Title": "HackRank - Array Rotate Optimization" }
263990
<p>I am processing a file as the following and closing it. Later, I do some more processing and get some ID that I want to append to all rows in the previous CSV generated. So all rows will have the same value.</p> <p>My initial code of creating and appending data to csv:</p> <pre><code> private StringBuilder stringBuilder = new StringBuilder(); public void writeToFile(String[] tIds, PrintWriter printWriter) throws DataNotFoundException { int rowCount = 0; for(String id: tIds) { Data data = util.getData(id); csvHelper.prepareFileData(data, this.stringBuilder); rowCount++; if (rowCount == CHUNK_SIZE) { printWriter.println(this.stringBuilder.toString()); this.stringBuilder = new StringBuilder(); rowCount = 0; } } printWriter.close(); } </code></pre> <p>Now further processing returns me some <code>processedID</code> that I want to append to all rows as a new column.</p> <p>One option is this:</p> <pre><code>public void appendAgain(String processedId) { BufferedReader br = new BufferedReader(new FileReader(feedFile)); String output = &quot;&quot;; String line; while ((line = br.readLine()) != null) { output += line.replace(&quot;,&quot;, &quot;,&quot; + alertId + &quot;,&quot;); } FileWriter fw = new FileWriter(feedFile, false); //false to replace file contents, your code has true for append to file contents fw.write(output); fw.flush(); fw.close(); } public void prepareFileForData(Data data, StringBuilder sb) { // map values from data to sb sb.append(data.getId()); sb.append(&quot;,&quot;); sb.append(data.getName()); .. and so on } </code></pre> <p>Please comment on a better way or any suggestions on the current one. Thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T09:24:07.603", "Id": "521354", "Score": "2", "body": "You'll need to explain better what this \"processing\" is. Also the code doesn't make sense without context: What does `prepareFileData` do? While is `stringBuilder` a field?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T19:12:15.880", "Id": "521399", "Score": "0", "body": "@RoToRa Updated and added" } ]
[ { "body": "<p>Your first code snippet seems to use <code>prepareFileData</code> to inject string-encoded rows into a String-buffer. Every <code>CHUNK_SIZE</code> rows, the buffer is appended to a file and the buffer is then reset.\nThat makes some sense, but:</p>\n<ol>\n<li>If the number of rows is not a multiple of <code>CHUNK_SIZE</code>, some rows will be not be written and hence lost.</li>\n<li>Mixing abstraction levels (here: dealing with CSV vs. buffering) in a single procedure is almost never a good idea. Consider using something like <code>BufferedOutputStream</code> to delegate the buffering aspect.</li>\n</ol>\n<p>Your second code snippet is confusing. It seems to work at first glance (the extraneous comma is a bit strange though), but your first snippet seemed very concerned with memory footprint. The second snippet however just collects all data in one String, suggesting that memory isn't an issue at all.</p>\n<p>My recommendation: take a step back and spend some time on considering what it is that you care about (apart from correctness): is it memory, is it speed, is it thread-safeness, is it readability, is it any combination of the former (including none)?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T12:34:07.577", "Id": "264208", "ParentId": "263994", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T22:22:16.463", "Id": "263994", "Score": "-2", "Tags": [ "java", "csv" ], "Title": "Java: Is there an easy way to append a new column that will be having same value for all rows in csv?" }
263994
<p>I was rejected after a tech screening for the following code. I mainly struggled to make the code 'production ready'. I was running out of time so I did not create a class for testing. How could I have improved this code?</p> <pre><code>/* Problem Imagine you are building a friend locator app. Given your current position identified on a bidimensional plane as (0,0) and a list of friend locations, each identified by a (x,y) pair, return the k closest friends to your current location. For simplicity, you can compute the distance between you and your friends using the Euclidean distance formula ( d = sqrt(x^2 +y^2) ). Given a list of friend locations [[1,3], [-2,2]], K = 1 Output: [[-2,2]] */ import java.io.*; import java.util.*; /* * To execute Java, please define &quot;static void main&quot; on a class * named Solution. * * If you need more classes, simply define them inline. */ class Solution { static class Pair{ int x, y; Pair(int x, int y){ this.x = x; this.y = y; } } /* d -&gt; cords time - O(n) space - O(n) */ public static List&lt;Pair&gt; closestFriends(List&lt;Pair&gt; list, int k){ SortedMap&lt;Double, Pair&gt; map = new TreeMap&lt;&gt;(); List&lt;Pair&gt; results = new ArrayList&lt;Pair&gt;(); int i =0; for(Pair pair : list){ double d = distance(pair); map.put(d, pair); } for(Map.Entry&lt;Double, Pair&gt; entry : map.entrySet()){ if(i &lt; k){ results.add(entry.getValue()); i++; } } return results; } public static double distance(Pair p){ return Math.sqrt(p.x*p.x + p.y*p.y); } public static void main(String[] args) { ArrayList&lt;Pair&gt; cords = new ArrayList&lt;&gt;(); cords.add(new Pair(1,3)); cords.add(new Pair(-2,2)); cords.add(new Pair(0,10)); cords.add(new Pair(-2,2)); cords.add(new Pair(1,3)); cords.add(new Pair(-2,2)); int k =1; /* empty list of cords negative k list list of cords test cases for distance - correct calculation */ List&lt;Pair&gt; res = closestFriends(cords, k); for(int i =0; i &lt; res.size(); i++){ System.out.println(res.get(i).x + &quot;,&quot; +res.get(i).y); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T23:18:35.017", "Id": "521339", "Score": "1", "body": "`class Solution {` is something I'd expect to see in a programming-challenge, not in production code. Was this provided by the company?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T09:20:01.427", "Id": "521353", "Score": "2", "body": "Why not use streams? It's a one-liner with streams... `return cords.stream().sorted(Comparator.comparingDouble(p -> Math.hypot(p.x, p.y))).limit(k).collect(Collectors.toList())`." } ]
[ { "body": "<h2 id=\"major-issue-misunderstanding-of-exercise\">major issue: misunderstanding of exercise</h2>\n<p>you should find the <strong>amount k</strong> of friends - not the friends within an distanz k</p>\n<h2 id=\"major-issue-bug\">major issue: bug</h2>\n<pre><code>for(Pair pair : list){\n double d = distance(pair);\n map.put(d, pair);\n}\n</code></pre>\n<p>if two &quot;pair&quot;s have the same distance you'll lose one result</p>\n<h2 id=\"major-issue-naming\">major issue: naming</h2>\n<p>sounds obvious but you should create a <code>Position</code> not a <code>Pair</code> (also named in your exercise as <code>Location</code> - but never a <code>Pair</code>)</p>\n<h2 id=\"minor-issue-map-instead-of-a-list-mostly-assumption-on-this\">minor issue: <code>Map</code> instead of a <code>List</code> (mostly assumption on this)</h2>\n<p>your exercise wants you to return a the first k items of a sorted list. I had expected you to use a <code>List</code> and create a <code>Comparator</code>, sort the list and then return the k first entries. you use a map to sort the element. and it's a buggy (see above) algorithm to sort.</p>\n<h2 id=\"minor-issue-java-coding-conventions-not-considering-encapsulation\">minor issue: Java coding conventions, not considering encapsulation</h2>\n<p>as example I say that <code>int x, y;</code> should be:</p>\n<pre><code>int x;\nint y;\n</code></pre>\n<p>and formatting, use the spaces properly</p>\n<h2 id=\"minor-issue-naming\">minor issue: naming</h2>\n<ul>\n<li>when they give you the <code>amount k</code> you could pick up and rename that variable into a proper name</li>\n<li>when they give you a <strong>list of friends</strong> that you should filter rename that list properly</li>\n</ul>\n<p><code>public static List&lt;Pair&gt; closestFriends(List&lt;Pair&gt; friends, int amount)...</code></p>\n<p>another one here: I'm missing a proper <em>verb</em> in your method name: <code>getClosestFriends()</code> or maybe <code>findClosestLocations()</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T05:52:32.870", "Id": "521346", "Score": "3", "body": "Another major issue is naming number 3: `List<Pair> list` - I'd already kick the OP out of my office for that. Yes, we see from the data type that the variable is a list, there's no need to repeat this information in the variable name. But what does it contain, what does it signify? No indication." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T05:57:37.217", "Id": "521348", "Score": "1", "body": "yes, yes, very obvious, my bad i didnt see it! `List<Pair> list` should be named properly: `List<Pair> candidates` or `fiends` or similar (still `Pair` is improper)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T06:24:12.273", "Id": "521349", "Score": "0", "body": "@mtj i will add that point to the review" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T09:58:41.357", "Id": "521356", "Score": "6", "body": "I don't get why you're saying the first major issue is that he misunderstood the exercise. Best I can tell, he did in fact find the K closest friends." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T10:50:49.373", "Id": "521357", "Score": "1", "body": "@MartinFrank tbh, in logner code the Data type in the declaration can be far away. My lists are named candidatesList (or similar), just to be on the very same side. Also makes it obvious at a glance whether that one line is referencing candidateS oder a candidate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T11:18:31.743", "Id": "521360", "Score": "1", "body": "@Hobbamok whyen you use the Type as a variablen Name, this is called HungarianNotation. Things get bad when you change the type: then you have to rename the variablen name as well! (see https://en.wikipedia.org/wiki/Hungarian_notation) and why this is always a point of discussion: https://softwareengineering.stackexchange.com/questions/102689/what-is-the-benefit-of-not-using-hungarian-notation)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T05:26:10.203", "Id": "264001", "ParentId": "263995", "Score": "10" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T22:49:06.677", "Id": "263995", "Score": "6", "Tags": [ "java", "sorting", "interview-questions", "hash-map" ], "Title": "friend locator app" }
263995
<p>I'm looking at improving my PHP knowledge and wondering if anybody has any tips on improving and optimising my function below?</p> <pre><code>&lt;?php function urlCheck($string = '') { $searches = array('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen'); $serverUrl = $_SERVER['REQUEST_URI']; $getContents = file_get_contents('php://input'); $queryJoin = $serverUrl . $getContents; foreach ($searches as $search) { if (strpos(strtolower(urldecode($queryJoin)), strtolower($search)) !== false) { return true; } } return false; } print_r(urlCheck()); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T13:18:40.503", "Id": "521362", "Score": "3", "body": "I'm not convinced that I have enough context here. How about some sample input? Do you need word boundaries to ensure that you are matching a whole word? Is this hypothetical code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T17:48:52.130", "Id": "521475", "Score": "0", "body": "For clarity `$getContents = file_get_contents('php://input');` is only aiming to get query string variables, right? or is it intended to include POST data also?" } ]
[ { "body": "<p>If you replace</p>\n<blockquote>\n<pre><code> $queryJoin = $serverUrl . $getContents;\n</code></pre>\n</blockquote>\n<p>with</p>\n<pre><code> $queryJoin = strtolower(urldecode($serverUrl . $getContents));\n</code></pre>\n<p>You can change</p>\n<blockquote>\n<pre><code> if (strpos(strtolower(urldecode($queryJoin)), strtolower($search)) !== false) {\n</code></pre>\n</blockquote>\n<p>to</p>\n<pre><code> if (strpos($queryJoin, strtolower($search)) !== false) {\n</code></pre>\n<p>and save a <code>strtolower</code> call and <code>urldecode</code> call for every iteration.</p>\n<p>For that matter, if the keys are constants, as they are here, you could simply drop the <code>strtolower</code> on <code>$searches</code> as well. Just make sure that the values are lower case.</p>\n<p>Alternatively, consider making a check class.</p>\n<pre><code>class URL_Checker {\n\n protected $searches;\n\n public function __construct($searches) {\n $this-&gt;searches = array_map('strtolower', $searches);\n }\n\n public function check($string) {\n $haystack = strtolower(urldecode($string));\n foreach ($this-&gt;searches as $search) {\n if (false !== strpos($haystack, $search)) {\n return true;\n }\n }\n\n return false;\n }\n\n}\n</code></pre>\n<p>That would work better if you are calling the function multiple times for the same search keys.</p>\n<p>Just as a matter of good style, it would be better to separate loading the data from checking it. This class would be reusable for any data string. Or you could load the body of the request once and reuse it multiple times. Your original form would allow neither input nor processing reuse.</p>\n<p>It's possible that replacing the <code>foreach</code> with an <code>array_reduce</code> might be more efficient on average. You'd have to run metrics. It would tend to improve the worst case at the cost of the best case; that might be a useful tradeoff regardless. The worst case being when the search keys do not appear so you have to check all of them.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T13:00:28.640", "Id": "264009", "ParentId": "263996", "Score": "3" } }, { "body": "<p>Unless the request has an encoding issue, <a href=\"https://www.php.net/manual/en/reserved.variables.server.php\" rel=\"nofollow noreferrer\"><code>$_SERVER['QUERY_STRING']</code></a> could likely be used when assigning <code>$getContents</code> instead of reading from the raw input (I.e. <code>file_get_contents('php://input')</code>).</p>\n<p>If you want to optimize for readability then consider generating the values in the array <code>$searches</code> using PHP's built-in <a href=\"https://www.php.net/manual/en/class.numberformatter.php\" rel=\"nofollow noreferrer\">number formatter</a> with the formatter <a href=\"https://www.php.net/manual/en/class.numberformatter.php#numberformatter.constants.spellout\" rel=\"nofollow noreferrer\"><code>NumberFormatter::SPELLOUT</code></a>. The <a href=\"https://php.net/range\" rel=\"nofollow noreferrer\"><code>range()</code></a> function can also be used to create the array from 1 to 13. Then if the list of numbers needs to change you can easily modify the parameters to that function.</p>\n<pre><code>$nf = new NumberFormatter('en_US', NumberFormatter::SPELLOUT);\nforeach(range(1, 13) as $i) {\n $search = $nf-&gt;format($i);\n //look for $search in $queryJoin\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T16:14:07.840", "Id": "264020", "ParentId": "263996", "Score": "0" } } ]
{ "AcceptedAnswerId": "264009", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T23:41:42.550", "Id": "263996", "Score": "1", "Tags": [ "performance", "php", "strings", "array" ], "Title": "Check URL for keywords" }
263996
<p>Here is a minimal example of my task...</p> <p>I have four 2-column files. <code>profile1.data</code></p> <pre><code> zone luminosity 1 1 1359.019 2 2 1359.030 3 3 1359.009 4 4 1358.988 5 5 1358.969 6 6 1358.951 7 7 1358.934 8 8 1358.917 9 9 1358.899 10 10 1358.881 </code></pre> <p><code>profile2.data</code></p> <pre><code> zone luminosity 1 1 1357.336 2 2 1357.352 3 3 1357.332 4 4 1357.310 5 5 1357.289 6 6 1357.270 7 7 1357.252 8 8 1357.233 9 9 1357.214 10 10 1357.194 </code></pre> <p><code>profile3.data</code></p> <pre><code> zone luminosity 1 1 1355.667 2 2 1355.687 3 3 1355.667 4 4 1355.644 5 5 1355.622 6 6 1355.602 7 7 1355.582 8 8 1355.562 9 9 1355.541 10 10 1355.520 </code></pre> <p><code>profile4.data</code></p> <pre><code> zone luminosity 1 1 1354.008 2 2 1354.032 3 3 1354.013 4 4 1353.990 5 5 1353.967 6 6 1353.945 7 7 1353.923 8 8 1353.902 9 9 1353.879 10 10 1353.857 </code></pre> <p>I also have a vector named <code>phases</code>. There is one <code>phase</code> value for each <code>profile.data</code></p> <pre><code> rsp_phase1 rsp_phase2 rsp_phase3 rsp_phase4 0.002935897 0.004602563 0.006269230 0.007935897 </code></pre> <p>Finally, there are profile files for one of FOUR sets labeled A to D. The set directories are named <code>LOGS_A1a</code>, <code>LOGS_B1a</code>, etc. and contains the profile files, a file named <code>history.data</code> which contains <code>phase</code> values, and a <code>profile.index</code> file that states how many profiles there are in the directory. The sets do NOT have the same number of profiles.</p> <p>What I am doing with this data is plotting luminosity vs phase for each zone, and putting one each of the four plots for each set on one canvas altogether.</p> <p><a href="https://i.stack.imgur.com/grx8P.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/grx8P.png" alt="Example of plot with a subplot for each set" /></a></p> <p>For example, to create a luminosity vs phase plot of the first zone, I grab the luminosity value from every profile in the directory at zone 1. This is my first plot. Then I do the same for the other zones. At the moment, I am accomplishing this through for loops in R.</p> <pre><code>for (zone_num in 1:10){ png(file.path(paste(&quot;Light_Curve_&quot;,&quot;Zone_&quot;,zone_num,&quot;.png&quot;,sep=&quot;&quot;)), width = 1200, height = 960) par(mar=c(5,4,4,2) + 2) luminosities &lt;- c() for (prof_num in 1:4) { prof.path &lt;- file.path('LOGS_A1a', paste0('profile', prof_num, '.data')) if (!file.exists(prof.path)) next #print(prof.path) DF.profile &lt;- read.table(prof.path, header=1, skip=5) luminosity &lt;- DF.profile$luminosity[zone_num] luminosities &lt;- c(luminosities, luminosity) } plot.table &lt;- data.frame(phases, luminosities) o &lt;- order(phases) with(plot.table, plot(x=phases[o], y=luminosities[o], main=paste(&quot;Zone&quot;,zone_num,&quot;Light Curve&quot;,sep=&quot; &quot;), type=&quot;l&quot;, pch=3, lwd = 6, col=&quot;purple&quot;, xlab=expression(&quot;Phase&quot;), ylab=expression(&quot;Luminosity &quot; (L/L['\u0298'])), cex.main=1.60, cex.lab=1.80, cex.axis=1.60)) dev.off() } </code></pre> <p>As you will realize, it seems that the biggest problem is that I am repeatedly reading the same files into R. This should be done once separately. Is there a way to avoid this and speed it up?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T23:34:47.723", "Id": "521409", "Score": "0", "body": "I have rolled back the code changes in revision 2. After receiving an answer you are not allowed to update the code in your question. This is not a forum where you should keep the most updated version in your question. Please see [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) as well as [_what you may and may not do after receiving answers_](http://codereview.meta.stackexchange.com/a/1765)." } ]
[ { "body": "<p>for minimal code changes:</p>\n<pre><code>prof_num &lt;- 1:4\nprof.path &lt;- file.path('LOGS_A1a', paste0('profile', prof_num, '.data'))\nDF.profile &lt;- lapply(prof.path, function(x) read.table(x, header = 1, skip = 5))\n\nfor (zone_num in 1:10) {\n \n png(file.path(paste(&quot;Light_Curve_&quot;,&quot;Zone_&quot;,zone_num,&quot;.png&quot;,sep = &quot;&quot;)), \n width = 1200, height = 960)\n par(mar = c(5,4,4,2) + 2) \n \n luminosities &lt;- c()\n for (prof_num in 1:4) {\n luminosity &lt;- DF.profile[[prof_num]]$luminosity[zone_num]\n luminosities &lt;- c(luminosities, luminosity)\n }\n \n plot.table &lt;- data.frame(phases, luminosities)\n o &lt;- order(phases)\n \n with(plot.table, plot(x=phases[o], y=luminosities[o],\n main=paste(&quot;Zone&quot;,zone_num,&quot;Light Curve&quot;,sep=&quot; &quot;),\n type=&quot;l&quot;, pch=3, lwd = 6, col=&quot;purple&quot;, xlab=expression(&quot;Phase&quot;),\n ylab=expression(&quot;Luminosity &quot; (L/L['\\u0298'])), cex.main=1.60,\n cex.lab=1.80, cex.axis=1.60))\n dev.off()\n}\n</code></pre>\n<p>I already answered this question... where did it disappear?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T15:27:55.513", "Id": "521377", "Score": "0", "body": "Why is `prof_num <- 1:4` defined in the first line?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T16:16:42.907", "Id": "521379", "Score": "1", "body": "@Woj why not? because in third line we read the data... it is the same variable as in your code... it shows file nr that needs to be read." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T16:32:22.630", "Id": "521380", "Score": "0", "body": "Understood. Also, the original post was deleted because although your solution speeds up the creation of one plot, it did not speed up the creation of the 2x2 plots I am actually creating for my task, but actually slowed it down. I am reading these profiles across 4 `sets <- c('A','B','C','D'), with each set's directory NOT having the same number of profiles. I was not sure how to convey the issue in a minimal example like the one above so the example assumes one set, but should I edit my post to show what I mean?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T16:35:12.023", "Id": "521381", "Score": "0", "body": "@Woj if you change the directories and read each time different datasets, then yes, you should specify that in question. Also, in that case, I think there will be hard to find improvements..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T19:11:08.703", "Id": "521398", "Score": "0", "body": "I've edited my question. I am not sure if I should include the entire compressed data (the compressed `LOGS` directories that I explain in the post) for clarity, or if I should subset all the files to keep a minimal example at the expense of clarity. But please let me know if something is not clear." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T19:35:51.547", "Id": "521400", "Score": "0", "body": "@Woj it looks that you can use my answer inside your loop. `prof_num <- prof.idx$prof_num`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T19:38:04.693", "Id": "521401", "Score": "0", "body": "@Woj look into faster functions for reading data, for example, `data.table`s `fread`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T20:29:52.423", "Id": "521404", "Score": "0", "body": "What do you mean? Do you mean I can paste `prof_num <- 1:4` and the other two lines in the profile loop?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T20:32:30.383", "Id": "521405", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/127490/discussion-between-minem-and-woj)." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T06:24:13.420", "Id": "264003", "ParentId": "263998", "Score": "1" } } ]
{ "AcceptedAnswerId": "264003", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T01:15:43.410", "Id": "263998", "Score": "0", "Tags": [ "r" ], "Title": "R code for reading tabular data files and plotting light curves of modeled stars" }
263998
<p>I have this piece of code which I'd like to improve:</p> <pre><code>std::optional&lt;IntersectionInfo&gt; Scene::intersects(const Ray&amp; ray) const { float closest = std::numeric_limits&lt;float&gt;::max(); int index = -1; int i = 0; for(auto&amp; sphere : _spheres) { auto [b, d] = Intersections::intersects(ray, sphere._shape); if(b &amp;&amp; d &lt; closest) { closest = d; index = i; } i++; } i = 0; bool isPlane = false; for(auto&amp; plane : _planes) { auto [b, d] = Intersections::intersects(ray, plane._shape); if(b &amp;&amp; d &lt; closest) { closest = d; index = i; isPlane = true; } i++; } i = 0; bool isBox = false; for(auto&amp; box : _boxes) { auto [b, d] = Intersections::intersects(ray, box._shape); if(b &amp;&amp; d &lt; closest) { closest = d; index = i; isBox = true; } } i = 0; bool isTri = false; for(auto&amp; tri : _triangles) { auto [b, d] = Intersections::intersects(ray, tri._shape); if(b &amp;&amp; d &lt; closest) { closest = d; index = i; isTri = true; } } if(index != -1) { IntersectionInfo info; info._intersection = ray._position + ray._direction * closest; if(isTri) { info._normal = Intersections::computeIntersectionNormal(ray, info._intersection, _triangles[index]._shape); info._material = *_triangles[index]._material; } else if(isBox) { info._normal = Intersections::computeIntersectionNormal(ray, info._intersection, _boxes[index]._shape); info._material = *_boxes[index]._material; } else if(isPlane) { info._normal = Intersections::computeIntersectionNormal(ray, info._intersection, _planes[index]._shape); info._material = *_planes[index]._material; } else { info._normal = Intersections::computeIntersectionNormal(ray, info._intersection, _spheres[index]._shape); info._material = *_spheres[index]._material; } info._intersection += info._normal * 0.001f; return info; } return {}; } </code></pre> <p>This function operates over several vectors (_spheres, _planes, _boxes and _triangles) which stores different types. Since the code is syntactically identical (but intersects and computeIntersectionNormal calls varies depending on the input type), I'd like to find a way to improve it.</p> <p>An obvious solution would be to use inheritance and have a single vector storing a Shape, which would have virtual members for intersects and computeInteresctionNormal, however :</p> <ul> <li>I do not wish to change the existing type structures just for the sake of this function.</li> <li>This function is an hot loop of my program inheritance has shown a visible cost.</li> </ul> <p>I'd also would like to avoid macros (unless they are really simple).</p> <p>I came up with this :</p> <pre><code>enum class ShapeType { None, Sphere, Plane, Box, Triangle }; template&lt;typename Shape&gt; std::function&lt;IntersectionInfo()&gt; intersectsWithShapes(const std::vector&lt;MaterialShape&lt;Shape&gt;&gt;&amp; materialShapes, const Ray&amp; ray, ShapeType currentType, float&amp; closest, int&amp; index, ShapeType&amp; type) { int i = 0; for(const auto&amp; materialShape : materialShapes) { auto [b, d] = Intersections::intersects(ray, materialShape._shape); if(b &amp;&amp; d &lt; closest) { closest = d; index = i; type = currentType; } i++; } return [&amp;]() { IntersectionInfo info; info._intersection = ray._position + ray._direction * closest; info._normal = Intersections::computeIntersectionNormal(ray, info._intersection, materialShapes[index]._shape); info._material = *materialShapes[index]._material; info._intersection += info._normal * 0.001f; return info; }; } std::optional&lt;IntersectionInfo&gt; Scene::intersects(const Ray&amp; ray) const { float closest = std::numeric_limits&lt;float&gt;::max(); int index = -1; auto type = ShapeType::None; auto F1 = intersectsWithShapes(_spheres, ray, ShapeType::Sphere, closest, index, type); auto F2 = intersectsWithShapes(_planes, ray, ShapeType::Plane, closest, index, type); auto F3 = intersectsWithShapes(_boxes, ray, ShapeType::Box, closest, index, type); auto F4 = intersectsWithShapes(_triangles, ray, ShapeType::Triangle, closest, index, type); decltype(F1) F; switch(type) { case ShapeType::None: return {}; case ShapeType::Sphere: F = F1; break; case ShapeType::Plane: F = F2; break; case ShapeType::Box: F = F3; break; case ShapeType::Triangle: F = F4; break; } return F(); } </code></pre> <p>I prefer this over the above function because adding a shape is simpler and less prone to error, and the entire interesting code is located in a small function. But it's not ideal because now Scene::intersects() is entirely made of boilerplate code, it's not obvious to guess why intersectsWithShapes returns a lambda, and this introduces a visible cost (althrough this time, only in debug build).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T06:53:01.707", "Id": "521422", "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](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." } ]
[ { "body": "<p>Could we not use a second template function instead of the lambda? e.g.:</p>\n<pre><code>template&lt;class Shape&gt;\nIntersectionInfo getIntersectionInfo(std::vector&lt;MaterialShape&lt;Shape&gt;&gt; const&amp; materialShapes, Ray const&amp; ray, float closest, std::size_t index)\n{\n auto position = ray._position + ray._direction * closest;\n auto normal = Intersections::computeIntersectionNormal(ray, position, materialShapes[index]._shape);\n auto material = *materialShapes[index]._material;\n\n position += info._normal * 0.001f;\n\n return { position, normal, material };\n};\n</code></pre>\n<p>Then we can call it directly from the switch statement:</p>\n<pre><code>std::optional&lt;IntersectionInfo&gt; Scene::intersects(const Ray&amp; ray) const\n{\n float closest = std::numeric_limits&lt;float&gt;::max();\n int index = -1;\n auto type = ShapeType::None;\n\n intersectsWithShapes(_spheres, ray, ShapeType::Sphere, closest, index, type);\n intersectsWithShapes(_planes, ray, ShapeType::Plane, closest, index, type);\n intersectsWithShapes(_boxes, ray, ShapeType::Box, closest, index, type);\n intersectsWithShapes(_triangles, ray, ShapeType::Triangle, closest, index, type);\n\n switch(type)\n {\n case ShapeType::None: return {};\n case ShapeType::Sphere: return getIntersectionInfo(_spheres, ray, closest, index);\n case ShapeType::Plane: return getIntersectionInfo(_planes, ray, closest, index);\n case ShapeType::Box: return getIntersectionInfo(_boxes, ray, closest, index);\n case ShapeType::Triangle: return getIntersectionInfo(_triangles, ray, closest, index);\n }\n\n return { };\n}\n</code></pre>\n<hr />\n<p>Another possibility is to use a <code>std::variant</code> for the shape type. We can then store all the shapes in one container and use <code>std::visit</code> to dispatch to functions that need the specific types, something like:</p>\n<pre><code>using Shape = std::variant&lt;Sphere, Plane, Box, Triangle&gt;;\n\nstd::optional&lt;IntersectionInfo&gt; Scene::intersects(Ray const&amp; ray) const\n{\n auto hit = false;\n auto closestDistance = std::numeric_limits&lt;float&gt;::max();\n auto closestIndex = std::size_t(-1);\n\n auto const intersects = [&amp;] (auto const&amp; shape) { return Intersections::intersects(ray, shape) };\n\n for (auto i = std::size_t{ 0 }; i != _shapes.size(); ++i)\n {\n auto [b, d] = std::visit(intersects, _shapes[i]._shape); // _shape is now the &quot;Shape&quot; variant type\n\n if (!b) continue;\n if (d &gt;= closest) continue;\n\n hit = true;\n closestDistance = d;\n closestIndex = i;\n }\n\n if (!hit) return { };\n\n auto const getInfo = [&amp;] (auto const&amp; shape)\n {\n auto position = ray._position + ray._direction * closestDistance;\n auto normal = Intersections::computeIntersectionNormal(ray, position, shape);\n auto material = *_shapes[closestIndex]._material;\n \n position += info._normal * 0.001f;\n \n return { position, normal, material };\n };\n\n return std::visit(getInfo, _shapes[closestIndex]._shape);\n}\n</code></pre>\n<p><code>std::visit</code> will cast the variant to the correct type, and pass it to the lambda.</p>\n<p>The lambda takes an <code>auto</code> argument, which effectively means it has a templated call operator:</p>\n<pre><code>struct anonymous_lambda_type\n{\n template&lt;class ShapeT&gt;\n auto operator()(ShapeT const&amp; shape) { ... };\n}\n</code></pre>\n<p>We could instead define our own functor using overloading if we needed to change the behavior based on the specific type (which we don't here):</p>\n<pre><code>struct ray_intersection\n{\n std::tuple&lt;bool, float&gt; operator()(Sphere const&amp; sphere) { ... }\n std::tuple&lt;bool, float&gt; operator()(Plane const&amp; plane) { ... }\n ...\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T14:55:37.377", "Id": "521375", "Score": "0", "body": "The variant would dispatch to the shape with the same overhead as the virtual function. Making each shape in its own collection is faster, just just because it saves an indirection in the function call, but processes all the like things together so the code for one shape stays in the cache." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T15:17:37.033", "Id": "521376", "Score": "0", "body": "I guess. I think we'd probably want to implement an acceleration structure (BVH, grid, etc.) before worrying about that though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T14:17:49.427", "Id": "521450", "Score": "0", "body": "Not using virtual functions was mentioned in the OP. Faking it with the same or higher overhead would be just as bad for the same reasons he mentioned." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T14:45:24.840", "Id": "521454", "Score": "0", "body": "I'm not sure that's true. It's all run-time polymorphism, whether we use a \"type\" enum and a switch statement, a variant, or actual inheritance. The only way to know is to measure it and see. (And it seems that performance isn't actually such an issue, because we're not using any kind of acceleration structure.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T15:33:39.913", "Id": "521466", "Score": "0", "body": "Regardless, he says he doesn't want to use virtual functions because of whatever reasons; it doesn't make sense to suggest a more complex workaround that technically doesn't use virtual functions but actually has those same issues. The reply should be \"go ahead, if you didn't measure it it's not the limiting factor anyway.\" not do something equivalent but more difficult." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T17:40:06.777", "Id": "521474", "Score": "0", "body": "It's just \"another possibility\". (And it's not something I invented as a \"workaround\". I think it's a reasonable solution and I've used it in the past, and much prefer it to inheritance.)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T09:06:58.170", "Id": "264005", "ParentId": "264000", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T04:17:47.603", "Id": "264000", "Score": "3", "Tags": [ "c++" ], "Title": "Factorize a function where inheritance is unwanted" }
264000
<p>I have a code in vba that works well but it is slow so I am looking for a better solution to this code.</p> <p>If there is any one who could help me I would be grateful!</p> <pre><code>Sub Formula() Sheets(&quot;Result&quot;).Range(&quot;D2:D&quot; &amp; Cells(Rows.Count, 2).End(xlUp).Row).FormulaR1C1 = &quot;=VLOOKUP(RC[-2],DATA!C[2]:C[86],3,FALSE)&quot; Sheets(&quot;Result&quot;).Range(&quot;E2:E&quot; &amp; Cells(Rows.Count, 2).End(xlUp).Row).FormulaR1C1 = &quot;=VLOOKUP(RC[-3],DATA'!C[1]:C[85],4,FALSE)&quot; Sheets(&quot;Result&quot;).Range(&quot;F2:F&quot; &amp; Cells(Rows.Count, 2).End(xlUp).Row).FormulaR1C1 = &quot;=VLOOKUP(RC[-4],DATA!C:C[84],13,FALSE)&quot; Sheets(&quot;Result&quot;).Range(&quot;G2:G&quot; &amp; Cells(Rows.Count, 2).End(xlUp).Row).FormulaR1C1 = &quot;=VLOOKUP(RC[-5],DATA!C[-5]:C,6,FALSE)&quot; Sheets(&quot;Result&quot;).Range(&quot;H2:H&quot; &amp; Cells(Rows.Count, 2).End(xlUp).Row).FormulaR1C1 = &quot;=VLOOKUP(RC[-6],DATA!C[-2]:C[82],21,FALSE)&quot; Sheets(&quot;Result&quot;).Range(&quot;I2:I&quot; &amp; Cells(Rows.Count, 2).End(xlUp).Row).FormulaR1C1 = &quot;=VLOOKUP(RC[-7],DATA!C[-3]:C[81],22,FALSE)&quot; Sheets(&quot;Result&quot;).Range(&quot;J2:J&quot; &amp; Cells(Rows.Count, 2).End(xlUp).Row).FormulaR1C1 = &quot;=VLOOKUP(RC[-8],DATA!C[-4]:C[80],24,FALSE)&quot; Sheets(&quot;Result&quot;).Range(&quot;K2:K&quot; &amp; Cells(Rows.Count, 2).End(xlUp).Row).FormulaR1C1 = &quot;=VLOOKUP(RC[-9],DATA!C[-5]:C[79],25,FALSE)&quot; Sheets(&quot;Result&quot;).Range(&quot;L2:L&quot; &amp; Cells(Rows.Count, 2).End(xlUp).Row).FormulaR1C1 = &quot;=VLOOKUP(RC[-10],DATA!C[-6]:C[78],44,FALSE)&quot; Dim LastRowColumnA As Long LastRowColumnA = Cells(Rows.Count, 1).End(xlUp).Row Sheets(&quot;Result&quot;).Range(&quot;A2:L&quot; &amp; LastRowColumnA).Select Selection.Copy Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False End Sub </code></pre>
[]
[ { "body": "<p>This should run faster. If any of the applications I turn off at the start is messing up with the functionality of the macro delete it.</p>\n<pre><code>Sub Formula()\n\n'turn off applications not required\nApplication.Calculation = xlCalculationManual\nApplication.ScreenUpdating = False\nApplication.DisplayStatusBar = False\nApplication.EnableEvents = False\nActivesheet.DisplayPageBreaks = False\n\nWith Sheets(&quot;Result&quot;)\n\n.Range(&quot;D2:D&quot; &amp; Cells(Rows.Count, 2).End(xlUp).Row).FormulaR1C1 = &quot;=VLOOKUP(RC[-2],DATA!C[2]:C[86],3,FALSE)&quot; \n.Range(&quot;E2:E&quot; &amp; Cells(Rows.Count, 2).End(xlUp).Row).FormulaR1C1 = &quot;=VLOOKUP(RC[-3],DATA'!C[1]:C[85],4,FALSE)&quot; \n.Range(&quot;F2:F&quot; &amp; Cells(Rows.Count, 2).End(xlUp).Row).FormulaR1C1 = &quot;=VLOOKUP(RC[-4],DATA!C:C[84],13,FALSE)&quot; \n.Range(&quot;G2:G&quot; &amp; Cells(Rows.Count, 2).End(xlUp).Row).FormulaR1C1 = &quot;=VLOOKUP(RC[-5],DATA!C[-5]:C,6,FALSE)&quot; \n.Range(&quot;H2:H&quot; &amp; Cells(Rows.Count, 2).End(xlUp).Row).FormulaR1C1 = &quot;=VLOOKUP(RC[-6],DATA!C[-2]:C[82],21,FALSE)&quot; \n.Range(&quot;I2:I&quot; &amp; Cells(Rows.Count, 2).End(xlUp).Row).FormulaR1C1 = &quot;=VLOOKUP(RC[-7],DATA!C[-3]:C[81],22,FALSE)&quot; \n.Range(&quot;J2:J&quot; &amp; Cells(Rows.Count, 2).End(xlUp).Row).FormulaR1C1 = &quot;=VLOOKUP(RC[-8],DATA!C[-4]:C[80],24,FALSE)&quot; \n.Range(&quot;K2:K&quot; &amp; Cells(Rows.Count, 2).End(xlUp).Row).FormulaR1C1 = &quot;=VLOOKUP(RC[-9],DATA!C[-5]:C[79],25,FALSE)&quot; \n.Range(&quot;L2:L&quot; &amp; Cells(Rows.Count, 2).End(xlUp).Row).FormulaR1C1 = &quot;=VLOOKUP(RC[-10],DATA!C[-6]:C[78],44,FALSE)&quot; \n\nEnd With\n\nDim LastRowColumnA As Long\nLastRowColumnA = Cells(Rows.Count, 1).End(xlUp).Row\n\nSheets(&quot;Result&quot;).Range(&quot;A2:L&quot; &amp; LastRowColumnA).Select\nSelection.Copy\n Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _\n :=False, Transpose:=False\n\n'turn applications back on\nApplication.Calculation = xlCalculationAutomatic\nApplication.ScreenUpdating = True\nApplication.DisplayStatusBar = True\nApplication.EnableEvents = True\nActivesheet.DisplayPageBreaks = True\n\nEnd Sub\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T10:50:51.960", "Id": "521358", "Score": "2", "body": "It's strongly recommended that you store the _current_ values of the `Application` settings, then restore them to their previous values, instead of resetting them to a predetermined set of values." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T13:19:02.050", "Id": "521363", "Score": "0", "body": "Also you can avoid `Select`ing and the clipboard when pasting values: `With Sheets(\"Result\").Range(\"A2:L\" & LastRowColumnA)`, `.Value = .Value`, `End With`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T08:49:30.460", "Id": "264004", "ParentId": "264002", "Score": "0" } }, { "body": "<p>Suggestion: use <a href=\"https://www.ablebits.com/office-addins-blog/2017/07/11/excel-name-named-range-define-use/\" rel=\"nofollow noreferrer\">named ranges</a> if possible to make your ranges more descriptive (and also diminish the risk of confusion).</p>\n<p>And perhaps try the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/microsoft.office.tools.excel.worksheet.usedrange?view=vsto-2017\" rel=\"nofollow noreferrer\">UsedRange</a> argument rather than selecting whole columns down to the last row. The overly broad selection is wasteful and could be a cause of slowdown. I am on Linux now, so I\ncan't test. But make sure you are not making calculations for nothing. Focus on the range that is effectively in use and holding data, not the whole sheet.</p>\n<p>Something else: the relative references. For example:</p>\n<pre><code>VLOOKUP(RC[-3],\n</code></pre>\n<p>means if I am not wrong: the current row and 3 columns to the left. I am wondering if this could be faster if written in plain A1 notation instead, so Excel doesn't have to compute the value. This is a question, I really don't know but it's something I might want to try.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T19:52:28.350", "Id": "264029", "ParentId": "264002", "Score": "0" } }, { "body": "<h2 id=\"a-vba-lookup\">A VBA Lookup</h2>\n<ul>\n<li><p>The two 'Source Lookup Ranges' (<code>&quot;F2:Flr&quot;</code>, <code>&quot;B2:Blr&quot;</code>), the ranges where you try to find a match, stay as ranges (because <code>Application.Match</code> is faster on ranges) while the rest is written to arrays. The results are written to the 'Destination Array' (<code>dData</code>) which is then, in one go, written to the 'Destination Range'.</p>\n</li>\n<li><p>Adjust (double-check) the values in the constants section.</p>\n</li>\n</ul>\n<pre class=\"lang-vb prettyprint-override\"><code>Option Explicit\n\nSub VBALookup()\n \n Const sName As String = &quot;Data&quot;\n Const slFirst1 As String = &quot;F2&quot;\n Const slFirst2 As String = &quot;B2&quot;\n Const sl2ColIndex As Long = 3 ' in connection to &quot;B2&quot; and ...,G,...\n Const sColsList As String = &quot;H,I,R,G,Z,AA,AC,AD,AW&quot;\n \n Const dName As String = &quot;Result&quot;\n Const dlFirst As String = &quot;B2&quot;\n Const dFirst As String = &quot;D2&quot;\n \n Dim wb As Workbook: Set wb = ThisWorkbook\n \n Dim dws As Worksheet: Set dws = wb.Worksheets(dName)\n Dim dlrg As Range: Set dlrg = RefColumnRange(dws.Range(dlFirst))\n If dlrg Is Nothing Then Exit Sub\n\n Dim drCount As Long: drCount = dlrg.Rows.Count\n Dim dlData As Variant: dlData = GetColumnRange(dlrg)\n \n Dim sws As Worksheet: Set sws = wb.Worksheets(sName)\n \n Dim sCols() As String: sCols = Split(sColsList, &quot;,&quot;)\n Dim nUpper As Long: nUpper = UBound(sCols)\n \n Dim slrg1 As Range: Set slrg1 = RefColumnRange(sws.Range(slFirst1))\n \n Dim sData As Variant: ReDim sData(0 To nUpper)\n \n Dim dData As Variant: ReDim dData(1 To drCount, 1 To nUpper + 1)\n \n Dim crg As Range\n Dim rIndex As Variant\n Dim n As Long\n Dim r As Long\n \n If Not slrg1 Is Nothing Then\n For n = 0 To nUpper\n If n &lt;&gt; sl2ColIndex Then\n Set crg = slrg1.EntireRow.Columns(sCols(n))\n sData(n) = GetColumnRange(crg)\n End If\n Next n\n For r = 1 To drCount\n rIndex = Application.Match(dlData(r, 1), slrg1, 0)\n If IsNumeric(rIndex) Then\n For n = 0 To nUpper\n If n &lt;&gt; sl2ColIndex Then\n dData(r, n + 1) = sData(n)(rIndex, 1)\n End If\n Next n\n End If\n Next r\n End If\n \n Dim slrg2 As Range: Set slrg2 = RefColumnRange(sws.Range(slFirst2))\n \n If Not slrg2 Is Nothing Then\n n = sl2ColIndex\n Set crg = slrg2.EntireRow.Columns(sCols(n))\n sData(n) = GetColumnRange(crg)\n For r = 1 To drCount\n rIndex = Application.Match(dlData(r, 1), slrg2, 0)\n If IsNumeric(rIndex) Then\n dData(r, n + 1) = sData(n)(rIndex, 1)\n End If\n Next r\n End If\n \n With dws.Range(dFirst).Resize(, nUpper + 1)\n .Resize(drCount).Value = dData\n .Resize(.Worksheet.Rows.Count - .Row - drCount + 1) _\n .Offset(drCount).ClearContents\n End With\n\nEnd Sub\n\nFunction RefColumnRange( _\n ByVal FirstCellRange As Range) _\nAs Range\n If FirstCellRange Is Nothing Then Exit Function\n \n Dim lCell As Range\n With FirstCellRange.Cells(1)\n Set lCell = .Resize(.Worksheet.Rows.Count - .Row + 1) _\n .Find(&quot;*&quot;, , xlFormulas, , , xlPrevious)\n If lCell Is Nothing Then Exit Function\n Set RefColumnRange = .Resize(lCell.Row - .Row + 1)\n End With\n\nEnd Function\n\nFunction GetColumnRange( _\n ByVal ColumnRange As Range) _\nAs Variant\n If ColumnRange Is Nothing Then Exit Function\n \n Dim rCount As Long: rCount = ColumnRange.Rows.Count\n Dim cData As Variant\n With ColumnRange.Columns(1)\n If rCount = 1 Then\n ReDim cData(1 To 1, 1 To 1): cData(1, 1) = .Value\n Else\n cData = .Value\n End If\n End With\n \n GetColumnRange = cData\nEnd Function\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T01:56:17.787", "Id": "264079", "ParentId": "264002", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T05:44:23.280", "Id": "264002", "Score": "2", "Tags": [ "vba", "excel" ], "Title": "VBA Vlookup to work faster" }
264002
<p>To put it in context, I had the assignment to do for a job interview in Node.JS, which basically making CRUD with products (and it have certain conditions). The assignment was well-understandable, and I have succeeded to make this task. After the company reviewed my code, I've got rejected because one of the main reasons (along with unit test not done, code not properly commented etc... ) was</p> <ul> <li><strong>&quot;Huge coupling of the controller&quot; and Model is in ProductService</strong>.</li> </ul> <p>I am actually confused with this sentence because I have used the Services and Repository Pattern, and separate all of the concerns, as follows (Folder structure):</p> <ul> <li>Controllers <em>Responsible for controlling the flow of the application execution</em></li> <li>Models <em>Database ORM object</em></li> <li>Repositories <em>handling table data via models</em></li> <li>Services <em>responsible for business logic</em></li> </ul> <p><strong>Product Router</strong> (import to my index router) <div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const router = require('koa-router')(); const ProductController = require('../../app/controllers/product.controller'); const AuthMiddleware = require('../../middleware/authValidation') // router.get('location', ErpApiController.getLocation) router.get('/', ProductController.searchAllProducts); // GET /api/v1/products/ router.get('code/:code', ProductController.searchProductByCode); // GET /api/v1/products/code/:code router.get('name/:name', ProductController.searchProductByName); // GET /api/v1/products/name/:name router.get('brand/:brand', ProductController.searchProductByBrand); // GET /api/v1/products/brand/:brand router.get('category/:category', ProductController.searchProductByCategory); // GET /api/v1/products/brand/:brand</code></pre> </div> </div> </p> <p>Here is my <strong>Product Controller</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const productService = require("../services/product.service"); exports.searchAllProducts = async (ctx) =&gt; { const result = await productService.getAllProducts(); ctx.body = result; } exports.searchProductByCode = async (ctx) =&gt; { const result = await productService.getAllProductByCode(ctx.params.code) ctx.body = result; } exports.searchProductByName = async (ctx) =&gt; { const result = await productService.getAllProductByName(ctx.params.name) ctx.body = result; } ....</code></pre> </div> </div> </p> <p><strong>Product Repository</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const models = require("../models"); const Sequelize = require("sequelize"); exports.fetchAllProduct = async () =&gt; { return await models.Products.findAll({ include: [ // { // model: models.Brands, // as: "brand", // attributes: { exclude: ['id', 'description', 'category_ID', 'createdAt', 'updatedAt'] }, // }, { model: models.ProductSizes, as: "sizes", attributes: { exclude: ['id', 'description', 'product_code', 'createdAt', 'updatedAt'] }, }, { model: models.Categories, as: "category", attributes: ['name'], through: { attributes: [], } }, ], }); } exports.fetchProductByCode = async (code) =&gt; { return models.Products.findOne({ where: { code: code, }, include: [ { model: models.ProductSizes, as: "sizes", attributes: { exclude: ['description', 'product_code', 'createdAt', 'updatedAt'] }, }, { model: models.Categories, as: "category", attributes: ['name'], through: { attributes: [], } }, ], }) }</code></pre> </div> </div> </p> <p><strong>Product Service file</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const dateFormat = require("../../utils/dateUtil"); const productRepo = require("../repositories/product.repository"); const productSizeRepo = require("../repositories/productSize.repository"); const productCateRepo = require("../repositories/productCategory.repository"); const categoryRepo = require("../repositories/category.repository"); const _ = require("lodash"); exports.getAllProducts = async () =&gt; { return await productRepo.fetchAllProduct(); } exports.getAllProductByCode = async (ctxcode) =&gt; { const data = await productRepo.fetchProductByCode(ctxcode) if(!data) { return { code: "204", success: true, data: [], }; } const products = []; products.push({ code: data.code, name: data.name, description: data.description, img_url: data.img_url, product_url: data.product_url, brand_name: data.brand_name, color: data.color, start_period: dateFormat.dateFormat(data.start_period), end_period: dateFormat.dateFormat(data.end_period), isActive: data.isActive, sizes: data.sizes, categories: data.category }) return { code: "200", success: true, count: products.length, message: "", data: products, }; } exports.getAllProductByName = async (name) =&gt; { const data = await productRepo.fetchProductByName(name) if(!data) { return { code: "204", success: true, data: [], }; } const products = []; for(let i =0; i &lt; data.length; i++) { products.push({ code: data[i].code, name: data[i].name, description: data[i].description, img_url: data[i].img_url, product_url: data[i].product_url, brand_name: data[i].brand_name, color: data[i].color, start_period: dateFormat.dateFormat(data[i].start_period), end_period: dateFormat.dateFormat(data[i].end_period), isActive: data[i].isActive, sizes: data[i].sizes, categories: data[i].category }) } return { code: "200", success: true, data: products, }; }</code></pre> </div> </div> </p> <p>I would like to know your thought on it and how can I improve the architecture</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T11:16:57.407", "Id": "521359", "Score": "0", "body": "They probably mean that the service should return data (or throw exception if there were any errors) and the controller should decide what status to return and how to present that data or error to the client." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T13:14:12.497", "Id": "521361", "Score": "0", "body": "@slepic Thank you for your answer. I hear you when you are mentioning about the return data format (which I did in a middleware, but due to lack of time, I have implemented it in every services method). But Can you explained to me what does it mean that **the controller is coupling (too much)**. I have a strong feeling that I have decoupled my code and in the service layer, I respect his purpose which is write the business logic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T13:20:23.080", "Id": "521364", "Score": "0", "body": "Not to mention that I didn't call the Product Model in the Service Layer (Only Repositories). Thank you for highlighting me on this, as I am a bit confused with these explanations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T13:52:09.110", "Id": "521368", "Score": "0", "body": "Welcome to the Code Review Community, the title of the question should be about what the code does, rather than your concerns about the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T03:22:31.463", "Id": "521589", "Score": "0", "body": "Hi @pacmaninbw, sorry for the title, should I need to rename it as \"separation of concern Controller | Service | Repositories Layer\"?" } ]
[ { "body": "<p>As it stands your controller is pretty much pointless since it's the service that decides on the api's output model and status codes. The service is also responsible for the db model transformation, i.e. it converts the db model directly to the api model. However, you have stated that the service is responsible for business logic. It is not setup to do this well (why? because it has to handle three models at the same time)</p>\n<p>What I would suggest is to separate the boundaries in your system more clearly. In your case you have the api, the db, and everything in between. You could transform DatabaseProduct into Product in the repository, then process Product inside the service (your business logic), and finally transform Product into ApiProduct in the controller (with some helper functions or classes depending on your needs). Note that for a simple api these models might be the same, but it can still be helpful to think about in this way.</p>\n<p>Finally, I would also consider extracting the transform functions into pure functions. You might find that you can eliminate some classes/modules entirely. You might also find that the list of products and single product are the same model</p>\n<p>Edit:</p>\n<p>I'm not familiar with koa router, and don't use sequelize, but something like below is what I'm talking about:</p>\n<pre class=\"lang-js prettyprint-override\"><code>\n// repo\nconst rowToProduct = (row) =&gt; {\n return {\n code: row.code,\n name: row.name,\n description: row.description,\n img_url: row.img_url,\n product_url: row.product_url,\n brand_name: row.brand_name,\n color: row.color,\n start_period: dateFormat.dateFormat(row.start_period),\n end_period: dateFormat.dateFormat(row.end_period),\n isActive: row.isActive,\n sizes: row.sizes, // or a separate transform for size\n categories: row.category // or a separate transform for category\n }\n}\n\nexports.fetchProductByCode = async (code) =&gt; {\n const row = await models.Products.findOne(/* query */)\n if (!row) {\n return null\n }\n return rowToProduct(row)\n}\n\n// controller\nexports.searchProductByCode = async (ctx) =&gt; {\n const product = await productRepo.fetchProductByCode(ctx.params.code)\n\n if (!product) {\n ctx.status = 404\n return\n }\n\n // like below, or a separate transform for the api response\n ctx.body = {\n code: &quot;200&quot;,\n success: true,\n count: 1,\n message: &quot;&quot;,\n data: [product],\n }\n}\n</code></pre>\n<p>So just remove the service since you don't have any business logic (add it only if you need it). Do the transform right in the repo. Move the api model to the controller.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T03:23:39.320", "Id": "521590", "Score": "0", "body": "Thank you for your answer Magnus. I understand the point that the controller is pointless. Could you please guide me or share with me a repo that I can compare and see what I can improve in my code. Thank you" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T07:13:30.160", "Id": "521597", "Score": "0", "body": "I added some example code in the edit. I don't have an open source repo that shows this easily.." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T19:06:06.027", "Id": "264068", "ParentId": "264006", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T09:41:50.343", "Id": "264006", "Score": "1", "Tags": [ "javascript", "node.js", "interview-questions", "mvc", "repository" ], "Title": "Is My Controller too Coupling?" }
264006
<p>I have been learning Java for approximately 3 weeks now and made 2 posts on code review. Learned quite a lot from people and learned a lot of Java at the same time as well. I made this Age Calculator program to mainly practice with splitting up code into methods and classes as well as using method parameters and return types.</p> <p>As for the program itself, it takes user input of birth year, month, and day, and prints out the difference. It also has a prompt to allow you to restart the program or terminate it. I was wondering if there's anything I can do in a better and elegant way.</p> <p>Main class:</p> <pre><code>public class Main { // Main method to run application. public static void main(String[] args) { Application application = new Application(); application.printInstructions(); application.loopProgram(); } } </code></pre> <p>Application class:</p> <pre><code>import java.time.LocalDate; import java.time.Period; import java.util.Scanner; public class Application { Scanner scan = new Scanner(System.in); // Calculates the age of a user. public String calculateAge(int year, int month, int day) { LocalDate today = LocalDate.now(); // Today's date LocalDate birthday = LocalDate.of(year, month, day); // Birth date Period dateDifference = Period.between(birthday, today); return &quot;You are &quot; + dateDifference.getYears() + &quot; year(s), &quot; + dateDifference.getMonths() + &quot; month(s), &quot; + dateDifference.getDays() + &quot; day(s) old.&quot;; } // Prints a brief description about the program. public void printInstructions() { System.out.println(&quot;—————————————————————————————————————&quot;); System.out.println(&quot;Age Calculator - Calculates your current age using your birthday.&quot;); } // Loops the program until the user exits with 'N'. public boolean loopProgram() { String commandPrompt = &quot;&quot;; while (!commandPrompt.equals(&quot;N&quot;)) { System.out.print(&quot;Enter your birth year: &quot;); int birthYear = scan.nextInt(); System.out.print(&quot;Enter your birth month: &quot;); int birthMonth = scan.nextInt(); System.out.print(&quot;Enter your birth day: &quot;); int birthDay = scan.nextInt(); scan.nextLine(); System.out.println(calculateAge(birthYear, birthMonth, birthDay)); System.out.print(&quot;Restart? (Y/N): &quot;); commandPrompt = scan.nextLine().toUpperCase(); System.out.println(&quot;—————————————————————————————————————&quot;); } return false; } } </code></pre>
[]
[ { "body": "<p>I have a lot experience with Java, but still, code is a very subjective thing, so on many things there is no single universal truth.</p>\n<ol>\n<li>Rename Application to AgeCalculator</li>\n<li>Application implements Runnable</li>\n<li>Encapsulate(make private) methods printInstructions and loopProgram in the Application and call only run from main. You are forcing the user of Application to learn how to start it(By user I mean other developer that would want to reuse the Application).</li>\n<li>No point in having Main class separate. It would make more sense to\nsplit logical operations into different classes, I would opt for\nsplitting if I get over 200-300 of lines, or see a clear reason for\nit. So you could create a class for reading and printing to terminal\nand a class for calculating.</li>\n<li>You should create a method log() which would hide the ugly System.out.print(&quot;. This is totally subjective.</li>\n<li>Create a special method for printing ------------- as it is used more than once</li>\n<li>In this case it makes total sense that you define strings where you use them, but it is more optimal to use constants, so the string does not have to be created a new every time you use it.</li>\n<li>Make calculateAge private. By default you wanna make everything private unless you really need to make it otherwise.</li>\n<li>You are providing the results of calculation already as a formatted string, so if you'd like to reuse it you would have to change this method.</li>\n</ol>\n<p>New task: try creating also a calculator for how many days till next birthday. Create a new interface. Separate the logic for calculating the age and next birthday to new classes and make them both implement the Calculator interface.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T18:11:38.410", "Id": "521388", "Score": "0", "body": "Thank you for your input! I realized that code indeed is pretty subjective and there's really no right or wrong in most cases. You raised very good points but I was wondering what you meant by splitting the logic for calculating age and next birthday and have them implement the Calculator interface." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T15:30:37.487", "Id": "521462", "Score": "0", "body": "I was suggesting for you to do another exercise - to add also days till next birthday functionality. I was suggesting then to create a separate classes where 1 would be holding just a method for calculating the age, the other just for next birthday. Both would be implementing an interface. \nYou can then play around with referring to the calculators in main app just through that interface. Try to do an UML diagram of it. This will help you better understand the principles of Object oriented programming." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T16:00:06.710", "Id": "521468", "Score": "0", "body": "Ah, I see. Well, thank you for your input again. I will mark this as solved :)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T14:27:24.433", "Id": "264014", "ParentId": "264010", "Score": "2" } } ]
{ "AcceptedAnswerId": "264014", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T13:17:37.170", "Id": "264010", "Score": "1", "Tags": [ "java", "beginner" ], "Title": "AgeCalculator - Calculates your current age using your birth date" }
264010
<p>I am working on an API call in pure Javascript and I hit a section of code that i want to refractor The code is something like this</p> <pre><code>function getStart(city, lat, long, response) { const latDir = lat[lat.length - 1]; const latVal = lat.slice(0, -1); const latMinVal = latVal - 15 &lt; 0 ? 0 : latVal - 15; const latMaxVal = latVal + 15 &gt; 90 ? 90 : latVal + 15; const longDir = long[long.length - 1]; const longVal = long.slice(0, -1); const longMinVal = longVal - 15 &lt; 0 ? 0 : longVal - 15; const longMaxVal = longVal + 15 &gt; 180 ? 180 : longVal + 15; response = response.data; console.log(response); for (let i = 0; response &amp;&amp; i &lt; response.length; i++) { if ( response[i][4] === latDir &amp;&amp; response[i][6] === longDir &amp;&amp; response[i][3] &gt;= latMinVal &amp;&amp; response[i][3] &lt;= latMaxVal &amp;&amp; response[i][5] &gt;= longMinVal &amp;&amp; response[i][5] &lt;= longMaxVal ) { const latRes = `${response[i][3]}${latDir}`; const longRes = `${response[i][5]}${longDir}`; const data = { e: response[i][1], lat: latRes, long: longRes, city: city }; return data; } } return null; } </code></pre> <p>Is there any way to create a shorter version of this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T13:49:08.860", "Id": "521367", "Score": "1", "body": "Welcome to the Code Review Community, what we do here is review working code that you have written and provide tips on how to improve that code. The statement `The code is something like this` indicates this is not the exact working code that you have written and that would make the question off-topic for at least 2 reasons. 1) It isn't the actual working code. 2) It is not clear that you wrote the code. Please read [How do I ask a good question?(https://codereview.stackexchange.com/help/how-to-ask)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T06:40:58.670", "Id": "521420", "Score": "0", "body": "Welcome to Code Review! We need to know *what the code is intended to achieve*. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](//meta.codereview.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](//meta.codereview.stackexchange.com/q/2436), rather than your concerns about the code." } ]
[ { "body": "<p>Not really shorter, but something can be done to make it more readable.</p>\n<h3 id=\"do-some-cleanup-07io\">Do some cleanup</h3>\n<p>Is</p>\n<pre><code>console.log(response)\n</code></pre>\n<p>really needed after the debugging is done?</p>\n<h3 id=\"validate-data-before-processing-zka4\">Validate data before processing</h3>\n<p>You're checking for <code>response</code> not being falsy on every loop. Probably you should check it first and only then proceed to all other actions. This</p>\n<pre><code>if(!response.data)\n return null;\n</code></pre>\n<p>on the beginning will make the function longer, but the purpose will be much clearer.</p>\n<h3 id=\"use-deconstruction-suxw\">Use deconstruction</h3>\n<p>I guess latVal is not exactly what to you want it to be (but still JavaScript allows some operations with wrong types, so the code can still be working-ish). Try</p>\n<pre><code>const [latVal, latDir] = lat\nconst [longVal, longDir] = long\n</code></pre>\n<p>instead.</p>\n<h3 id=\"use-min-and-max-to-limit-values-0ih6\">Use min and max to limit values</h3>\n<p>This looks obvious when you know it, but somehow many developers misses it:</p>\n<pre><code>const latMinVal = Math.max(0, latVal - 15)\n</code></pre>\n<p>does the same and is much more readable.</p>\n<h3 id=\"consider-using-for-of-op7z\">Consider using <code>for - of</code></h3>\n<p>If the <code>response</code> is validated,</p>\n<pre><code>for(const line of response)\n</code></pre>\n<p>or something like that can be better then using response[i] every time. You can also use decomposition here:</p>\n<pre><code>for(const [_1, respName, _2, respLat, respLatDir, respLong, lespLongDir] of response)\n</code></pre>\n<h3 id=\"complex-interval-comparisons-look-better-with-less-sign-only-jg82\">Complex interval comparisons look better with less sign only</h3>\n<pre><code> latMinVal &lt;= response[i][3] &amp;&amp; response[i][3] &lt;= latMaxVal\n</code></pre>\n<p>is the best you can do to immitate mathematical/pythonic <code>latMinVal &lt;= response[i][3] &lt;= latMaxVal</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T14:18:50.677", "Id": "264013", "ParentId": "264011", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T13:24:29.747", "Id": "264011", "Score": "0", "Tags": [ "javascript" ], "Title": "Refractor a function call" }
264011
<p>This is my implementation of <code>itoa()</code> (Integer to Alpha), which converts an integer to a string. Memory management and optimization is important. The <strong>caller is not responsible for allocation</strong> of the string. The <strong>caller is responsible for freeing</strong> the string, as my implementation does not allow to call <code>free()</code>. The function handles everything internally, except freeing. The function <strong>allocates memory twice</strong>, for the <strong>string</strong> to be returned and the <strong>int array</strong> where the digits are stored.</p> <p>I am concerned about <strong>memory leaks</strong> with the <strong>allocation of the int array</strong> which stores the digits. Is there any way to optimize / secure the memory allocation so I do not get leaks?</p> <p>The code:</p> <pre><code>#include &lt;stdlib.h&gt; static int digitcount(int n) { int i = 0; if (n == 0) return (1); while (n != 0) { n /= 10; i++; } return (i); } static int *revarray(int *a, int size) { int tmp = 0; int i = 0; while (i &lt; size / 2) { tmp = a[i]; a[i] = a[size - i - 1]; a[size - i - 1] = tmp; i++; } return (a); } static int *getdigits(int n, int size) { int *a; int r = 0; int i = 0; a = malloc(size * sizeof(int)); if (a == NULL) return (NULL); if (n == 0) a[i] = 0; while (n != 0) { r = n % 10; if (r &lt; 0) r *= -1; a[i] = r; i++; n /= 10; } a = revarray(a, size); return (a); } char *itoa(int n) { char *nbr; int *digits; int digits_size; int i; int j; digits_size = digitcount(n); digits = getdigits(n, digits_size); if (n &lt; 0) digits_size++; nbr = malloc(digits_size + 1 * sizeof(char)); if (nbr == NULL || digits == NULL) return (NULL); i = 0; j = 0; if (n &lt; 0) nbr[i++] = '-'; while (i &lt; digits_size) { nbr[i] = digits[j] + '0'; i++; j++; } nbr[i] = 0; return (nbr); } </code></pre> <p>EDIT: For practice and understanding I wanted to implement my own <code>itoa()</code> instead of just calling <code>sprintf()</code> or using external libraries.</p>
[]
[ { "body": "<p>Counting the digits doubles the amount of work, and the division/modulo is indeed very hard work for the CPU.</p>\n<p>You know the maximum size of the resulting string, because it would be the largest or most negative integer you can be passed. So use a local array as a buffer, and then copy the result to allocated memory.</p>\n<p>You have a separate function to reverse the string. Instead, fill your buffer from the <em>right</em>, decrementing the pointer as you write each digit.</p>\n<p>Instead of checking for a negative remainder each time through the loop, check for negative input once at the beginning. If it's negative, remember that and change to positive. Then when done, finish off with a <code>-</code> character if your is-negative flag is set.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T07:09:46.690", "Id": "521423", "Score": "0", "body": "\"If it's negative, remember that and change to positive.\" is a problem when `n == INT_MIN`, as `-INT_MIN` is _undefined behavior_ with 2's compliment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T14:03:42.087", "Id": "521446", "Score": "0", "body": "@chux-ReinstateMonica I didn't want to digress with details. Either notice that as a special singular case, or have the base function use unsigned or wider types (I've seen C standard library in MSVC where the only implementation was the longest unsigned type and other types were thin wrappers that called it. That's slower than a modern template version, BTW)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T14:37:14.490", "Id": "521453", "Score": "0", "body": "`INT_MIN` does not need to be a special case or resort to other types or suffer performance. Simply fold positive values to negative ones and use the `n%10` result of [-9...0] to form the digit character." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T15:39:37.783", "Id": "521467", "Score": "0", "body": "Until very recent standards of C++, the behavior of `%` for negative numbers was implementation-defined. I don't know if that's still true in C compilers. Historically, we avoided the negative value when implementing `itoa` etc. In any case, my comment was on the conditional branch needed to form the absolute value being in the middle of the loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T16:16:17.313", "Id": "521472", "Score": "0", "body": "Move to a precise `%` happened in C in 1999. [Sample](https://stackoverflow.com/a/56404008/2410359) code without a repetitive sign test." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T17:33:22.767", "Id": "521561", "Score": "0", "body": "@chux-ReinstateMonica: It's probably even better to use `0U - n` to get the `unsigned` absolute value without UB, instead of making it always-negative. Unsigned `n /= 10` is more efficient than signed for constant divisors; no sign fixup needed. Your linked [How do I fix my \\`itoa\\` implementation so it doesn't print reversed output?](https://stackoverflow.com/a/56404008) takes a runtime-variable `base` so it's slow unless it inlines into a caller that passes `10`. (glibc uses `switch(base)` with the same code for each of `case 8`/`10`/default, but that gets GCC to specialize a const base)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T17:59:21.510", "Id": "521567", "Score": "0", "body": "@PeterCordes With a compliant C implementation, `UINT_MAX == INT_MAX` is a possibility, (padding allowed) so `0U - n` does not function as needed. From a _practical_ view though, I agee 100.0%. I am cautious about introducing more types to solve an issue. (FWIW, I have only ever come across one machine, pre C99, where `ULONG_MAX == LONG_MAX`. Likely rusted away by now.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T18:02:29.403", "Id": "521568", "Score": "0", "body": "@chux-ReinstateMonica: Ok, good point. So you'd want to `_Static_assert(UINT_MAX > INT_MAX, \"here's a nickel, kid, get yourself a new compiler\")` or something to acknowledge that possibility." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T18:27:39.093", "Id": "521572", "Score": "1", "body": "@PeterCordes You may enjoy this collection of such asserts: [Detecting unicorn and dinosaur compilers](https://codereview.stackexchange.com/q/215113/29485) - only cost $0.05." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T15:02:20.197", "Id": "264017", "ParentId": "264012", "Score": "9" } }, { "body": "<p>The standard functions in <code>string.h</code> are not using <code>malloc</code> and <code>free</code> almost all. Therefore, the interface of <code>itoa</code> might be changed like this:</p>\n<pre><code>/* NG - because itoa returns a new memory */\nchar *itoa(int n) { ... }\n\n/* OK - because itoa uses an existing memory */\nvoid itoa(char *s, int n) { ... }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T22:14:44.127", "Id": "521408", "Score": "5", "body": "Completely rewriting OP's code does not constitute a code review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T15:02:52.713", "Id": "521456", "Score": "1", "body": "The suggested two parameter form is bad. What if somebody writes: `char s[2]; itoa(s,1000);` ? You need to either provide a length parameter or enforce a length, perhaps with a structure, like: `struct itoa_param { char buf[14]; }; extern void itoa(struct itoa_param *s, int n);` It also might be good to return the start of the string. This can simplify things be making the returned string not required to be the start of the buffer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T11:10:30.970", "Id": "521522", "Score": "0", "body": "Not so bad, I think. It's the same as `char s[2]; sprintf(s, \"%d\", n);`. Almost C standard functions are unsafe. For real safe programming, we know about the potential unsafeness of C language. In this case, we talk about memory leaks. Array boundary problem is also important but not now's topic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T15:09:28.943", "Id": "521548", "Score": "0", "body": "@HaruoWakakusa: That's why there is `snprintf`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T15:32:41.477", "Id": "264018", "ParentId": "264012", "Score": "3" } }, { "body": "<p>Besides lots of optimizations other people have suggested, you have two memory leaks.</p>\n<p>The first is that, just before the final return in itoa(), you need to write <code>free(digits);</code></p>\n<p>The second is in the error handling. (A common place for errors BTW.) In particular, if <code>getdigits</code> returns successfully, but the <code>malloc</code> fails, you leak <code>digits</code>. The fix: Test <code>digits</code> before the <code>malloc</code> and just return. Test <code>nbr</code> after the <code>malloc</code>, and <code>free(digits);</code> and return if it failed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T03:03:54.837", "Id": "521416", "Score": "1", "body": "I think this answer addresses the question better than the others, which are more focused on the implementation rather than the memory leaks the poster is concerned about." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T17:42:45.907", "Id": "521562", "Score": "0", "body": "You don't need an array of `int` digits in the first place, though, and if you do, it can be a local in automatic storage because the max digit-length of an `int` is small. Automatic storage is fast and immune to leaks. A local `char buf[sizeof(int)*CHAR_BIT / 3]` or something would make even more sense (the number of bits in an int / 3 is a loose bound on the max length). (edit: chux's answer already suggests that.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T22:53:00.783", "Id": "521585", "Score": "1", "body": "@PeterCordes Well, I did say \"lots of optimizations\". I wrote my answer just to spell out the leaks in the *current* code. Personally, for this functionality, I would make a local buffer as a `char` array, flll it from the right, and return `strdup()` of my final pointer. (I also wouldn't write this prototype&semantics.) As for the array size, I recommend adding 2, one for the trailing nul, and one for the leading minus sign. Especially since on a 16 bit int platform, your array would be 5 characters and there could be 5 digits, and similarly for a 32 bit int platform, 10 and 10." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T02:21:49.710", "Id": "264035", "ParentId": "264012", "Score": "7" } }, { "body": "<p><strong>Leak</strong></p>\n<p><code>digits</code> is never free'd.</p>\n<p>If either one of <code>digits</code> or <code>nbr</code> return <code>NULL</code>, the other allocation is lost.</p>\n<pre><code>digits = getdigits(n, digits_size);\n...\nnbr = malloc(digits_size + 1 * sizeof(char));\nif (nbr == NULL || digits == NULL)\n return (NULL);\n</code></pre>\n<p><strong>Concept error</strong></p>\n<p><code>sizeof(char)</code> is 1 so not much of a issue, yet <code>sizeof(char)</code> should multiply by the sum.</p>\n<pre><code>// malloc(digits_size + 1 * sizeof(char));\nmalloc((digits_size + 1) * sizeof(char));\n</code></pre>\n<p><strong>Simplification</strong></p>\n<p>Use a <code>do { } while();</code></p>\n<pre><code>//if (n == 0) return (1);\n//while (n != 0) {\n// n /= 10;\n// i++;\n//}\n\ndo {\n n /= 10;\n i++;\n} while (n != 0);\n</code></pre>\n<p><strong>Allocate to the refenced object</strong></p>\n<p>Rather than code the type, use the referenced object. Easy to code right, review and maintain.</p>\n<pre><code>// a = malloc(size * sizeof(int));\na = malloc(size * sizeof *a);\n</code></pre>\n<p><strong>Good use of <code>static</code> functions</strong></p>\n<p><strong>Use a local buffer for the reverse</strong></p>\n<p>No need to free it then either. <a href=\"https://stackoverflow.com/a/43788824/2410359\"><code>INT_STRING_SIZE</code> details</a></p>\n<pre><code>#define INT_STRING_SIZE ((sizeof(int)*CHAR_BIT - 1)*28/93 + 3)\n\n// int *digits;\nint digits[INT_STRING_SIZE];\n</code></pre>\n<p><code>digits</code> is now local storage and will be reclaimed on function exit. It's OK if it is more than needed for a given <code>n</code>, just as long as it can handle the worst case <code>n == INT_MIN</code>.</p>\n<p><strong>Simplified approach</strong></p>\n<blockquote>\n<p>Is there any way to optimize / secure the memory allocation so I do not get leaks?</p>\n</blockquote>\n<p>Yes. Form the string in a local buffer of worst case size (not an allocated one). Fill from right to left so no need for a later reverse. Now armed with the known size, allocate and <code>strcpy()</code>.</p>\n<pre><code>// Pseudo code\nchar *itoa_alloc(int n) {\n int n_origin = n;\n char buf[INT_STRING_SIZE];\n char *p = Address of end of buf\n *p = null character;\n\n do \n p--;\n *p = |n%10| + '0'; // Various ways to avoid repeated sign test exist\n n /= 10;\n } while (n != 0);\n\n if (n_origin &lt; 0)\n *(--p) = '-';\n char *s = malloc(end_of buf - p + 1);\n if (s == NULL) return NULL // Handle_error\n\n strcpy(s, p);\n // **OR**\n memcpy(s, p, end_of buf - p + 1);\n\n return s;\n}\n</code></pre>\n<p>With <a href=\"https://en.wikipedia.org/wiki/C2x\" rel=\"nofollow noreferrer\">C2x</a>, looks like <code>strdup()</code> may arrive and so could replace</p>\n<pre><code> char *s = malloc(end_of buf - p + 1);\n if (s == NULL) return NULL // Handle_error\n strcpy(s, p);\n return s;\n // **OR** C2x or select implementations today\n return strdup(p);\n</code></pre>\n<p><a href=\"https://stackoverflow.com/a/56404008/2410359\">Sample related code</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T17:48:06.197", "Id": "521563", "Score": "0", "body": "You have the length so you can use `memcpy` instead of `strcpy`. If you're going to str functions to favour simplicity over speed, you could just use `strdup` (although that POSIX, not ISO C)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T17:51:00.873", "Id": "521564", "Score": "0", "body": "You can do unsigned absolute value safely in C with `unsigned n = n<0 ? 0U - n : n;`, allowing you to hoist that work out of the loop and use more-efficient unsigned division. The implicit `(unsigned)n` conversion is guaranteed to use modulo-reduction to the range of `unsigned` without signed-overflow, correctly handling `INT_MIN` even on 2's complement systems." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T18:04:46.837", "Id": "521569", "Score": "0", "body": "@PeterCordes Note posted code, although C-like, is `// Pseudo code`. I did not want to give OP a cut/paste solution here, but a guide, to allow OP the specific coding experience. Agree about bring the test out of the loop and `memcpy()` and that is what is done in linked [sample](https://stackoverflow.com/a/56404008/2410359) with `return memcpy(dest, p, size_used);`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T07:07:56.467", "Id": "264042", "ParentId": "264012", "Score": "4" } }, { "body": "<p>You have used <code>static</code> for the helper functions, to give them internal linkage. That's good.</p>\n<hr />\n<blockquote>\n<pre><code> return (1);\n</code></pre>\n</blockquote>\n<p>The parentheses don't add any value here. Just write <code>return 1;</code> like everyone else.</p>\n<p>We can avoid the need to special-case <code>n == 0</code> by always performing at least one division; use <code>do</code>/<code>while</code> in place of <code>while</code>:</p>\n<pre><code>int i = 0;\ndo {\n n /= 10;\n ++i;\n} while (n);\n</code></pre>\n<p>The similar test in <code>getdigits()</code> can be eliminated in the same way.</p>\n<hr />\n<blockquote>\n<pre><code>int i = 0;\n\nwhile (i &lt; size / 2)\n{\n …\n i++;\n}\n</code></pre>\n</blockquote>\n<p>We have a construct that expresses that better:</p>\n<pre><code>for (int i = 0; i &lt; size / 2; ++i) {\n …\n}\n</code></pre>\n<p>The variable <code>tmp</code> doesn't need to be at function scope; it can be declared within the loop:</p>\n<pre><code>static int *revarray(int *a, int size)\n{\n for (int i = 0; i &lt; size / 2; ++i) {\n int tmp = a[i];\n a[i] = a[size - i - 1];\n a[size - i - 1] = tmp;\n }\n return a;\n}\n</code></pre>\n<hr />\n<blockquote>\n<pre><code> a = malloc(size * sizeof(int));\n</code></pre>\n</blockquote>\n<p>A convention that's often helpful is to write the size in terms of the pointer being assigned to. That helps readers immediately see that it's consistent, without having to look for the declaration of <code>a</code>:</p>\n<pre><code> a = malloc(sizeof *a * size);\n</code></pre>\n<p>I've written the <code>sizeof</code> expression first - it makes no difference here, but can avert overflow when there's a multiplication for the number of elements: <code>size_t * int * int</code> is safer than <code>int * int * size_t</code>.</p>\n<hr />\n<blockquote>\n<pre><code> a = revarray(a, size);\n</code></pre>\n</blockquote>\n<p>That's a pointless assignment, since <code>revarray()</code> returns the unchanged value of <code>a</code>. We should probably make <code>revarray()</code> return <code>void</code>.</p>\n<hr />\n<blockquote>\n<pre><code>digits = getdigits(n, digits_size);\nnbr = malloc(digits_size + 1 * sizeof(char));\nif (nbr == NULL || digits == NULL)\n return (NULL);\n</code></pre>\n</blockquote>\n<p>Oops - what if <code>digits</code> is a valid pointer, but <code>nbr</code> is null? Then we leak <code>digits</code>. We need a call to <code>free()</code> in there (remember that <code>free(NULL)</code> is defined, so it can be an unconditional <code>free(digits)</code>).</p>\n<p>Multiplying by <code>sizeof (char)</code> is a no-op: since <code>sizeof</code> yields values in units of <code>char</code>, it follows that <code>sizeof (char)</code> must be 1.</p>\n<hr />\n<blockquote>\n<pre><code> while (i &lt; digits_size)\n</code></pre>\n</blockquote>\n<p>Again, this should be a <code>for</code> loop:</p>\n<pre><code> for (int i = 0, j = 0; i &lt; digits_size; ++i, ++j)\n</code></pre>\n<hr />\n<p>We forgot to <code>free(digits)</code> before we return.</p>\n<hr />\n<p>As other reviewers have pointed out, the algorithm is inefficient, with the extra measuring and copying, and the reversal of digit order. I'll not repeat those observations here.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T07:23:27.643", "Id": "264043", "ParentId": "264012", "Score": "5" } }, { "body": "<blockquote>\n<p>Memory management and optimization is important.</p>\n</blockquote>\n<p>I will avoid any stylistic remark and focus on this particular aspect of your query.</p>\n<hr />\n<h2 id=\"memory-m1po\">Memory</h2>\n<p>First of all, the first rule of optimization is to avoid allocating memory. In general, memory allocation is slow-ish, and memory de-allocation even slower. In particular, most malloc implementation will perform &quot;consolidation&quot; work during the call to <code>free</code> which can take a few <em>milliseconds</em>. (The average case isn't that slow, but the worst case can be bad).</p>\n<p>As a result, <em>not</em> allocating is generally much faster than allocating. And if you do insist on allocating, at the very least you should only allocate <em>once</em> for the final result, and not allocate for any intermediate value.</p>\n<p>Hence the ideal API:</p>\n<pre><code>char* my_itoa(char* buffer, int i);\n</code></pre>\n<hr />\n<h2 id=\"number-of-digits-ysa7\">Number of digits</h2>\n<p>Your method is naive, and therefore slow.</p>\n<p>In general, division and modulo are the slowest arithmetic operations on a CPU. For x64, a 64-bits division is 30 to 90 cycles when an addition is 1 cycle and a multiplication 3 cycles. 32-bits divisions fare a bit better, but not by much.</p>\n<p>Of course, the compiler will perform strength reduction, and replace the division/modulo by a constant <a href=\"https://stackoverflow.com/questions/41183935/why-does-gcc-use-multiplication-by-a-strange-number-in-implementing-integer-divi\">with a series of additions/multiplications/shifts</a>... but even then it'll still be a slow-ish operation. (Especially for signed <code>int</code>)</p>\n<p>Luckily for you, there was a recent spree on Internet on the <a href=\"https://lemire.me/blog/2021/06/03/computing-the-number-of-digits-of-an-integer-even-faster/\" rel=\"nofollow noreferrer\">fastest way to compute the number of digits</a>.</p>\n<p>I have myself benchmarked this method, and its performance is truly good. It takes 3 CPU cycles (just like a single multiplication) regardless of the value of the integer. I would encourage simply using it:</p>\n<pre><code>/* Note: GCC builtin, other compilers should have an equivalent method\n to count the number of leading zeroes */\nint int_log2(uint32_t x) { return 31 - __builtin_clz(x|1); }\n\nint numberDigits(uint32_t x)\n{\n static uint64_t const TABLE[] = {\n 4294967296, 8589934582, 8589934582, 8589934582,\n 12884901788, 12884901788, 12884901788, 17179868184,\n 17179868184, 17179868184, 21474826480, 21474826480,\n 21474826480, 21474826480, 25769703776, 25769703776,\n 25769703776, 30063771072, 30063771072, 30063771072,\n 34349738368, 34349738368, 34349738368, 34349738368,\n 38554705664, 38554705664, 38554705664, 41949672960,\n 41949672960, 41949672960, 42949672960, 42949672960\n };\n return (int)((x + TABLE[int_log2(x)]) &gt;&gt; 32);\n}\n</code></pre>\n<hr />\n<h2 id=\"reversal-of-array-p4md\">Reversal of Array</h2>\n<p>This is mutually exclusive with computing the number of digits.</p>\n<p>In order to obtain the digits, you have to use <code>% 10</code> (or <code>% 100</code> to get them 2 by 2), and this means getting the lowest digits first.</p>\n<p>There are 3 strategies to deal with this:</p>\n<ul>\n<li>Write the digits in reverse order in a temporary array:\n<ul>\n<li>Either reverse them in place and bulk-copy them to the destination.</li>\n<li>Or copy them one at a time to the destination, reversing as you go.</li>\n</ul>\n</li>\n<li>Write the digits (as ASCII <code>char</code>, not <code>int</code>) in order in a large enough array, then bulk-copy them to the destination.</li>\n<li>Compute the number of digits, then write the digits in order in the destination, starting from the accurate final place.</li>\n</ul>\n<p>In general, the reversal strategy is the worse performance wise. Element-by-element manipulation loses out quickly as the number of elements go up.</p>\n<p>The difference between the last two hinges on the performance of bulk-copying vs computing the number of digits, and the latter should win if well-implemented.</p>\n<p>At the moment, you are using the worst possible combination: computing number of digits (slowly), discarding the result, and using the reversal strategy.</p>\n<p>That's a lot of unnecessary work; performance suffers accordingly.</p>\n<hr />\n<h2 id=\"performance-goal-qhmb\">Performance Goal</h2>\n<p>I was, in fact, just this week benchmarking our number-formatting routines, after implementing a variant of the faster &quot;number of digits&quot; computation.</p>\n<p>On my computer (4.6 GHz), formatting a <em>64 bits</em> unsigned integer with the algorithm I use takes:</p>\n<ul>\n<li>6 ns for <code>1</code>.</li>\n<li>14 ns for <code>UINT64_MAX</code></li>\n</ul>\n<p><em>Note: for reference <code>sprintf</code> takes 74 ns to do the same on my computer.</em></p>\n<p>There's nothing magic there:</p>\n<ol>\n<li>Compute number of digits: 1 ns/1.2 ns.</li>\n<li>Loop until 0, <code>% 100</code> at a time, writing in-place in the destination buffer.</li>\n<li>Handle last digit, if any.</li>\n</ol>\n<p>The destination buffer is user-provided, of course, to avoid any memory allocation.</p>\n<p>I would argue this is the order of magnitude you should aim for, if performance matters to you.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T17:08:55.893", "Id": "521557", "Score": "1", "body": "[How do I print an integer in Assembly Level Programming without printf from the c library?](https://stackoverflow.com/a/46301894) has some links at the bottom to blogs about fast itoa. (e.g. doing `x /= 100` steps and splitting that up, to gain some instruction-level parallelism.) https://pvk.ca/Blog/2017/12/22/appnexus-common-framework-its-out-also-how-to-print-integers-faster/ / https://tia.mat.br/posts/2014/06/23/integer_to_string_conversion.html" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T17:24:10.490", "Id": "521558", "Score": "0", "body": "Storing directly into the destination does nicely avoid store-forwarding stalls which costs latency. Note that out-of-order exec will overlap the num_digits latency with the multiply latency. `bsr` -> load -> `add` -> `shr` is at least 10 cycle latency on an Intel CPU (3 + 5 + 1 + 1), assuming L1d hit for the table. So not 1 ns, but performance of tiny sequences of instructions must be considered as latency and front-end / back-end throughput costs separately, not one-dimensional ns or cycles to add up. (I'd believe that it costs ~1 ns tput vs. a func that formats from the end of a buffer.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T17:26:23.167", "Id": "521559", "Score": "0", "body": "You might actually use an API like `char *atoi_end(char *buff_end, unsigned x);` to avoid needing to count at all (like in the asm Q&A I linked). glibc actually does that internally. But that's probably only useful if you're going to feed it to a syscall (like in the linked asm question) or a function like puts. \n If you were going to copy without truncating to a fixed length, you'd want to just do a normal atoi to write the digits to their final location." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T17:31:03.230", "Id": "521560", "Score": "0", "body": "I was trying to figure out if there was some use for a rougher inexact count, but if you keep the mallocing API it probably only makes sense if the string does start at the front of the buffer. So you need an exact count, either via a tmp buffer (length for free) and memcpy or ahead of allocation. Perhaps getting some multiply latency into the pipeline before the call to malloc could help some with latency. Using the calculated exact length as a loop termination condition could allow the loop-exit branch prediction to be checked earlier than the `x /= 10` dep chain.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T18:08:33.673", "Id": "521570", "Score": "0", "body": "\"fair a bit better\" -> \"fare a bit better\" :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T19:05:48.220", "Id": "521579", "Score": "1", "body": "@Dev: Eeek! Fixed, thanks." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T14:05:10.033", "Id": "264059", "ParentId": "264012", "Score": "5" } } ]
{ "AcceptedAnswerId": "264059", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T13:48:23.033", "Id": "264012", "Score": "5", "Tags": [ "c", "reinventing-the-wheel", "memory-management", "pointers", "memory-optimization" ], "Title": "Implementation of itoa which allocates the string" }
264012
<p>So I'm currently trying to learn more about events using C# and the example that I just write seems a bit.. It seems a bit too much? I feel like you could accomplish the same thing with way less code. I just have a hard time seeing why an event in this case would be useful? Maybe I just did it wrong.</p> <p>Is this a good way of using event? Could it be improved?</p> <pre><code>class Program { static void Main(string[] args) { Player player = new Player(); player.OnLevelUp += Player_OnLevelUp; Console.WriteLine(player.Level); for (int i = 0; i &lt; 10; i++) { player.SetXp(10); } Console.ReadLine(); } private static void Player_OnLevelUp(object sender, EventArgs e) { var player = (Player)sender; player.Level += 1; Console.WriteLine(&quot;You leveled up!&quot;); Console.WriteLine(player.Level); } } public class Player { public event EventHandler OnLevelUp; public string Name { get; set; } public int Level { get; set; } public int XP { get; set; } private int _nextLevelXp = 50; private void LevelUp() { OnLevelUp?.Invoke(this, EventArgs.Empty); } public void SetXp(int xp) { XP += xp; if (XP &gt;= _nextLevelXp) { LevelUp(); _nextLevelXp *= 2; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T14:51:45.893", "Id": "521374", "Score": "4", "body": "Events can shine whenever you have more than one consumer. So a single producer emits an event and many consumer can react on it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T23:41:40.677", "Id": "521410", "Score": "0", "body": "Also, the `SetXP` method should probably be named `AddXP` as it is not setting xp to a specific value, but incrementing xp by specific value" } ]
[ { "body": "<p>Events should report when something changed.</p>\n<p><em>edit</em> as pointed out events can be before or after. I'm just used to mainly dealing with after but events can happen before and some events that happen before even allow for the process to be cancelled. But the main point is events are fired for something happening and events don't make the change happen.</p>\n<p>In your example of levelup where the event is the one that actually increases the level property is extremely rare. I would go so far as saying incorrect.</p>\n<p>What typically happens is the Level property is increased then an event is fired to tell everyone that is listening to the level property changed. Maybe an item is available when a player is at a specific level and it only shows or is enabled at a specific level. That code could subscribe to the event and listen for when the player cross a specific level.</p>\n<p>Also the event args should be about the event that happen. Instead of EventArgs.Empty you could send out a custom event that would contain the event data that is important. In this case the player Name and level that was changed to.</p>\n<p>Events really shine to decouple when something happens to the consumer and when there are multiple consumers.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T22:05:48.583", "Id": "521406", "Score": "0", "body": "There are events that can be fired before, during, and after something has happened. What I agree with is that the logic of the level-up (the increment) should not be inside the event." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T22:09:26.170", "Id": "521407", "Score": "1", "body": "Good point. Events can be more than just after. After is just what I'm more a custom to. I'll update answer" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T20:51:30.477", "Id": "264031", "ParentId": "264015", "Score": "1" } }, { "body": "<h2>What you've done is conceptually wrong</h2>\n<p><strong>Events are there to allow other objects to be notified and react when something happens.</strong></p>\n<p>That said, your solution works and does what you want, at least at a first short glance, but it's misusing the event system for something it should not be doing.</p>\n<p>Events are there to allow objects with different responsibilities to react to the change of state of the originator.</p>\n<p>What you've done is moved the responsibility of the <code>player</code> class (the actual level-up - the incrementing of the level) to another class (<code>Program</code>). The <code>Program</code> has different responsibility than maintaining the inner state of the player.</p>\n<p>The <code>player</code> is a class that has its own state and methods that change it (the whole <code>SetXP</code> and <code>LevelUp</code> methods). The <code>Program</code> is just using those methods (and sometimes reading that state) to make the <code>player</code> do something and uses the event to manage its own responsibility, which is to write about the level up when it happens.</p>\n<p>The code just needs a small change and do something like:</p>\n<pre><code> private void LevelUp()\n {\n Level++; //this leaves the responsibility of leveling up to the Player\n OnLevelUp?.Invoke(this, EventArgs.Empty);\n }\n</code></pre>\n<p>and then leave the <code>OnLevelUp</code> as:</p>\n<pre><code> private static void Player_OnLevelUp(object sender, EventArgs e)\n {\n //this allows the Program to only be responsible for it's own state\n var player = (Player)sender;\n Console.WriteLine(&quot;You leveled up!&quot;);\n Console.WriteLine(player.Level);\n }\n</code></pre>\n<p>To be well enough formed.</p>\n<p><strong>Handle the LevelUp in the <code>LevelUp</code> method and then let the <code>Program</code> know through the <code>OnLevelUp</code> event and let the <code>Program</code> fulfil its responsibility by writing about it to the console.</strong></p>\n<hr />\n<h2>The SOLID principles</h2>\n<p>Now, since you're learning, let's make a bit more sense of what I'm saying.</p>\n<p>We programmers have some paradigms that we try to follow to make each other's lives easier. They are not unwritten - in fact, there are so many books about them it would fill a really large library.</p>\n<p>One of those paradigms that people, who work with object-oriented languages, will (or should) start learning as soon as reasonable are the SOLID principles.</p>\n<p>Those principles have really far-reaching consequences. We shouldn't be treating them like gospel and be holier than thou, but we should be aware of them.</p>\n<p>One of the <strong>SOLID</strong> principles is <strong>The Principle of Single Responsibility</strong> - a class/module/function should have one responsibility.</p>\n<p><em>It is a general rule and we should not take it too far, but it is a good, if abstract, rule.</em></p>\n<p>Under this principle - we call it <strong>SRP</strong> for short - the <strong>class <code>Player</code> is responsible for representing the player and his state</strong> and <strong>The <code>Program</code> is responsible for letting the user play the game (which includes using the methods exposed by the <code>player</code> class and writing about what's happening to the <code>Console</code> window)</strong>.</p>\n<p><strong>What you've done is violated this principle by letting the <code>Program</code> mess with the <code>player</code> directly.</strong></p>\n<p>The thing this practically achieves is <strong>Separation of Concerns</strong>. We separate the logic and state to the <code>Player</code> class that is responsible for it, and the logic of the game to another class that is responsible for its own thing and uses the separated logic through the interface (methods and properties and fields) it exposes.</p>\n<p><em>It is not such a big deal here, in a tutorial program. But, once you start working with large objects that have lots of properties and fields and need to maintain a complex state, it can be problematic.</em></p>\n<p><em>Especially when you don't have control over who will be using the class. Letting some unknown party do something to the state of your object without your control can be a disaster.</em></p>\n<p>Imagine you write a class that works as an HTTP client. It is complex and has a lot of events and properties and fields. But, you're not the one who will be using it. There will be some other programmer in this large team you're working in (or just someone using your library), who will be using it to do something - probably send an HTTP request and receive a response...</p>\n<p>Is it really a good idea to let him change the internal state of your client willy nilly? Or to make the other programmer responsible for changing the values your class is responsible for (your client's own internal status)?</p>\n<p>That's why the client has an event. Let the other programmer subscribe his methods to your event and let his classes react to the changes in the state of the client, but change the state with the methods you've written.</p>\n<p><strong>Also - there can be multiple consumers subscribed to the event.</strong></p>\n<p>If I start building on your example, there can be an object that draws the player on the screen (<code>Graphics</code>), and when the <code>OnLevelUp</code> is fired it, starts a level-up animation.</p>\n<p>Then there can be objects representing the <code>Fight</code> the player is in, that are subscribed to the <code>OnLevelUp</code> event. When he levels up, the hypothetical <code>Fight</code> class, responsible for the ongoing fight, might check if his opponents are too weak and might trigger them to try to flee from the player...</p>\n<p>In your case, it's the <code>Program</code> subscribing to the <code>Player</code>'s <code>OnLevelUp</code> event and writing about the change to the <code>Console</code> window. It is the responsibility of the <code>Program</code> to write everything on the screen. It is the responsibility of the <code>player</code> object to maintain its own state and represent a player.</p>\n<p>Of course, this is just an example. There are probably reasons why you might want to change the state of another object in an event. The pundits have probably already sharpened their pens, and gods willing, will inform us of them in their own answers. Your usage, however, is clearly not it.</p>\n<hr />\n<h2>WHY SO MUCH CODE</h2>\n<p>Well, mainly because the system needs to be universal enough for a lot of people to use.</p>\n<p>The whole program can be - of course - written with much less code, but it is just a tutorial example to let you know about how events work.</p>\n<p>It is like taking two perfectly good pieces of two by four and hammering a nail through them to show us how nailing works. In reality, you could also just glue them together or use a piece of string to tie them together, but the author wanted to show you nails and how they work...</p>\n<hr />\n<h2>POTENTIAL PROBLEMS</h2>\n<p>If you change the inner state of one object in another object in an uncontrolled manner, the problems will start to crop up as your program grows.</p>\n<p>Imagine you persist in that practice and have multiple classes that do this. Even relatively small programs devolve into a nightmare because you have to keep a tally of which class changes what in another class. Now imagine you have a hundred classes that do that...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-08T13:16:09.557", "Id": "525107", "Score": "1", "body": "Agree with you except that you cannot use operator \"=\" with event (Compilation error)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-12T18:27:47.580", "Id": "525424", "Score": "0", "body": "@AlexeyNis edited :) good catch" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T22:12:55.703", "Id": "264032", "ParentId": "264015", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T14:43:23.980", "Id": "264015", "Score": "0", "Tags": [ "c#", "event-handling" ], "Title": "is this a good way of using events?" }
264015
<pre><code># digit containing 9 has to be greater or equal in length mul9 = { str(i): str(9-i) for i in range(10)} print(f&quot;{mul9}\n&quot;) number1 = int(input(&quot;Enter 9s': &quot;)) len1 = len(str(number1)) number2 = int(input(f&quot;Enter (0 - {str(9)*len1}): &quot;)) if len(str(number1)) &lt; len(str(number2)): print(&quot;This trick won't work&quot;) else: res = str(number2 - 1) print(f&quot;{number2} - 1 = {res} &quot;) end = '' for i in res: end += mul9[i] print(f&quot;{i} needs {mul9[i]} to become 9&quot;) res += (len(str(number1)) - len(str(number2))) * &quot;9&quot; + end # This accounts for adding the invisible 0s at the start of 'res' in the video. I've simply added the correct number of 9s and avoided but avoided looping through them in the for loop. print(res) </code></pre> <p>gives</p> <pre><code>{'0': '9', '1': '8', '2': '7', '3': '6', '4': '5', '5': '4', '6': '3', '7': '2', '8': '1', '9': '0'} Enter 9s': 99 Enter (0 - 99): 99 99 - 1 = 98 9 needs 0 to become 9 8 needs 1 to become 9 9801 [Program finished] </code></pre> <p>The objective of the code is to demo students how we can multiply large numbers in smallest amount of time. I am new to python so not that aware of syntax. Works as expected. Can you please point out at lines which can be reduced.</p>
[]
[ { "body": "<ul>\n<li>Introduce some validation loops, rather than just bailing when the trick won't work</li>\n<li>Rephrase your outputs to be real equations - there's no reason not to</li>\n<li>Rearrange your digit storage order so that first things are added to a list first, and at the end call <code>join</code></li>\n<li>Beware your use of parens in your first prompt; this suggests an open interval when I think you want a closed interval. Your original meaning aside, I don't think that your <code>(0 - 99)</code> is actually supported - 0 crashes, so I'll suggest that you instead ask for a minimum of 1.</li>\n<li>Storing <code>mul9</code> as a dictionary is more effort than it's worth. Just calculate the difference for each digit.</li>\n<li>You might as well include a test to verify that your answer is correct.</li>\n<li>Explain how you get to the number of middle-9 digits.</li>\n</ul>\n<h2 id=\"suggested\">Suggested</h2>\n<pre><code>while True:\n number1 = input('Enter a number whose digits are all 9: ')\n if set(number1) == {'9'}:\n break\nlen1 = len(number1)\nnumber1 = int(number1)\n\nwhile True:\n number2 = input(f'Enter [1-{number1}]: ')\n len2 = len(number2)\n try:\n number2 = int(number2)\n except ValueError:\n continue\n if 0 &lt; number2 &lt;= number1:\n break\n\nres = number2 - 1\ndigits = [str(res), '9'*(len1 - len2)]\nprint(\n f'{number2} - 1 = {res}\\n'\n f'The difference of the input lengths '\n f'{len1}-{len2}={len1-len2} is the number '\n f'of &quot;9&quot; digits to insert in the middle'\n)\n\nfor str_i in str(res):\n i = int(str_i)\n mul9 = 9 - i\n digits += str(mul9)\n print(f'{i} + {mul9} = 9')\n\nans = int(''.join(digits))\nif number1 * number2 != ans:\n raise ValueError('Unexpected algorithm failure')\nprint(f'{number1} * {number2} = {ans}')\n</code></pre>\n<h2 id=\"output\">Output</h2>\n<pre><code>Enter a number whose digits are all 9: 9999\nEnter [1-9999]: 526\n526 - 1 = 525\nThe difference of the input lengths 4-3=1 is the number of &quot;9&quot; digits to insert in the middle\n5 + 4 = 9\n2 + 7 = 9\n5 + 4 = 9\n9999 * 526 = 5259474\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T17:49:52.953", "Id": "521385", "Score": "0", "body": "my code misses how ```9``` becomes part of final answer, so is urs.... i will debug that and thanks for suggestion" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T18:04:03.470", "Id": "521387", "Score": "0", "body": "@Subham done, though obviously this one isn't as easy to phrase in the form of an equation." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T17:29:33.927", "Id": "264025", "ParentId": "264019", "Score": "3" } } ]
{ "AcceptedAnswerId": "264025", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T15:42:38.720", "Id": "264019", "Score": "4", "Tags": [ "python-3.x", "mathematics" ], "Title": "Multiply by 9 without multiplying by 9, using vedic math" }
264019
<pre><code>add9 = [] add9.append(int(input(&quot;Enter 1st 4-digit no.: &quot;))) print(f&quot;The answer will be 2 and {str(add9[0])[0 :-1]} and {str(add9[0]-2)[-1]} = 2{add9[0]-2}&quot;) add9.append(int(input(&quot;Enter 2nd 4-digit no.: &quot;))) add9.append(9999-add9[1]) print(f&quot;The 3rd 4-digit is 9999 - {add9[1]}= {add9[2]}&quot;) add9.append(int(input(&quot;Enter 4th 4-digit no.: &quot;))) add9.append(9999-add9[3]) print(f&quot;The 5th 4-digit is 9999 - {add9[2]}= {add9[4]}&quot;) print(f&quot;&quot;&quot; So, {add9[0]}+{add9[1]} = {add9[0]+add9[1]} {add9[0]+add9[1]}+{add9[2]} = {add9[0]+add9[1]+add9[2]} {add9[0]+add9[1]+add9[2]}+{add9[3]} = {add9[0]+add9[1]+add9[2]+add9[3]} {add9[0]+add9[1]+add9[2]+add9[3]}+{add9[4]} = {add9[0]+add9[1]+add9[2]+add9[3]+add9[4]} &quot;&quot;&quot;) </code></pre> <p>gives</p> <pre><code>Enter 1st 4-digit no.: 9999 The answer will be 2 and 999 and 7 = 29997 Enter 2nd 4-digit no.: 2345 The 3rd 4-digit is 9999 - 2345= 7654 Enter 4th 4-digit no.: 6789 The 5th 4-digit is 9999 - 7654= 3210 So, 9999+2345 = 12344 12344+7654 = 19998 19998+6789 = 26787 26787+3210 = 29997 [Program finished] </code></pre> <p>Code works fine. It's for kids to demo how to produce output using 3 inputs from user. The trick is to subtract 9999 from 2nd and 3rd input from user. I have tried to use as small syntax as possible.</p> <p>Edit: 3rd and 5th digit are - 9999</p> <pre><code>Enter 1st 4-digit no.: 9990 The answer will be 2 and 999 and 8 = 29988 Enter 2nd 4-digit no.: 6667 The 3rd 4-digit is 9999 - 6667= 3332 Enter 4th 4-digit no.: 8888 The 5th 4-digit is 9999 - 3332= 1111 So, 9990+6667 = 16657 16657+3332 = 19989 19989+8888 = 28877 28877+1111 = 29988 [Program finished] </code></pre> <p>is working as expected</p> <p>From calculator,</p> <pre><code> Calculation 1 (1/1) 9,990. + (1/2) 6,667. = (1/3) 16,657. + (1/4) 3,332. = (1/5) 19,989. + (1/6) 8,888. = (1/7) 28,877. + (1/8) 1,111. = (1/9) 29,988. </code></pre>
[]
[ { "body": "<ul>\n<li>To start, I wouldn't put everything in a list. There are benefits to putting all five numbers in a sequence, but that needn't happen until the end</li>\n<li>You can expand your explanation for the &quot;answer&quot;. First, it's unclear what you mean by &quot;answer&quot;; it's actually the fourth sum. Also, you can expand your explanation for each of the terms going into this fourth sum. Some of the notation I've shown is perhaps a little advanced for kids, so simplify it at your discretion.</li>\n<li>You should be replacing your expressions at the bottom with a loop.</li>\n<li>Where possible, you should be phrasing your operations as mathematical (mod, floor division) rather than string-based.</li>\n<li>I think you have an algorithmic problem? When I enter <code>9990</code> for the first number, the predicted and actual fourth sum diverge.</li>\n</ul>\n<h2 id=\"suggested\">Suggested</h2>\n<pre><code>a = int(input(&quot;Enter 1st 4-digit no.: &quot;))\nsum4 = int(f'2{a//10}{(a - 2)%10}')\nprint(\n f&quot;The fourth sum will be the concatenation of:&quot;\n f&quot;\\n 2&quot;\n f&quot;\\n ⌊{a}/10⌋ = {a//10}&quot;\n f&quot;\\n mod({a} - 2, 10) = {(a - 2)%10}&quot;\n f&quot;\\n= {sum4}&quot;\n f&quot;\\n&quot;\n)\n\nb = int(input(&quot;Enter 2nd 4-digit no.: &quot;))\nc = 9999 - b\nprint(f&quot;The 3rd 4-digit no. is 9999 - {b} = {c}&quot;)\n\nd = int(input(&quot;Enter 4th 4-digit no.: &quot;))\ne = 9999 - d\nprint(f&quot;The 5th 4-digit no. is 9999 - {c} = {e}&quot;)\n\nnums = (a, b, c, d, e)\nprint('\\nSo,')\nfor i in range(4):\n addend = sum(nums[:i+1])\n augend = nums[i+1]\n print(f'{addend} + {augend} = {addend+augend}')\n</code></pre>\n<h2 id=\"output\">Output</h2>\n<pre><code>Enter 1st 4-digit no.: 9999\nThe fourth sum will be the concatenation of:\n 2\n ⌊9999/10⌋ = 999\n mod(9999 - 2, 10) = 7\n= 29997\n\nEnter 2nd 4-digit no.: 2345\nThe 3rd 4-digit no. is 9999 - 2345 = 7654\nEnter 4th 4-digit no.: 6789\nThe 5th 4-digit no. is 9999 - 7654 = 3210\n\nSo,\n9999 + 2345 = 12344\n12344 + 7654 = 19998\n19998 + 6789 = 26787\n26787 + 3210 = 29997\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T20:34:57.493", "Id": "264030", "ParentId": "264021", "Score": "0" } } ]
{ "AcceptedAnswerId": "264030", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T17:05:29.960", "Id": "264021", "Score": "1", "Tags": [ "python-3.x", "mathematics" ], "Title": "Game: Predict answer based on 3 user inputs, 2 self created inputs" }
264021
<p><a href="https://stackoverflow.com/questions/68364789/mix-javascript-debounce-not-plugin-with-jquery-event-handler">I asked this on StackOverflow</a> and was directed here...</p> <p>Instead of including a debounce plugin library for a very small form section of my site, I've implemented some of <a href="https://davidwalsh.name/javascript-debounce-function" rel="nofollow noreferrer">David Walsh's JavaScript Debounce Function</a> in my code to allow a small wait for slower user input, however I am binding it to the input field using jQuery instead of regular DOM event listener. The code works fine but my main question here is some peer input on if this is ok to do (will it cause unforeseen issues? is there a better method?) I couldn't find another example on this scenario on stack overflow but if it has been already asked, please do point me in the right direction.</p> <pre><code>$(function() { // debounce function by David Walsh function debounce(func, wait, immediate) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate &amp;&amp; !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; }; // allow .5s for slower user input before processing var debounceCustomInput = debounce(function() { // if both inputs valid if ($(&quot;#left&quot;).val().length &gt; 0 &amp;&amp; $(&quot;#right&quot;).val().length &gt; 0) { // process form myAjaxFunction(); } }, 500); // event binding $(document).on(&quot;input&quot;, &quot;#left,#right&quot;, function() { // debounce input debounceCustomInput(); }); }); </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T17:20:42.957", "Id": "264023", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "Mix JavaScript debounce (not plugin) with jQuery event handler?" }
264023
<p>Im currently working doing a webscrape which in my case if sydsvenskan but will be a template over time for other sites.</p> <p>I have currently done:</p> <pre><code>from typing import Optional import attr import requests from bs4 import BeautifulSoup from loguru import logger from requests import RequestException from requests.exceptions import ( ConnectionError, ConnectTimeout, ProxyError, ReadTimeout, ChunkedEncodingError, SSLError, Timeout ) @attr.dataclass class Data: store: str = attr.ib(factory=str) name: Optional[str] = attr.ib(factory=str) info: Optional[str] = attr.ib(factory=str) image: Optional[str] = attr.ib(factory=str) class Info: def from_page(url: str) -&gt; Data: while True: try: with requests.get(url) as response: if response.status_code == 404: return Data(store=&quot;Sydsvenskan&quot;) if response.ok: doc = BeautifulSoup(response.text, 'html.parser') else: response.raise_for_status() name = doc.select_one('span.prose-title') info = doc.select_one('div.article__preamble-wrapper') image = doc.select_one('img.article-image') return Data( store=&quot;Sydsvenskan&quot;, name=name.text.strip() if name else '', info=info.text.strip() if info else '', image=image['src'] if image else '', ) except ( ReadTimeout, Timeout, ConnectTimeout, ConnectionError, ChunkedEncodingError, SSLError, ProxyError ) as err: logger.info(f&quot;{type(err).__name__} at line {err.__traceback__.tb_lineno} of {__file__}: {err}&quot;) continue except RequestException as err: logger.exception(f&quot;{type(err).__name__} at line {err.__traceback__.tb_lineno} of {__file__},: {err}&quot;) raise RequestException from err except Exception as err: logger.exception(f&quot;{type(err).__name__} at line {err.__traceback__.tb_lineno} of {__file__},: {err}&quot;) raise Exception from err def main(): info = Info.from_page( url=&quot;https://www.sydsvenskan.se/2021-07-14/flera-anhallna-for-senaste-tidens-skjutningar-i-malmo&quot;) if info is None: logger.info('No new payload') else: logger.info(f'New payload: {info}') if __name__ == '__main__': main() </code></pre> <p>The current &quot;template&quot; I have created is meant to be able to add more news sites in the future and to be able to use this as a template. We do know that each site is different so we will never have any similar but the template should make it easy to adept in the future.</p> <p>I wonder if there is anything I can improve from here? I am mostly &quot;worried&quot; about the return of Data where I use the if else statement inside the dataclass, not sure if that is a correct way to do it?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T18:37:39.883", "Id": "521392", "Score": "0", "body": "Hi @Reinderien, Regarding the adopted stuff that you have taught me is still there. The reason I haven't added it here is due to I wanted to make it easy for the people to use the script where I am more curious about the scraping part where I use the dataclasses like you showed me before but without the dicts if you remember. The difference is that when we last spoke we or rather I didnt had the chance to ask if we find rhe webelement then we should return it with the dataclass and if not then return empty value and thats what I was looking for." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T18:39:14.870", "Id": "521393", "Score": "0", "body": "@Reinderien the context manager, the logging with discord notification and all that you have taught me is implemented but this was more a question regarding the \"If we find a webelement, then we take the text/href or whatever else it can be and if we dont find the element then return empty.\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T18:50:07.010", "Id": "521395", "Score": "0", "body": "@Reinderien I will work on a more real end to end scraper in that case :) Should I update this thread and create a new one for that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T08:42:02.697", "Id": "521431", "Score": "0", "body": "@Reinderien I have now updated the code and this is the real code I have been working on for a while with some pause in between. I hope this is much better compare from the beginning :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T17:56:52.663", "Id": "521565", "Score": "0", "body": "Does this scrape only a single page? Just 1?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T17:58:52.847", "Id": "521566", "Score": "0", "body": "@Mast Yes :) It should work in any sydsvenskan.se articles for now. :) Later on the point is to do a copy paste of this script and create for other sites such as bbc news etc etc..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T19:25:52.390", "Id": "521580", "Score": "0", "body": "For what Python version did you write this, Python 3.7? .8? .9?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T19:43:56.223", "Id": "521582", "Score": "1", "body": "@Mast Python 3.8 :) 3.8.2 to be exact" } ]
[ { "body": "<ul>\n<li>Your <code>attrs</code> should not need to have every single property decorated; there's an automatic mode</li>\n<li>On 404 returning a mostly-useless data instance seems like a bad idea.</li>\n<li>Your first tuple of exceptions contains classes that are all derived from <code>RequestException</code>. Is there a need to spell every one of them out? Why not just catch <code>RequestException</code> itself?</li>\n<li>You have a polling loop that continually <code>get</code>s from the server with no delay. That's not a very nice thing to do to a website. Best to add a delay.</li>\n<li>Separating <code>Info</code> and <code>Data</code> is not helpful, and <code>Info</code> on its own contains nothing that deserves to be a class. Just make <code>from_page</code> a class method on <code>Data</code> itself.</li>\n<li>There is no need to check for <code>.ok</code>. <code>raise_for_status</code> will unwind the stack and obviate any other logic.</li>\n</ul>\n<p><code>Data</code> can look like:</p>\n<pre><code>@attrs(auto_attribs=True, frozen=True, slots=True)\nclass Data:\n store: str\n name: Optional[str] = None\n info: Optional[str] = None\n image: Optional[str] = None\n\n @classmethod\n def from_page(cls, url: str) -&gt; 'Data':\n with requests.get(url) as response:\n response.raise_for_status()\n doc = BeautifulSoup(response.text, 'html.parser')\n\n name = doc.select_one('span.prose-title')\n info = doc.select_one('div.article__preamble-wrapper')\n image = doc.select_one('img.article-image')\n\n return cls(\n store=&quot;Sydsvenskan&quot;,\n name=name and name.text.strip(),\n info=info and info.text.strip(),\n image=image and image['src'],\n )\n</code></pre>\n<p>I suggest that your retry loop be in an outer method and not baked into <code>from_page</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T06:40:46.200", "Id": "521595", "Score": "0", "body": "Hi! Thanks for the awesome answer! The reason of exception for requestException is that if I use a bad proxy or a slow proxy in the future, there is a high chance it would throw timeout or any of those given exception I posted. What I wanted to do is to retry again instead of raising it. - I have a question. What is the difference between doing `name=name.text.strip() if name else ''` compare to yours where you use `and`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T16:22:51.703", "Id": "521634", "Score": "1", "body": "The `and` syntax defaults to `None` and short-circuits out the second half of the expression. IMO better that than an empty string, given that your member are marked `Optional`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T17:18:22.060", "Id": "521638", "Score": "0", "body": "Got it! Thanks! I agree. Will do that right away too!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T03:19:27.717", "Id": "264107", "ParentId": "264024", "Score": "3" } }, { "body": "<p><a href=\"https://codereview.stackexchange.com/a/264107/200133\">Reinderien's answer</a> is good and covers most of the points I was going to raise, but there are still some things that seem odd to me.</p>\n<p>Most contentiously, I'm skeptical that it makes sense for you to be using <code>attr</code>. This is not a library I'm previously familiar with, I had to track down <a href=\"https://www.attrs.org/en/stable/index.html\" rel=\"nofollow noreferrer\">the documentation</a> for it.</p>\n<ul>\n<li>It doesn't look like you're using any of the features attrs offers over <a href=\"https://docs.python.org/3.8/library/dataclasses.html\" rel=\"nofollow noreferrer\">dataclasses</a> (argument validation or sanitation; slotted classes).</li>\n<li>Both attrs and dataclasses have a <code>frozen</code> option which I feel pretty strongly <em>should</em> default to <code>True</code>.</li>\n<li>The API for attrs seems to be changing rather a lot from one version to the next. (They actually list this as an advantage, which is <em>ok</em>, but not an argument why you should use them.) In particular, you're using <code>attr.dataclass</code> (<a href=\"https://github.com/python-attrs/attrs/issues/408\" rel=\"nofollow noreferrer\">which was never part of the official api?</a> I can't find any other documentation of it), and Reinderien is using <code>attrs</code>, which <a href=\"https://www.attrs.org/en/stable/overview.html#on-the-attr-s-and-attr-ib-names\" rel=\"nofollow noreferrer\">is just an extra wrinkle for a new reader to work through</a>.</li>\n</ul>\n<p>Seconding some of Reinderien's points:</p>\n<ul>\n<li>Treat 404 as an error, not a dummy object.</li>\n<li>Don't poll too fast. If the first one fails, trying again too soon can make the problem <em>worse</em>; I suggest a 2-second delay. Also don't poll indefinitely; I would usually have the number of attempts be configurable and default to <em>two</em>.</li>\n<li><code>Info</code> as a separate class is pointless.</li>\n</ul>\n<p>Further points:</p>\n<ul>\n<li>The class name <code>Data</code> isn't great. <code>PageData</code> could be ok. If this is specific to sydsvenskan then call it <code>SydsvenskanData</code> or something.</li>\n<li>This is supposed to be a template system for various sites, right? What's the &quot;template&quot; part (that's the same across sites) and what's the sydsvenskan-specific part? Keep these clearly and cleanly separate from each other, so that the site-specific stuff can be swapped out seamlessly. Is that why you had a distinct <code>Info</code> class? If so, just have a top-level method, but make sure it's clearly associated with the site it's supposed to be used on.</li>\n<li>Reinderien implies that you should move your exception handling up out of your <code>Data</code>-builder function. Clearly you need two layers, with retry-logic somewhere higher and the <code>Data(...)</code> call at the bottom. In keeping with my above point, all of the <code>requests</code> stuff should go in the higher layer with exception-handling and retry-logic; the <code>Data</code>-builder function should take a <code>BeautifulSoup</code> object as its argument.</li>\n<li>Will this mostly be used from the command line, or as a library? In both cases try to expose more of the options to the caller. For example, <a href=\"https://docs.python.org/3.8/library/argparse.html\" rel=\"nofollow noreferrer\">the <code>argparse</code> library</a> takes some work to understand, but is well worth learning if you want to write CLI tools.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T13:25:02.850", "Id": "521610", "Score": "0", "body": "Thank you so much for the answer aswell! Much much appreciated! Don't really know where to start honestly but I agree on everything. 1. Regarding the dataclass, I dont believe I can argue anything there as I have learned mostly from Reinderien and of course there is still improvents to do but good to know!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T13:26:33.177", "Id": "521611", "Score": "0", "body": "2. Regarding the 404 and all other status you are also right, I should only handle the 200 and then the rest of the status code should be handled by a raise. Polling data was meant to be sleeping much longer than 2 seconds as I feel like I might ddos even thought they have good system probably but still. Good point! I agree with the class name isn't great either as I do find PageData to be much better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T13:28:21.273", "Id": "521612", "Score": "0", "body": "3. Regarding the template, The specific part is meant that I scrape different values (webelements) for sydsvenskan compare to bbc news e.g. I guess thats the difference and who knows what other difference other sites has for difference than just webelements. Nothing I can say now already but maybe that gave you some more clearity?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T13:30:03.610", "Id": "521613", "Score": "0", "body": "4. The exception handling, I assume you meant that I should do the exception inside the `main()` when calling `from_page` ? instead of having it inside the from_page function? If I understood you both right? and yes. Later on it will be a command line where Ic an use argparse to say which \"site\" i want to start monitoring. - Thats it for me :) Waiting for reply!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T13:52:49.200", "Id": "521620", "Score": "1", "body": "A lot of design decisions depend on _how_ the thing will be used. But one way or another it seems like you should have a function for making the requests and handling all the ways that can fail, and another function that builds a `Data` based on a `BeautifulSoup`. A function called `main` should be responsible for CLI usage of the script." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T16:27:59.300", "Id": "521635", "Score": "0", "body": "Agreed on all points. Use built-in dataclasses when possible. I have the misfortune of having to maintain a product on 3.6 that doesn't have them, so under some circumstances attrs are your only option." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T17:23:52.493", "Id": "521639", "Score": "0", "body": "Small question regarding the built-in dataclasses, do you referer to your example as you have provided with the @attrs before? or is it something I might missed?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T17:31:33.123", "Id": "521640", "Score": "0", "body": "As you mentioned regarding @attrs because of 3.6, how would it look like if you ran with higher than 3.6? Any examples? " }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T18:21:00.760", "Id": "521642", "Score": "2", "body": "I'm pretty sure if you start with `from dataclasses import dataclass` instead of `from attr import attrs` (as in @Reinderien;s example), then `@dataclass(frozen=True)` will be a drop-in replacement for `@attrs(auto_attribs=True, frozen=True)`, _for your purposes_. (You'll notice that I left out `slots`; dataclasses doesn't have any comparable option. The libraries are _very similar_, but not _the same_." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T07:20:40.660", "Id": "521668", "Score": "0", "body": "Thank you both! I wished I could split the bounty to give you each 50/50 :( You guys have been amazing!" } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T13:18:58.647", "Id": "264116", "ParentId": "264024", "Score": "2" } } ]
{ "AcceptedAnswerId": "264107", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T17:26:41.070", "Id": "264024", "Score": "1", "Tags": [ "python", "python-3.x" ], "Title": "Scraping webelements if found" }
264024
<p>I'm working on a programming exercise (university, nothing related to industry) which basically asks to implement a Buffer to be used by two threads (a producer and a consumer). The first one enqueues data calling <code>next(T t)</code>, while the other gets the oldest value (in a FIFO mechanism) calling <code>consume()</code> or waits if the buffer is empty. The producer can send a stop signal to declare the enqueuing ended. The text also requires a <code>fail()</code> method in case anything goes wrong, but I'd like to ignore it for this question. This is my solution</p> <pre><code>template &lt;typename T&gt; class Buffer { std::mutex m; std::condition_variable cv; std::queue&lt;T&gt; values; bool stop, failed; std::exception_ptr _eptr; public: Buffer() : stop(false), failed(false) {} void fail (const std::exception_ptr &amp;eptr){ { std::unique_lock ul{m}; failed = true; _eptr = eptr; } cv.notify_all(); } void terminate(){ { std::unique_lock ul {m}; if (stop || failed ) throw std::runtime_error(&quot;enqueing has stopped&quot;); stop = true; } cv.notify_one(); // notify stop signal } void next(T t) { { std::unique_lock ul{m}; if ( stop || failed ) throw std::runtime_error (&quot;enqueing has stopped&quot;); values.push(t); } cv.notify_one(); // notify the consumer (if waiting) } std::optional&lt;T&gt; consume(){ std::unique_lock ul{m}; cv.wait(ul, [this]() { return !values.empty() || stop || failed; }); if (values.empty()) { // if got notified and the queue is empty, then stop or failed have been sent if (stop) return std::nullopt; else std::rethrow_exception(_eptr); } // extract the value to consume T val = values.front(); values.pop(); return std::optional&lt;T&gt;(val); } }; </code></pre> <p>This is how I think the Buffer might be used (I'm still ignoring the <code>fail()</code> method)</p> <pre><code>#define N 10000 Buffer&lt;int&gt; buf; std::thread prod([&amp;buf](){ for(int i = 0 ; i &lt; N; ++i) { std::cout &lt;&lt; &quot;enqueing: &quot; &lt;&lt; i &lt;&lt; std::endl; buf.next(i); } buf.terminate(); }); std::thread cons([&amp;buf](){ for(int i = 0; i &lt; N; ++i) std::cout &lt;&lt; &quot;consuming: &quot; &lt;&lt; buf.consume().value() &lt;&lt; std::endl; }); prod.join(); cons.join(); </code></pre> <p>I got some questions:</p> <ul> <li><p>do you agree this is nothing but a blocking queue or am I missing something ?</p> </li> <li><p>do I need to implement the destructor ? If it is the case, can you please show me an example of usage that requires having it?</p> </li> <li><p>What happens if the object goes out of scope and nobody called <code>terminate()</code> ? Should I take care of this problem ? Is it anyway a <code>Buffer</code> 's problem or the programmer using this class should care about it ? Can you please show me an example when this happens (I was thinking about the threads being detached instead of joined, does it fit ?) ?</p> </li> </ul>
[]
[ { "body": "<p>Yup. Looks like a queue. Maybe all multithreading is really a queue? ... <em>strokes beard philosophically</em></p>\n<hr />\n<p>Naming:</p>\n<ul>\n<li><code>terminate()</code> should probably be called <code>finished()</code> or <code>done()</code> or something similar. (To distance it from <code>std::terminate</code>). <code>stop()</code> would also be wrong, since that implies we're telling the threads to stop processing regardless of whether there's more input. What we're really saying is simply that there's no more input to process.</li>\n<li><code>next()</code> should be called <code>push()</code>... because that's what it does.</li>\n<li><code>consume()</code> would be better named something like <code>wait_and_pop()</code>.</li>\n</ul>\n<hr />\n<pre><code>void terminate(){\n {\n std::unique_lock ul {m};\n if (stop || failed ) throw std::runtime_error(&quot;enqueing has stopped&quot;);\n stop = true;\n }\n cv.notify_one(); // notify stop signal\n}\n</code></pre>\n<p>I don't think we need to throw an error if the queue is already stopped (or failed). We can just do nothing and return. (Similar to calling close on a file that's already closed. It's not wrong, there's just nothing to do). Especially since we have no way to check if the queue is currently stopped!</p>\n<p>(It might be worth adding an <code>bool is_stopped() const</code>. Note that making this function <code>const</code> would mean making the mutex a <code>mutable</code> variable (which is fine)).</p>\n<p>We should call <code>notify_all</code> instead of notify one. We presumably want all threads to stop waiting promptly.</p>\n<p>We could use <code>std::lock_guard</code> instead of <code>std::unique_lock</code> (we don't need any of the extra functionality of <code>std::unique_lock</code>).</p>\n<hr />\n<pre><code>void next(T t) {\n {\n std::unique_lock ul{m};\n if ( stop || failed ) throw std::runtime_error (&quot;enqueing has stopped&quot;);\n values.push(t);\n }\n cv.notify_one(); // notify the consumer (if waiting)\n}\n</code></pre>\n<p>We could use <code>std::move</code> when pushing the value onto the queue: <code>values.push(std::move(t));</code>.</p>\n<p>Again, we could use <code>std::lock_guard</code> instead of <code>std::unique_lock</code>.</p>\n<hr />\n<pre><code>std::optional&lt;T&gt; consume(){\n std::unique_lock ul{m};\n cv.wait(ul, [this]() { return !values.empty() || stop || failed; });\n if (values.empty()) { // if got notified and the queue is empty, then stop or failed have been sent\n if (stop)\n return std::nullopt;\n else\n std::rethrow_exception(_eptr);\n }\n // extract the value to consume\n T val = values.front();\n values.pop();\n return std::optional&lt;T&gt;(val);\n}\n</code></pre>\n<p>Here we do need <code>std::unique_lock</code>. :)</p>\n<p>Again we can do <code>T val = std::move(values.front());</code></p>\n<p>I'm not sure the logic here is quite correct. If the <code>failed</code> flag is set, we probably need to do something about it even if the queue <em>isn't</em> empty? (I don't know what your spec says though).</p>\n<hr />\n<p>Destruction:</p>\n<p>Yep, we need a destructor. It's quite possible for the <code>Buffer</code> to be destroyed while consumer threads are still trying to read from it. A contrived example:</p>\n<pre><code>auto consumers = std::vector&lt;std::thread&gt;();\n\n{\n auto buf = Buffer&lt;int&gt;();\n\n for (auto i = 0; i != 5; ++i)\n consumers.emplace_back([&amp;] () { while (true) { auto value = buf.consume(); if (!value) return; std::cout &lt;&lt; value.value(); } });\n\n for (auto i = 0; i != 5000; ++i)\n buf.next(i);\n \n buf.terminate();\n\n} // buf goes out of scope here! but we don't know that consumers have finished consuming!\n\nfor (auto&amp; c : consumers)\n c.join();\n</code></pre>\n<p>We have two choices:</p>\n<ul>\n<li>Make this an obvious programming error (print an error message to <code>std::cerr</code> and call <code>std::terminate</code> if necessary (when <code>failed</code> isn't set, or when <code>stop</code> is set, but the queue isn't empty).</li>\n<li>Make it less dangerous (assume that input is finished and we want to finish processing it, so set <code>stop</code> in the destructor and then wait for the queue to be empty).</li>\n</ul>\n<p>I think the second option is better - depending on whether threads have finished work as an error condition may end up calling <code>std::terminate</code> quite randomly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T11:34:05.340", "Id": "521440", "Score": "0", "body": "I don't get why using your example, the program exits with 0 and the expected output even if the buffer went out of scope.\nNotice: I replaced the `while(true)` with a `for` iterating N tiems and I only introduced 1 consumer and 1 producer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T15:32:13.450", "Id": "521464", "Score": "0", "body": "It's undefined behavior, so it might work, or it might not. Maybe the consumer finished quickly, maybe the consumer is still accessing memory that has the right values in it even though the buffer is destroyed... etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T22:31:58.987", "Id": "521490", "Score": "0", "body": "You should probably get in the habit of using `scoped_lock`, rather than `lock_guard`. It *usually* doesn’t make a difference, but when it does, it *really* does. So why have yet another special case? Why create the problem of having to explain when to use one or the other? Just “forget” `lock_guard`—remember it as yet another failed experiment, like `auto_ptr`, that ultimately became obsolete by new and better technologies—and now the only rule you need to remember is “just do `auto lock \n= std::scoped_lock{mutex}`”." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T08:02:57.453", "Id": "521513", "Score": "0", "body": "@indi. I guess. I'm just following the advice here: https://stackoverflow.com/a/60172828" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T09:36:06.480", "Id": "264048", "ParentId": "264026", "Score": "1" } } ]
{ "AcceptedAnswerId": "264048", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-13T18:50:26.997", "Id": "264026", "Score": "6", "Tags": [ "c++", "multithreading" ], "Title": "C++ producer-consumer using blocking buffer" }
264026
<p>I am learning Python and managed to accomplish the above. But my script doesn't seem optimal. Could someone help to take a review and suggest for betterment?</p> <pre><code>import boto3 from datetime import datetime,timedelta REGION = &quot;ap-southeast-1&quot; retention_days = 45 account_id = boto3.client('sts').get_caller_identity().get('Account') ec2 = boto3.client('ec2', region_name=REGION) def lambda_handler(event, context): now = datetime.now() outdated_snapID = [] retain_snapID = [] result = ec2.describe_snapshots(OwnerIds=[account_id]) for snapshot in result['Snapshots']: # Remove timezone info from snapshot in order for comparison to work below snapshot_time = snapshot['StartTime'].replace(tzinfo=None) # Subtract snapshot time from now returns a timedelta # Check if the timedelta is greater than retention days if (now - snapshot_time) &gt; timedelta(retention_days): outdated_snapID.append(snapshot['SnapshotId']) retain_snap = ec2.describe_snapshots(OwnerIds=[account_id], Filters=[{'Name': 'tag:Retain', 'Values': ['True', 'true']}]) for snap in retain_snap['Snapshots']: # Remove timezone info from snapshot in order for comparison to work below snapshot_time = snap['StartTime'].replace(tzinfo=None) if (now - snapshot_time) &gt; timedelta(retention_days): retain_snapID.append(snap['SnapshotId']) # Remove retained snapshotID's from the outdated array for i in retain_snapID: outdated_snapID.remove(i) for x in outdated_snapID: delete_snapshot(x) def delete_snapshot(snapshotID): try: ec2.delete_snapshot(SnapshotId=snapshotID) except Exception as ex: print(&quot;Something went wrong:&quot;, ex) pass <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>For a beginners' project, the code is well formulated, comments are short and to the point. I'll list out a few things which might help you, but are specific to your requirements.</p>\n<hr />\n<h2>Environment variables</h2>\n<p>AWS populates an environment variable called <code>AWS_REGION</code> for its lambda execution environments. If your function is operating in the same region as the lambda is defined, you can leverage this instead of hardcoding the <code>REGION</code> and thereby making the function operable across regions without any changes.</p>\n<p>Similarly, you can populate the <code>RETENTION_DAYS</code> (name constants using <code>CAPITAL_SNAKE_CASE</code>) via env vars.</p>\n<h2>Client/service resource</h2>\n<p>I'm a huge supporter of the newer service resource API over the low-level client for boto3 operations. They are lazy loaded, have better support for pagination and more pythonic.</p>\n<p>Check the documentation for <a href=\"https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#service-resource\" rel=\"nofollow noreferrer\">the same here</a>.</p>\n<h2>Duplicated task</h2>\n<p>You have 2 loops, iterating over all snapshots, and then over filtered snapshots (for retention). They both require the same computation of <code>snapshot_time</code> and checking with retention limit. Perhaps, a function to check if <code>snapshot</code> is worthy of retention, and proceed accordingly would be better?</p>\n<h2>List vs set/tuple/dict</h2>\n<p>You know for sure that you only need to work with snapshot IDs, which are guaranteed to be unique. Using list for storage, and later calling <code>.remove</code> on list is not performant.</p>\n<p>A better performance can be achieved if you use a set or tuple for storing the ids (since removal would be <span class=\"math-container\">\\$ O(1) \\$</span> cost); however, if you plan to go with service resource, using a dictionary to map <code>id</code> to the snapshot resource would be my advice.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T09:33:29.133", "Id": "269220", "ParentId": "264034", "Score": "1" } } ]
{ "AcceptedAnswerId": "269220", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T02:19:17.573", "Id": "264034", "Score": "3", "Tags": [ "python", "python-3.x", "lambda", "amazon-web-services" ], "Title": "Delete older EBS Volume snapshots except few with certain tags using Python, Lambda" }
264034
<p>I am implementing a callback method to replace the use of generics.</p> <p>For maximum performance, it is not allowed to use <code>Box</code> and I also don’t want to use <code>dyn FnMut(T) -&gt; Ret</code> as that introduces <code>vtable</code>.</p> <p>So I decided to write a non-owning <code>ErasedFnPointer</code> that stores the function pointer and the pointer to the <code>struct</code> if the function pointer is an associated function.</p> <p>It isn’t that difficult since associated function in rust is just regular function.</p> <p>In order to make it smaller, I uses <code>transmute</code> to convert <code>fn(&amp;self, T) -&gt; Ret</code> to <code>fn(*mut c_void, T) -&gt; Ret</code>, which does run, however I am not so sure about its correctness.</p> <p>I also wonder whether there exists other approach that is more performant and more compact.</p> <pre class="lang-rust prettyprint-override"><code>use core::ffi::c_void; use core::mem::transmute; use core::ptr::null_mut; use core::marker::PhantomData; /// ErasedFnPointer can either points to a free function or associated one that /// `&amp;mut self` struct ErasedFnPointer&lt;'a, T, Ret&gt; { struct_pointer: *mut c_void, fp: *const (), // The `phantom_*` field is used so that the compiler won't complain about // unused generic parameter. phantom_sp: PhantomData&lt;&amp;'a ()&gt;, phantom_fp: PhantomData&lt;fn(T) -&gt; Ret&gt;, } impl&lt;'a, T, Ret&gt; ErasedFnPointer&lt;'a, T, Ret&gt; { pub fn from_associated&lt;S&gt;(struct_pointer: &amp;'a mut S, fp: fn(&amp;mut S, T) -&gt; Ret) -&gt; ErasedFnPointer&lt;'a, T, Ret&gt; { ErasedFnPointer { struct_pointer: struct_pointer as *mut _ as *mut c_void, fp: fp as *const (), phantom_sp: PhantomData, phantom_fp: PhantomData, } } pub fn from_free(fp: fn(T) -&gt; Ret) -&gt; ErasedFnPointer&lt;'static, T, Ret&gt; { ErasedFnPointer { struct_pointer: null_mut(), fp: fp as *const (), phantom_sp: PhantomData, phantom_fp: PhantomData, } } pub fn call(&amp;self, param: T) -&gt; Ret { if self.struct_pointer.is_null() { let fp = unsafe { transmute::&lt;_, fn(T) -&gt; Ret&gt;(self.fp) }; fp(param) } else { let fp = unsafe { transmute::&lt;_, fn(*mut c_void, T) -&gt; Ret&gt;(self.fp) }; fp(self.struct_pointer, param) } } } fn main() { let erased_ptr = ErasedFnPointer::from_free(|x| { println!(&quot;Hello, {}&quot;, x); x }); erased_ptr.call(2333); println!(&quot;size_of_val(erased_ptr) = {}&quot;, core::mem::size_of_val(&amp;erased_ptr)); ErasedFnPointer::from_associated( &amp;mut Test { x: 1}, Test::f ).call(1); let mut x = None; ErasedFnPointer::from_associated(&amp;mut x, |x, param| { *x = Some(param); println!(&quot;{:#?}&quot;, x); }).call(1); } struct Test { x: i32 } impl Test { fn f(&amp;mut self, y: i32) -&gt; i32 { let z = self.x + y; println!(&quot;Hello from Test, {}&quot;, z); z } } <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T04:52:54.170", "Id": "264040", "Score": "4", "Tags": [ "rust", "generics", "pointers" ], "Title": "A safe type-erased Fn Pointer in rust that can be used to call associated and regular function" }
264040
<p>I have service class which loads data from external service. This service needs API key which loads from db and unique for every user.</p> <pre><code>public class GoogleCloudService { private readonly ILogger&lt;GoogleCloudService&gt; logger; public GoogleCloudService(string key) { Key = key; logger = Startup.ServiceProvider.GetService&lt;ILogger&lt;GoogleCloudService&gt;&gt;(); } public string Key { get; set; } public async Task&lt;string&gt; ImageTextRecognizeAsync(byte[] imageBytes, string type = &quot;TEXT_DETECTION&quot;, string languageHints = &quot;en-t-i0-handwrit&quot;) { string url = &quot;https://vision.googleapis.com/v1/images:annotate&quot; + &quot;?key=&quot; + Key; using (var client = new HttpClient()) { try { var values = new { requests = new[] { new { image = new { content = Convert.ToBase64String(imageBytes) }, features = new[] { new { type = type } }, imageContext = new { languageHints = new[] { languageHints } } } } }; var response = await client.PostAsJsonAsync(url, values); try { response.EnsureSuccessStatusCode(); var jsonSettings = new JsonSerializerOptions(); jsonSettings.Converters.Add(new DynamicJsonConverter()); dynamic responseJson = await response.Content.ReadFromJsonAsync&lt;dynamic&gt;(jsonSettings); if (responseJson is not null &amp;&amp; responseJson.responses is not null &amp;&amp; responseJson.responses[0] is not null &amp;&amp; responseJson.responses[0].fullTextAnnotation is not null) { return responseJson.responses[0].fullTextAnnotation.text; } else { return null; } throw new HttpRequestException(); } catch (Exception ex) { ex.Data.Add(&quot;Request&quot;, await response.RequestMessage.ToRawAsync()); ex.Data.Add(&quot;Response&quot;, await response.ToRawAsync()); throw; } } catch (Exception ex) { logger.LogError(ex, &quot;Возникла ошибка при отправке запроса в Google Cloud.&quot;); } } return null; } } </code></pre> <p>and usage:</p> <pre><code>var gService = new GoogleCloudService(entityDB.GoogleApiKey); string text = await gService.ImageTextRecognizeAsync(imageBytes); </code></pre> <p>Everything works fine, but I think using global ServiceProvider from static Startup.ServiceProvider is not a good idea. How can I eliminate service locator pattern and configure service key dynamically by user in code? What are best practices?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T07:58:27.490", "Id": "521425", "Score": "0", "body": "`public GoogleCloudService(string key, ILogger<GoogleCloudService> logger)` - the constructor must accept one more parameter" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T08:00:45.777", "Id": "521426", "Score": "0", "body": "[HttpClient](https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=net-5.0#remarks) is intended to be instantiated once and re-used throughout the life of an application." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T10:13:33.143", "Id": "521435", "Score": "0", "body": "Problem not in a HttpClient - it's just an example. Problem in using dependency injection with other params from DB." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T15:33:27.617", "Id": "521465", "Score": "2", "body": "Please do not edit the question, especially the code after an answer has been posted. Everyone needs to be able to see what the reviewer was referring to. [What to do after the question has been answered](https://codereview.stackexchange.com/help/someone-answers)." } ]
[ { "body": "<p>why not use <code>Request</code> headers?</p>\n<p>You can register the <code>IHttpContextAccessor</code> service at <code>Startup</code> :</p>\n<pre><code>public void ConfigureServices(IServiceCollection services)\n{\n services.AddControllers();\n\n //register IHttpContextAccessor\n services.AddHttpContextAccessor();\n}\n</code></pre>\n<p>now, configure your service to construct with <code>IHttpContextAccessor</code> :</p>\n<pre><code>public class GoogleCloudService\n{\n private readonly ILogger&lt;GoogleCloudService&gt; _logger;\n private readonly IHttpContextAccessor _httpContextAccessor;\n\n public GoogleCloudService(IHttpContextAccessor httpContextAccessor, ILogger&lt;GoogleCloudService&gt; logger)\n {\n _httpContextAccessor = httpContextAccessor;\n _logger = logger;\n \n // Get apiKey\n Key = httpContextAccessor.HttpContext.Request.Headers[&quot;apiKey&quot;];\n }\n \n // ..etc.\n}\n</code></pre>\n<p>now, everything can be configured from the controllers side. Suppose you need to validate the header and do some extra action based on it for every request, to do that, we can add a <code>FilterAction</code> and register it, something like this :</p>\n<pre><code> // this filter will be executed on each request. \npublic class ApiKeyFilterAttribute : ActionFilterAttribute\n{\n public async override Task OnActionExecutionAsync(ActionExecutingContext context , ActionExecutionDelegate next)\n { \n // get ApiKey \n var ApiKey = context.HttpContext.Request.Headers[&quot;ApiKey&quot;];\n \n if(string.IsNullOrWhiteSpace(ApiKey))\n {\n // the apiKey is lost or user is not authenticated\n // redirect user to the proper page \n }\n \n // what you need to do with the ApiKey ?\n // do some async actions ..etc. \n await base.OnActionExecutionAsync(context, next);\n }\n}\n</code></pre>\n<p>now, register this filter at <code>Startup</code> :</p>\n<pre><code>public void ConfigureServices(IServiceCollection services)\n{\n services.AddControllersWithViews(options =&gt;\n {\n options.Filters.Add(new ApiKeyFilterAttribute());\n });\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T15:11:52.047", "Id": "521458", "Score": "0", "body": "The ApiKey is not obtained from the request and has nothing to do with authorization. It is in the database. I am making requests to a remote service using user keys on their behalf. The question is not the key, but how to organize dependency injection with passing different parameters." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T15:22:11.833", "Id": "521460", "Score": "0", "body": "@sDima I see now, so you need a way to use DI for passing different parameters that would be initialized from the database to be reused across the project ? is that what you ask for ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T15:27:30.620", "Id": "521461", "Score": "0", "body": "Yes, exactly, I have updated the example for clarity. I know I can just add a service to a dependency container with a default constructor and manually assign each property before each use, but is that the right approach?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T16:09:36.767", "Id": "521469", "Score": "0", "body": "@sDima if i'm following your correctly, I think you're looking for `IOptions` service, which you can bind your class of parameters, and reuse it where you needed through DI. Have you thought about it ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T05:19:18.310", "Id": "521504", "Score": "0", "body": "IOptions is static, but I need the ability to call the service in a loop with different parameters." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T14:20:31.590", "Id": "521540", "Score": "0", "body": "@sDima you can use `IOptionsSnapshot` then, this is a scoped service, and can be updated on each request." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T05:18:15.043", "Id": "521593", "Score": "0", "body": "How to use IOptionsSnapshot in a scenario like this:\n`foreach (var entityDB in entities)\n {\n var gService = new GoogleCloudService(entityDB.GoogleApiKey);\n string text = await gService.ImageTextRecognizeAsync(entityDB.ImageBytes);\n }`" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T11:44:03.807", "Id": "264055", "ParentId": "264041", "Score": "0" } }, { "body": "<p>Here are my observations:</p>\n<ul>\n<li><code>Startup.ServiceProvider.GetService&lt;ILogger&lt;GoogleCloudService&gt;&gt;();</code>: As you might know Inversion of Control are usually achieved either via Dependency Injection or via Service Locator. The later one <a href=\"https://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/\" rel=\"nofollow noreferrer\">should be avoided</a> if possible. So, please prefer Dependency Injection:</li>\n</ul>\n<pre><code>public class GoogleCloudService\n{\n private readonly ILogger&lt;GoogleCloudService&gt; logger;\n\n public GoogleCloudService(string key, ILogger&lt;GoogleCloudService&gt; logger)\n {\n Key = key;\n this.logger = logger;\n }\n</code></pre>\n<ul>\n<li><p><code>public string Key { get; set; }</code>: Do you really need to expose this as public? Do you really need to allow external modification?</p>\n<ul>\n<li>If no then <code>private readonly string key</code> would be sufficient or if you stick to property then <code>private string Key { get; init; }</code></li>\n</ul>\n</li>\n<li><p><code>using (var client = new HttpClient())</code>: You don't need to create and <a href=\"https://www.aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/\" rel=\"nofollow noreferrer\">dispose an HttpClient</a> for each and every request. Please prefer a static <code>HttpClient</code> per domain or use <code>HttpClientFactory</code> if you can.</p>\n</li>\n<li><p><code>Convert.ToBase64String(imageBytes)</code>: I would suggest to perform some sort of preliminary check to make sure that <code>imageBytes</code> are not <code>null</code> and contains some data</p>\n</li>\n<li><p><code>var jsonSettings = new JsonSerializerOptions();</code> This could be declared as static because this is not changing from request to request</p>\n</li>\n<li><p><code>await response.Content.ReadFromJsonAsync&lt;dynamic&gt;</code>: Try to avoid deserializing data into <code>dynamic</code>. Please create a concrete class, which could be used as the contract between your client and the service provider. <code>dynamic</code> can hide a lot of problems</p>\n</li>\n<li><p><code>responseJson.responses[0] is not null</code>: This might cause <code>OutOfRangeException</code> if the <code>responses</code> is defined but empty. Please check the collection's length as well prior accessing a member directly</p>\n</li>\n<li><p><code>throw new HttpRequestException();</code>: According to my understanding you will never reach this code. The <code>else</code> block is also unnecessary:</p>\n</li>\n</ul>\n<pre><code>if (responseJson is not null \n &amp;&amp; responseJson.responses is not null \n &amp;&amp; responseJson.responses.Length &gt; 0\n &amp;&amp; responseJson.responses[0] is not null \n &amp;&amp; responseJson.responses[0].fullTextAnnotation is not null)\n{\n return responseJson.responses[0].fullTextAnnotation.text;\n}\n\nreturn null;\n</code></pre>\n<ul>\n<li><code>ex.Data.Add(&quot;Request&quot;, await response.RequestMessage.ToRawAsync());</code> Capturing the whole request-response might be expensive if their body are too lengthy. It might make sense to truncate them. Please bear in mind that you already have <code>values</code> variable which contains the request body. Please also bear in mind that you are not capture headers, which might contain valuable information</li>\n<li><code>catch(Exception ex)</code>: You can get rid of the outer try-catch if you perform preliminary checks</li>\n</ul>\n<pre><code>if(imageBytes == null || (imagesBytes != null &amp;&amp; imagesBytes.Length &lt; 1))\n return ...\n\nvar values = new ...\nvar response = await client.PostAsJsonAsync(url, values);\n\ntry\n{\n response.EnsureSuccessStatusCode();\n ...\n {\n return responseJson.responses[0].fullTextAnnotation.text;\n }\n return null;\n}\ncatch (Exception ex)\n{\n ex.Data.Add(&quot;Request&quot;, await response.RequestMessage.ToRawAsync());\n ex.Data.Add(&quot;Response&quot;, await response.ToRawAsync());\n\n logger.LogError(ex, &quot;Возникла ошибка при отправке запроса в Google Cloud.&quot;);\n}\n</code></pre>\n<hr />\n<p><strong>UPDATE</strong>: Reflect to comment</p>\n<p>You can create a Factory method which is responsible for creating <code>GoogleCloudService</code> instances. You can take advantage <code>ILoggerFactory</code> (<a href=\"https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.iloggerfactory\" rel=\"nofollow noreferrer\">Reference</a>) to avoid Service Locator.</p>\n<pre><code>public class GoogleCloudServiceFactory: ICloudServiceFactory\n{\n private readonly ILoggerFactory loggerFactory;\n public GoogleCloudServiceFactory(ILoggerFactory loggerFactory)\n {\n this.loggerFactory = loggerFactory;\n }\n\n public ICloudService Create(string key)\n {\n return new GoogleCloudService(key, loggerFactory);\n }\n}\n</code></pre>\n<p>Usage</p>\n<pre><code>foreach (var entityDB in entities) \n{ \n ICloudService gService = serviceFactory.Create(entityDB.GoogleApiKey); \n string text = await gService.ImageTextRecognizeAsync(entityDB.ImageBytes); \n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T05:13:48.543", "Id": "521592", "Score": "0", "body": "Thanks for your reply. My question is how to use the service without service locator in a scenario like this:\n`foreach (var entityDB in entities)\n {\n var gService = new GoogleCloudService(entityDB.GoogleApiKey);\n string text = await gService.ImageTextRecognizeAsync(entityDB.ImageBytes);\n }`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T06:20:36.280", "Id": "521594", "Score": "0", "body": "@sDima I've extended my post to reflect to your question. Please check it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T07:31:16.023", "Id": "264086", "ParentId": "264041", "Score": "1" } } ]
{ "AcceptedAnswerId": "264086", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T06:39:51.950", "Id": "264041", "Score": "1", "Tags": [ "c#", "dependency-injection", "asp.net-core", ".net-core" ], "Title": "Configure service with user-related parameters in .NET Core dependency injection" }
264041
<p>I have a 3-D array in numpy, of dimensions 3000 x 2000 x 8</p> <p>I need to modify the cells of the array so that each cell will contain the sum of all cells above and left of it, inclusive the current cell.</p> <p>I am doing it using loops like below, but it is taking around 5 minutes to complete the program run. Is there a faster way in Python to achieve this (preferably without a loop)?</p> <pre><code>for depth in range(simg.shape[2]): for row in range(1,simg.shape[0]-1): for col in range(1,simg.shape[1]-1): simg[row,col,depth]=simg[row-1,col,depth]+simg[row,col-1,depth]+simg[row,col,depth]-simg[row-1,col-1,depth] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T08:21:28.403", "Id": "521428", "Score": "1", "body": "You should provide code which is ready to be executed if we copy/paste to our IDE. How can we help you if you don't help us ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T15:12:20.897", "Id": "521459", "Score": "0", "body": "Seems like you want a convolution with a custom kernel. numpy and scipy offer fast implementation of such functions. Try searching about convolution or 2d convolution. Seems like you want a 3x3 kernel like [[0,1,0],[1,1,0],[0,0,0]]" } ]
[ { "body": "<p>I used integral function from openCV.\nIt worked fast (within a second)!</p>\n<blockquote>\n<p>iimg=cv.integral(simg)</p>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T07:06:21.603", "Id": "264084", "ParentId": "264044", "Score": "0" } } ]
{ "AcceptedAnswerId": "264084", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T07:40:12.350", "Id": "264044", "Score": "0", "Tags": [ "python", "numpy" ], "Title": "Slow calculating sum of individual cells of matrix" }
264044
<p>In my database, I have table <code>wp_postmeta</code>, example:</p> <pre><code>| meta_key | meta_value | post_id | --------------------------------- points | 12 | 23 points | 2 | 18 lorem | ipsum | 92 points | 8 | 15 </code></pre> <p>I want to order <code>points</code> by <code>meta_value</code> and get the row number of a specific <code>post_id</code>. Basically a rank system, with highest number at the top.</p> <p>For example, ordering <code>points</code> by <code>meta_value</code>:</p> <pre><code>| meta_key | meta_value | post_id | --------------------------------- points | 12 | 23 points | 8 | 15 points | 2 | 18 </code></pre> <p><code>post_id</code> with value <code>15</code> will be <strong>rank 2</strong>.</p> <p>What SQL query can I run to achieve this <em>with</em> optimisation in mind?</p> <h2 id="what-ive-tried-so-far">What I've tried so far</h2> <p>I have achieved this via query:</p> <pre><code>$query=&quot; SELECT post_id,FIND_IN_SET( post_id,(SELECT GROUP_CONCAT( post_id ORDER BY meta_value * 1 DESC) FROM $wpdb-&gt;postmeta WHERE meta_key ='points') ) AS `rank` FROM $wpdb-&gt;postmeta WHERE meta_key ='points' AND post_id = '&quot;.$post_id.&quot;' &quot;; $result = $wpdb-&gt;get_row($query); $rank = $result-&gt;rank; </code></pre> <p>Works fine. <em>However</em>, this query is very slow.</p> <p>How can I make this query faster?</p> <p>EDIT: Here is a list of indexes in this table:</p> <p><a href="https://i.stack.imgur.com/ymd38.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ymd38.png" alt="enter image description here" /></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T09:03:20.367", "Id": "521432", "Score": "0", "body": "Doesn't mysql now have `ROW_NUMBER()`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T09:17:18.880", "Id": "521433", "Score": "1", "body": "@choroba Can you please post an answer using `ROW_NUMBER()` with my code as reference?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T10:11:06.687", "Id": "521434", "Score": "0", "body": "I don't believe that there is enough context to actually answer this question. What are the inputs? What indexes do you have on the table? Please read the SQL tag wiki and provide the requested information. Note also that for many applications (e.g. a top ten list), it would be better to select the rank as part of the listing query." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T10:57:36.437", "Id": "521439", "Score": "0", "body": "@mdfst13 List of indexes in this table: https://i.imgur.com/QReQbZj.png" } ]
[ { "body": "<p>Mysql supports the ROW_NUMBER() function.</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT rank\nFROM (\n SELECT ROW_NUMBER() OVER (ORDER BY meta_value) AS rank,\n meta_key, meta_value, post_id\n FROM wp_postmeta\n WHERE meta_key = 'points'\n) AS r\nWHERE post_id = 18;\n</code></pre>\n<p>But I'm not sure it performs any better than your solution.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T10:42:55.723", "Id": "521436", "Score": "0", "body": "Thanks. I ran a speed test on this vs my original approach, and there is barely any difference unfortunately. Is there an approach where the query will perform better?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T10:44:30.997", "Id": "521437", "Score": "0", "body": "Do you have any indices defined on the table?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T10:49:41.600", "Id": "521438", "Score": "0", "body": "Yes, this is the current index setup of this table: https://i.imgur.com/QReQbZj.png" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T09:32:22.573", "Id": "264047", "ParentId": "264045", "Score": "0" } }, { "body": "<p>I would create a <a href=\"https://stackoverflow.com/q/609343/6660678\">covering index</a> on <code>meta_key</code>, <code>meta_value</code>, <code>post_id</code> and see if that helps.</p>\n<p>Note that you currently only have a prefix key on the meta_key column. So you will probably have to make both meta_key and meta_value prefixes and you may have to limit them to a combined length of 186 (assuming you need 20 for the post_id). That certainly works for the example, where you could get by with</p>\n<pre><code>CREATE INDEX meta_key_value_post_id_idx ON wp_postmeta ( meta_key(7), meta_value(21), post_id )\n</code></pre>\n<p>You may or may not need longer values for <code>meta_value</code> and/or <code>meta_key</code> for other queries. But if you only ever query for 'points' and it always has numeric values with twenty digits or fewer, this should work. Because it's enough to match points uniquely (7 bytes is more than the six one-byte characters in points, so it won't match things like pointsa) and numeric values (less than twenty ASCII digits).</p>\n<p><a href=\"https://stackoverflow.com/q/2357620/6660678\">This post</a> may help you determine what the maximum value length in the column is. E.g.</p>\n<pre><code>SELECT MAX(LENGTH(meta_value)) FROM wp_postmeta WHERE meta_key = 'points';\n</code></pre>\n<p>Note: this is assuming you use <a href=\"https://codereview.stackexchange.com/a/264047/71574\">@choroba's version</a>. I'm not sure that the index will help with <code>GROUP_CONCAT</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T13:49:20.510", "Id": "264058", "ParentId": "264045", "Score": "0" } }, { "body": "<p>you could make use of variables and subqueries, something like this <a href=\"http://sqlfiddle.com/#!9/196528/5\" rel=\"nofollow noreferrer\">SQLFiddle</a>:</p>\n<pre><code>SET @rank := 0;\nSELECT post_id, rank\nFROM (\n SELECT *, @rank := @rank + 1 rank\n FROM (\n SELECT \n post_id, \n meta_value * 1 meta_value\n FROM \n wp_postmeta \n WHERE\n meta_key ='points'\n ) a \n ORDER BY meta_value desc\n) e\nWHERE \n post_id = 15\n</code></pre>\n<p>this will return :</p>\n<pre><code>| post_id | rank |\n|---------|------|\n| 15 | 2 |\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T23:17:30.573", "Id": "269278", "ParentId": "264045", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T08:37:25.410", "Id": "264045", "Score": "3", "Tags": [ "sql", "mysql", "wordpress" ], "Title": "Order a table by column and get row number" }
264045
<pre><code>print(&quot;This trick only works for range 10 to 199 included&quot;) num1 = int(input(&quot;Enter 1st no.:&quot;)) num2 = int(input(&quot;Enter 2nd no.:&quot;)) max1 = max(num1, num2) min1 = min(num1, num2 ) cond = (min1 &gt; 9) and (max1 &lt; 200) def print2(res1, res2): res3 = num1+num2-100 res4 = (num1-100) * (num2 -100) print(f&quot;&quot;&quot; Step 1 : {num1} is {num1-100} greater than 100 And {num2} is {num2-100} greater than 100 Hence, The first 2 digits are 100+({num1-100})+({num2-100}) = {res3} The last digits are {num1-100} * {num2 -100} = {res4} Total {res1}{res2} &quot;&quot;&quot;) def print1(res1, res2): print(f&quot;&quot;&quot; Step 1 : {num1} is {num1-100} greater than 100 And {num2} is {num2-100} greater than 100 Hence, The first 3 digits are 100+({num1-100})+({num2-100}) = {res1} The last 2 digits are {num1-100} * {num2 -100} = {res2} Total {res1}{res2} &quot;&quot;&quot;) def check_len(res1, res2): if len(str(res2)) &lt; 2: res2 = str(0)+str(res2) print1(res1, res2) elif len(str(res2)) &gt; 2: res1 = res1 + int(str(res2)[:-2]) res2 = str(res2)[-2:] print2(res1, res2) def main(num1, num2): res1 = num1 + num2 - 100 res2 = (num1-100)*(num2-100) if cond: if num1 == num2 == 100: print(10000) elif max1 &lt; 100: if len(str(res2)) == 2: res2 = str(res2)[-2:] print2(res1, res2) else: check_len(res1,res2) elif min1 &gt; 100: if len(str(res2)) == 2: print1(res1, res2) else: check_len(res1,res2) else : res1 = max1 - 100 res2 = min1 - 100 res3 = (min1 + res1) * 100 res4 = res1*res2 print(f&quot;&quot;&quot; Step 1 : {max(num1, num2)} - {100} = {res1} Step 2 : ({num2} + {res1}) + 00 = {res3} Step 3 : {res1} x {res2} = {res4} Total {res3}+({res4}) = {res3+res4} &quot;&quot;&quot;) else: print(&quot;This trick won't work&quot;, num1, num2) exit(0) main(num1, num2) </code></pre> <p>Example 1: When the numbers are less than 100</p> <pre><code>This trick only works for range 10 to 199 included Enter first number:56 Enter second number:67 Step 1 : 56 is -44 greater than 100 And 67 is -33 greater than 100 Hence, The first 2 digits are 100+(-44)+(-33) = 23 The last digits are -44 * -33 = 1452 Total 3752 [Program finished] </code></pre> <p>Example 2: When greater than 100</p> <pre><code>This trick only works for range 10 to 199 included Enter first number:110 Enter second number:120 Step 1 : 110 is 10 greater than 100 And 120 is 20 greater than 100 Hence, The first 2 digits are 100+(10)+(20) = 130 The last digits are 10 * 20 = 200 Total 13200 [Program finished] </code></pre> <p>Example 3: One is smaller and one is greater than 100</p> <pre><code>This trick only works for range 10 to 199 included Enter first number:126 Enter second number:98 Step 1 : 126 - 100 = 26 Step 2 : (98 + 26) + 00 = 12400 Step 3 : 26 x -2 = -52 Total 12400+(-52) = 12348 [Program finished] </code></pre> <p>We cannot change the output as kids might not understand technical jargon Although, I admit its not that well formatted. I tried my best. The purpose is for kids to check stepwise where they are wrong.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T11:28:07.737", "Id": "521524", "Score": "0", "body": "I grew up in a generation where the essence was taught first. Any short-cuts were perhaps mentioned in passing and - if so - certainly afterwards. If the goal is to teach kids how to perform arithmetical computations quickly, just teach them how to install a calculator-app. I'm obviously biased, but if the goal is to teach kids arithmetic to get them started on the road of mathematics/logic in general, get the essence ingrained first, not the tricks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T13:23:36.613", "Id": "521531", "Score": "0", "body": "in a competitive exam, you have to know trick, bcos calc not allowed. it's better if we teach them from start, rather than learning at later age" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T18:23:21.463", "Id": "521571", "Score": "0", "body": "if num1 in cond and num2 in cond: - is this working?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T18:35:10.980", "Id": "521573", "Score": "0", "body": "refactored the code but forgot to do other necessary changes... sorry, correction done" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T11:40:32.213", "Id": "521789", "Score": "0", "body": "@Subham: I question the validity of evaluating the question (solely) in the context of competitive exams, but even there \"calcs\" are allowed (you're allowed to calculate anything using the machinery of your brain). I can't imagine a (serious) competitive exam where employing a trick that work on a 200/∞ ᵗʰ of all integers and (moreover) is computationally just as efficient as the real deal has merit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T13:52:51.737", "Id": "521791", "Score": "0", "body": "[https://afeias.com/faq/can-candidates-use-calculators-upsc-civil-services-exam/] Please read the first statement. Anyways its student who wanted me to make a project using python. I was able to help them with as much python I knew. There are many such tricks on YouTube. By statistics, this particular trick gives extra 15sec per calculation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-23T11:12:30.813", "Id": "521999", "Score": "0", "body": "@Subham If I follow the afeias-link of your previous comment it says \"Uh-Oh! It looks like you are lost!\" so I can't read the first statement (unless that was it). If they removed the page out of ethical reasons (because \"teaching tricks over techniques\" is bad, or \"speed is more important than understanding\" is wrong), I'm ok with that. Just to make sure: don't assume my opinion is personally addressed to you. It's not. Like you, I would have enjoyed coding something students requested." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-23T16:35:12.807", "Id": "522031", "Score": "0", "body": "Google search if calc is allowed for IAS exams India. It will say Not for UPSC Civil Services Preliminary Exam." } ]
[ { "body": "<pre><code>print(&quot;This trick only works for range 10 to 199 included&quot;)\n\nnum1 = int(input(&quot;Enter 1st no.:&quot;))\nnum2 = int(input(&quot;Enter 2nd no.:&quot;))\n\nmax1 = max(num1, num2)\nmin1 = min(num1, num2 )\n\n\nCOND = (min1 &gt; 9) and (max1 &lt; 200)\n\ndef print2(res1, res2):\n res3 = num1+num2-100\n res4 = (num1-100) * (num2 -100)\n print(f&quot;&quot;&quot; \nStep 1 : \n{num1} is {num1-100} greater than 100\nAnd\n{num2} is {num2-100} greater than 100\nHence, \nThe first 2 digits are 100+({num1-100})+({num2-100}) = {res3}\nThe last digits are {num1-100} * {num2 -100} = {res4}\n\nTotal {res1}{res2}\n &quot;&quot;&quot;)\ndef print1(res1, res2):\n print(f&quot;&quot;&quot; \nStep 1 : \n{num1} is {num1-100} greater than 100\nAnd\n{num2} is {num2-100} greater than 100\nHence, \nThe first 3 digits are 100+({num1-100})+({num2-100}) = {res1}\nThe last 2 digits are {num1-100} * {num2 -100} = {res2}\nTotal {res1}{res2}\n &quot;&quot;&quot;)\n \ndef check_len(res1, res2):\n if len(str(res2)) &lt; 2:\n res2 = str(0)+str(res2)\n print1(res1, res2) \n \n elif len(str(res2)) &gt; 2:\n res1 = res1 + int(str(res2)[:-2])\n res2 = str(res2)[-2:]\n print2(res1, res2) \n \n \n\ndef main(num1, num2):\n res1 = num1 + num2 - 100\n res2 = (num1-100)*(num2-100)\n\n if not COND:\n print(&quot;This trick won't work&quot;, num1, num2)\n return \n \n if num1 == 100 and num2 == 100:\n print(10000)\n return \n \n if max1 &lt; 100:\n if len(str(res2)) == 2:\n res2 = str(res2)[-2:]\n print2(res1, res2)\n return \n check_len(res1,res2) \n return \n \n if min1 &gt; 100: \n if len(str(res2)) == 2: \n print1(res1, res2) \n return \n check_len(res1,res2)\n return\n \n res1 = max1 - 100\n res2 = min1 - 100\n res3 = (min1 + res1) * 100\n res4 = res1 * res2\n print(f&quot;&quot;&quot; \nStep 1 : {max(num1, num2)} - {100} = {res1}\nStep 2 : ({num2} + {res1}) + 00 = {res3}\nStep 3 : {res1} x {res2} = {res4}\nTotal \n{res3}+({res4}) = {res3+res4}\n&quot;&quot;&quot;)\n \n \nmain(num1, num2)\n\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T17:05:05.667", "Id": "264122", "ParentId": "264046", "Score": "0" } } ]
{ "AcceptedAnswerId": "264122", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T09:20:12.110", "Id": "264046", "Score": "2", "Tags": [ "python-3.x", "mathematics" ], "Title": "Multiplication without multiplication for numbers in range 10-199, Vedic Maths" }
264046
<p>I have many stacks with the same navigation options, how do I abstract the navigationOptions part to have it repeat in all my stacks?</p> <pre><code>export const MakePaymentStack = createStackNavigator( { PaymentsBpayNewScreen, PaymentsBpayNewAmountScreen, }, { ...defaultNavStyle, initialRouteName: APP_SCREENS.PaymentsBpayNewScreen, }, ); (MakePaymentStack as any).navigationOptions = () =&gt; ({ animationEnabled: true, gesturesEnabled: false, // disable swipe down to dismiss on iOS }); </code></pre> <p>and like that all the others</p> <pre><code>export const StatementsStack = createStackNavigator( { StatementPdfScreen, }, { ...defaultNavStyle, initialRouteName: APP_SCREENS.StatementPdfScreen, }, ); (StatementsStack as any).navigationOptions = () =&gt; ({ animationEnabled: true, gesturesEnabled: false, // disable swipe down to dismiss on iOS }); </code></pre> <p>So how can I abstract the &quot;navigationOptions&quot;?</p> <p>Thanks in advance</p>
[]
[ { "body": "<p>What I would suggest is to wrap createStackNavigator in another function where you mimic the api but with different defaults.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T18:31:45.097", "Id": "264067", "ParentId": "264049", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T10:04:09.970", "Id": "264049", "Score": "1", "Tags": [ "javascript", "react.js", "typescript", "react-native" ], "Title": "abstract navigationOptions react navigation" }
264049
<h3 id="problem-statement-x2nr">Problem Statement</h3> <p>I need to access a <strong>deeply nested object</strong>. I could've used a 3rd party util such as <strong><a href="https://lodash.com/" rel="nofollow noreferrer">Lodash</a></strong> but insisted myself on writing a <strong>Vanilla JS</strong> solution with a <strong>recursive strategy</strong>.</p> <h3 id="code-4yeg">Code</h3> <p>Can this solution be <strong>improved</strong> with a <strong>better</strong> and <strong>more efficient</strong> approach? Is there any <strong>edge case</strong> which has been missed and could break the 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>const obj = { foo: { bar: { baz: "value" } } }; const getPathValue = (object, path) =&gt; { if ( // ======= object checks ======= // object === null || object === undefined || typeof object !== "object" || // ======= path checks ======= // path === null || path === undefined || path.length === 0 ) { return undefined; } // key -&gt; current key // rest -&gt; rest of the keys in path const [key, ...rest] = path; // value of current key const value = object[key]; // if rest of the keys are exhausted &amp; // a value is found, return the value if (rest.length === 0 &amp;&amp; value) { return value; } // as rest of key are not exhaused yet // in the path, keep traversing deeper return getPathValue(value, rest); }; // ======= test cases with object edge cases ======= // console.log(getPathValue()); // undefined console.log(getPathValue(null)); // undefined console.log(getPathValue(undefined)); // undefined // ======= test cases with path edge cases ======= // console.log(getPathValue(obj, [])); // undefined console.log(getPathValue(obj, null)); // undefined console.log(getPathValue(obj, [1, 2, 3])); // undefined console.log(getPathValue(obj, ["non exisiting key"])); // undefined console.log(getPathValue(obj, ["foo", "non exisiting key"])); // undefined console.log(getPathValue(obj, ["foo", "bar", "baz", "non exisiting key"])); // undefined console.log(getPathValue(obj, ["foo", "non exisiting key", "bar", "baz"])); // undefined // ======= normal test case ======= // console.log(getPathValue(obj, ["foo", "bar", "baz"])); // value</code></pre> </div> </div> </p>
[]
[ { "body": "<h2 id=\"recursion-ugma\">Recursion</h2>\n<p>There are many reasons to avoid recursion in JavaScript.</p>\n<ul>\n<li><p>Recursion is an inefficient way to implement simple loops.</p>\n<p>Generally you use recursion to follow tree like paths where the path is dynamic or unknown, in this case the path is pre-determined and there is no need to stack the previous loop state as you iterate.</p>\n</li>\n<li><p>A strong argument to NEVER use recursion is that JS has a limited call stack, but that same argument also means NEVER call a function (You may be at the end of the call stack) which is a ridiculous requirement.</p>\n<p>Until JS supports tail call optimization you should always use a loop in preference to recursion</p>\n</li>\n</ul>\n<h2 id=\"argument-vetting-xgzw\">Argument vetting</h2>\n<p>The argument vetting too complex and can be simplified to <code>typeof object === &quot;object&quot; &amp;&amp; object !== null &amp;&amp; Array.isArray(path)</code> see rewrite.</p>\n<p><strong>Note</strong> <em>&quot;<code>null</code> is bad&quot;</em> Good JS should never set a value to <code>null</code> and thus avoid the ridiculous need to test if an object is <code>null</code>, unfortunately we must deal with the designers of the DOM and CSS that seam to have missed what <code>null</code> means in JS.</p>\n<h2 id=\"cyclic-safe-3xb7\">Cyclic safe</h2>\n<p>As a rule iterating paths should be wary of cyclic paths, however this is only a concern if the search is open ended (able to loop infinitely) and thus not an issue in this case.</p>\n<h2 id=\"inconsistent-return-cm7g\">Inconsistent return</h2>\n<p>If passed an empty array your example returns <code>undefined</code> which does not make sense if compared to an incomplete path that will return an <code>Object</code> or <code>value</code>. An empty path is equivalent to an incomplete path.</p>\n<p>For example the objects</p>\n<pre><code>const o1 = {A: { B: {C: 0}}};\nconst o2 = {B: {C: 0}};\n</code></pre>\n<p>The root object can not be found</p>\n<pre><code>getPathValue(o1, [&quot;A&quot;]);// returns {B: {C: 0}};\ngetPathValue(o1, []); // returns undefined; One would expect {A: { B: {C: 0}}}\ngetPathValue(o2, []); // returns undefined; One would expect {B: {C: 0}}\ngetPathValue(getPathValue(o1, [&quot;A&quot;]), []); // returns undefined; One would expect {B: {C: 0}}\n</code></pre>\n<h2 id=\"rewrite-5bl8\">Rewrite</h2>\n<p>The rewrite</p>\n<ul>\n<li><p>Returns <code>undefined</code> if a path can not be found.</p>\n</li>\n<li><p>Returns the object at the end of the path. eg <code>getPathValue(obj, [])</code> returns <code>obj</code> not <code>undefined</code></p>\n</li>\n<li><p>Will also follow an index path into arrays.</p>\n</li>\n<li><p>Uses <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. Nullish coalescing operator\">?? (Nullish coalescing operator)</a> to simplify search along path and as such will return <code>undefined</code> rather than <code>null</code>. Fitting <em>&quot;<code>null</code> is bad&quot;</em> rule for JS.</p>\n</li>\n<li><p>If second argument is not an array the result will be <code>undefined</code>.</p>\n</li>\n</ul>\n<pre><code>\nfunction valueAtPath(obj, path) { \n var i = 0; \n if (typeof obj === &quot;object&quot; &amp;&amp; obj !== null &amp;&amp; Array.isArray(path)) {\n while (i &lt; path.length &amp;&amp; obj !== undefined) { obj = obj[path[i++]] ?? undefined }\n return obj;\n }\n}\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T14:00:36.983", "Id": "521538", "Score": "0", "body": "Had `o1` been accessed dynamically with `o1[]` or `o1['']`, it would have thrown an **error** or returned **undefined** value respectively. So, respecting this behaviour, I expect `getPathValue(o1, [])` to return **undefined** likewise. What are your thoughts on this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T14:23:11.947", "Id": "521542", "Score": "0", "body": "@VinaySharma An array with an empty string is not an empty array. What you return for these cases is up to you as there is no right or wrong. My view is... You do not provide a way to return the root object and thus would have to add a statement to the call if you required the root object. The function solves a path, if you take no steps along a path you in effect remain at the start (root) of the path. If you attempt to step on an undefined path eg named `\"\"` empty string, then you have moved to an undefined location." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T13:10:14.890", "Id": "264057", "ParentId": "264050", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T10:18:11.707", "Id": "264050", "Score": "1", "Tags": [ "javascript", "recursion", "ecmascript-6" ], "Title": "Recursively access deeply nested object" }
264050
<p>I created this short method:</p> <pre><code>private Item createItemType(final Integer type) { if(type == null) { return null; }else if (type == 0) { return Item.PLACE; } else if (type == 7) { return Item.ADDRESS; } return null; } </code></pre> <p>Logically it is correct, but I want to know if there is a better way/elegant way to write this piece of code ?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T20:20:33.040", "Id": "521482", "Score": "2", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T12:17:44.300", "Id": "521528", "Score": "1", "body": "Do you really need the Integer type? Do you think that int would work? If this is the case, it will remove the validation of the null... because int can't be null" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T09:57:29.563", "Id": "521609", "Score": "0", "body": "this question is very opinion based - you will not get useful input (beside the most obvious `switch-case`) to your question if you do not provide more content. --> What is `type`? why is `type` an `Integer`? how many `types` do you have? two (0,7)? eight (0..7)? whats the expected behavior in case you don't find a `type`?" } ]
[ { "body": "<p>In this case, i would use the inline if. This would take less line and would be cleaner overall.</p>\n<pre><code>private Item createItemType(final Integer type) {\n return type == null ? null : \n type == 0 ? Item.PLACE : \n type == 7 ? Item.ADDRESS :\n null;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T05:13:00.103", "Id": "521503", "Score": "3", "body": "Bad Idea: you moved the null check to the end (or rather removed it), which will lead to a null pointer exception when auto-unboxing the Integer for int comparison." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T16:20:58.727", "Id": "521633", "Score": "0", "body": "No difference. in fact see the two `null`s use a switch instead..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T12:07:02.447", "Id": "521790", "Score": "1", "body": "Nesting/chaining ternary operators is, in my opinion, ugly and a potential maintenance headache. In this case, it's not totally abhorrent, but if anyone in my team asked me to approve this code I'd refuse and ask for it to be recoded." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T12:52:14.903", "Id": "264056", "ParentId": "264053", "Score": "7" } }, { "body": "<h3 id=\"switch-wedc\"><code>switch</code></h3>\n<p>I would find a <code>switch</code> cleaner.</p>\n<pre><code>private static Item createItemType(final Integer type) {\n if (type != null) {\n switch (type) {\n case 0:\n return Item.PLACE;\n case 7:\n return Item.ADDRESS;\n }\n }\n\n return null;\n}\n</code></pre>\n<p>If you really want to reduce the number of lines, you can combine the <code>return</code> lines with the case labels. But I find that to reduce both readability and editability.</p>\n<p>This is also better than the inline <code>if</code> in the face of future changes, e.g. if you need to check something else as well.</p>\n<p>As stands, that method doesn't use any object state, so it can be <code>static</code>.</p>\n<h3 id=\"ternary-conditional-operator-r7ez\">Ternary conditional operator</h3>\n<p>Another alternative is nesting the ternary conditional operator.</p>\n<pre><code>private static Item createItemType(final Integer type) {\n return (type == null) ? null\n : (type == 0) ? Item.PLACE\n : (type == 7) ? Item.ADDRESS\n : null;\n}\n</code></pre>\n<p>This is even shorter than the inline <code>if</code> much less your original <code>if</code>/<code>else</code> tree. It only has one <code>return</code> keyword as compared to four in your original.</p>\n<p>Personally, I find this at least as readable as the inline <code>if</code> statements if formatted like this. It still suffers from difficulty of adding side effects, but it is more obvious about why that won't work.</p>\n<h3 id=\"map-mjbk\"><code>Map</code></h3>\n<pre><code>private final static Map&lt;Integer, Item&gt; ITEMS = new HashMap&lt;&gt;();\n\nstatic {\n ITEMS.put(0, Item.PLACE);\n ITEMS.put(7, Item.ADDRESS);\n}\n\nprivate static Item createItemType(final Integer type) {\n return ITEMS.get(type);\n}\n</code></pre>\n<p>This is the shortest function, but you have to build the map separately.</p>\n<p>It is possible to build the map automatically. Something like</p>\n<pre><code>foreach (Item item : Item.values()) {\n ITEMS.put(item.getIntValue(), Item.PLACE);\n}\n</code></pre>\n<p>But that requires <code>Item</code> to implement <code>getIntValue</code> (or similar).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T14:55:29.850", "Id": "264063", "ParentId": "264053", "Score": "11" } }, { "body": "<p>In the latter java versions its even much easier. I would recommend the following:-</p>\n<pre class=\"lang-java prettyprint-override\"><code>private static Item createItemType(final Integer type) {\n if (type != null) \n return switch (type) {\n case 0 -&gt; Item.PLACE;\n case 7 -&gt; Item.ADDRESS;\n default -&gt; return null;\n }\n return null;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T21:31:48.610", "Id": "521653", "Score": "2", "body": "Part of a code review is not only to give an alternative implementation, but also to explain why you believe your solution is better. One problem with your code, is that the `if` statement is lacking braces, which most style guides suggest that they are never left out." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T16:26:32.627", "Id": "264121", "ParentId": "264053", "Score": "0" } }, { "body": "<p>The sample code is too small, and lacks enough context, to allow a detailed analysis.</p>\n<p>Initial points though are:</p>\n<ol>\n<li>Your method name is poorly chosen. It doesn't create anything, it looks something up.</li>\n<li>Your if statements immediately return, so there's no need for &quot;else&quot;. In the IDE I use (eclipse) I'd get warnings about that!</li>\n<li>The suggestion to go without curly braces should be ignored. It's poor practice, as I know from &gt; 20 years of writing Java.</li>\n</ol>\n<p>I don't much like the use of &quot;if&quot; or &quot;switch&quot; for this sort of thing. There are approaches which are less fragile and easier to extend.</p>\n<p>In my opinion, the best approach is to find a good way to represent the data you're working with - if you can do that, you can often avoid &quot;if&quot; or &quot;switch&quot;...</p>\n<p>For this sort of lookup, I'm fond of using Java enums, so here's an example doing just that:</p>\n<pre><code>public class TypeGetter {\n\n static private enum Item {\n PLACE(0), ADDRESS(7);\n\n private int type;\n\n Item(int type) {\n this.type = type;\n }\n\n public static Item getByType(int requiredType) {\n for (Item candidate : Item.values()) {\n if (candidate.type == requiredType) {\n return candidate;\n }\n }\n return null;\n }\n\n }\n\n public static void main(String[] args) {\n TypeGetter typeGetter = new TypeGetter();\n for (int requiredType : new int[]{0, 7, 42}) {\n System.out.format(&quot;type %d gives item %s%n&quot;, requiredType, typeGetter.lookupItemByType(requiredType));\n }\n\n }\n\n private Item lookupItemByType(final int requiredType) {\n return Item.getByType(requiredType);\n }\n\n}\n</code></pre>\n<p>The Item.getByType(int) method is a pattern I use quite a lot with enums. In this case, as the list is small, I've simply done a linear scan of the Items.</p>\n<p>For more than (say) 6 or so Items, I'd probably use a Map, populated in a static initialiser. Here's the Item enum rewritten to use that approach:</p>\n<pre><code> static private enum Item {\n PLACE(0), ADDRESS(7);\n\n private static Map&lt;Integer, Item&gt; byType = new HashMap&lt;&gt;();\n\n private int type;\n\n Item(int type) {\n this.type = type;\n }\n\n static {\n for (Item item : Item.values()) {\n byType.put(item.type, item); // relies on autoboxing\n }\n }\n\n public static Item getByType(int requiredType) {\n return byType.get(requiredType); // relies on autoboxing\n }\n\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T10:53:33.880", "Id": "264203", "ParentId": "264053", "Score": "1" } } ]
{ "AcceptedAnswerId": "264056", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T11:18:27.363", "Id": "264053", "Score": "1", "Tags": [ "java" ], "Title": "How to rewrite if.. else statements in a more elegant way" }
264053
<p>This is a hangman game. The only word is 'word' and I am not planning on changing this since I am not going to publish this game or anything.</p> <p>If there is any unnecessary/bad code I need to get rid of, please tell me.</p> <p>Here is my code:</p> <pre><code>using System; using System.Threading; namespace Hangman { class Program { static void Restart() { try { Console.Write(&quot;restart? (y/n): &quot;); char restart_input = Convert.ToChar(Console.ReadLine().ToLower()); if(restart_input == 'y') { Console.WriteLine(&quot;----------&quot;); Main(); } else if (restart_input == 'n') { Console.Write(&quot;\nPress any key to exit&quot;); Console.ReadKey(); } else if (restart_input != 'y' &amp;&amp; restart_input != 'n') { Console.WriteLine(&quot;\ninvalid input&quot;); Restart(); } } catch(Exception e) { Console.Write(&quot;\n&quot; + e); Restart(); } } static void Main() { Console.Title = &quot;Hangman&quot;; int i = 0; int j = 1; bool has_guessed_the_letter = false; string word = &quot;word&quot;; int failed_attempts = 0; int score = 0; Random random = new Random(); int random_int = random.Next(0, 2); char[] char_array = word.ToCharArray(); char?[] hidden_letters = new char?[i]; foreach (char letter in char_array) { switch (random_int) { case 1: Console.Write(letter); Thread.Sleep(200); random_int = random.Next(0, 2); break; case 0: Console.Write(&quot;_&quot;); Thread.Sleep(200); random_int = random.Next(0, 2); Array.Resize(ref hidden_letters, j); hidden_letters[i] = letter; i++; j++; break; } } if (hidden_letters.Length == 0) { Console.Write(&quot;\nthere are no hidden letters, lucky :)&quot;); } else if (hidden_letters.Length == word.Length) { Console.Write(&quot;\nall letters are hidden, no luck :(&quot;); } else { try { label: i = 0; j = 1; has_guessed_the_letter = false; Console.Write(&quot;\n\ninput: &quot;); char user_input = Convert.ToChar(Console.ReadLine()); while (has_guessed_the_letter == false &amp;&amp; j &lt;= hidden_letters.Length) { if (user_input == hidden_letters[i]) { has_guessed_the_letter = true; hidden_letters[i] = null; } else { i++; j++; } } if (has_guessed_the_letter == true) { Console.WriteLine(&quot;Congratulations! &quot; + j + &quot;. hidden letter was &quot; + user_input); score++; if (score == hidden_letters.Length) { Console.Write(&quot;\nCongratulations! the hidden word was: &quot; + word); } else { Console.WriteLine(&quot;score: &quot; + score + &quot; (must reach: &quot; + hidden_letters.Length + &quot;)&quot;); Console.Write(&quot;failed attempts: &quot; + failed_attempts + &quot; (failed attempts left: &quot; + ((word.Length * 2) - failed_attempts) + &quot;)&quot;); goto label; } } else { Console.WriteLine(&quot;failed attempt: &quot; + user_input); failed_attempts++; if (failed_attempts == (word.Length * 2)) { Console.Write(&quot;\ngame over. the hidden word was: &quot; + word); } else { Console.WriteLine(&quot;score: &quot; + score + &quot; (must reach: &quot; + hidden_letters.Length + &quot;)&quot;); Console.Write(&quot;failed attempts: &quot; + failed_attempts + &quot; (failed attempts left: &quot; + ((word.Length * 2) - failed_attempts) + &quot;)&quot;); goto label; } } } catch(Exception e) { Console.Write(&quot;\n&quot; + e); } } Console.WriteLine(&quot;\n----------&quot;); Restart(); } } } </code></pre>
[]
[ { "body": "<p>There are a few more things than I want to go into at this time - but there are two Big Ones™ I want to address. One is the <code>goto</code> and the other is the recursion in the <code>Restart</code> method. Eventually, the recursion will blow the stack. And the <code>goto</code> is just bad form past 1985. Here's a reworked version that addresses both those items (plus a little thread-safety around <code>Random</code> for good measure):</p>\n<pre><code>namespace Hangman\n{\n using System;\n using System.Threading;\n\n internal static class Program\n {\n private static readonly Random _Random = new ();\n\n private enum ShouldRestart\n {\n Invalid,\n\n No,\n\n Yes\n }\n\n private static ShouldRestart Restart()\n {\n Console.Write(&quot;restart? (y/n): &quot;);\n\n char restartInput = Convert.ToChar(Console.ReadLine()?.ToLower() ?? string.Empty);\n\n if (restartInput == 'y')\n {\n Console.WriteLine(&quot;----------&quot;);\n return ShouldRestart.Yes;\n }\n\n if (restartInput == 'n')\n {\n Console.Write(&quot;\\nPress any key to exit&quot;);\n Console.ReadKey();\n return ShouldRestart.No;\n }\n\n Console.WriteLine(&quot;\\ninvalid input&quot;);\n return ShouldRestart.Invalid;\n }\n\n private static void Main()\n {\n Console.Title = &quot;Hangman&quot;;\n\n while (true)\n {\n int i = 0;\n int j = 1;\n\n const string Word = &quot;word&quot;;\n\n int failedAttempts = 0;\n int score = 0;\n int randomInt;\n\n lock (_Random)\n {\n randomInt = _Random.Next(0, 2);\n }\n\n char[] charArray = Word.ToCharArray();\n char?[] hiddenLetters = new char?[i];\n\n foreach (char letter in charArray)\n {\n switch (randomInt)\n {\n case 1:\n Console.Write(letter);\n Thread.Sleep(200);\n lock (_Random)\n {\n randomInt = _Random.Next(0, 2);\n }\n\n break;\n\n case 0:\n Console.Write(&quot;_&quot;);\n Thread.Sleep(200);\n lock (_Random)\n {\n randomInt = _Random.Next(0, 2);\n }\n\n Array.Resize(ref hiddenLetters, j);\n hiddenLetters[i] = letter;\n i++;\n j++;\n break;\n }\n }\n\n if (hiddenLetters.Length == 0)\n {\n Console.Write(&quot;\\nthere are no hidden letters, lucky :)&quot;);\n }\n else if (hiddenLetters.Length == Word.Length)\n {\n Console.Write(&quot;\\nall letters are hidden, no luck :(&quot;);\n }\n else\n {\n while (true)\n {\n i = 0;\n j = 1;\n\n bool hasGuessedTheLetter = false;\n\n Console.Write(&quot;\\n\\ninput: &quot;);\n\n char userInput = Convert.ToChar(Console.ReadLine() ?? string.Empty);\n\n while (!hasGuessedTheLetter &amp;&amp; j &lt;= hiddenLetters.Length)\n {\n if (userInput == hiddenLetters[i])\n {\n hasGuessedTheLetter = true;\n hiddenLetters[i] = null;\n }\n else\n {\n i++;\n j++;\n }\n }\n\n if (hasGuessedTheLetter)\n {\n Console.WriteLine(&quot;Congratulations! &quot; + j + &quot;. hidden letter was &quot; + userInput);\n score++;\n if (score == hiddenLetters.Length)\n {\n Console.Write(&quot;\\nCongratulations! the hidden word was: &quot; + Word);\n break;\n }\n\n Console.WriteLine(&quot;score: &quot; + score + &quot; (must reach: &quot; + hiddenLetters.Length + &quot;)&quot;);\n Console.Write(&quot;failed attempts: &quot; + failedAttempts + &quot; (failed attempts left: &quot; + ((Word.Length * 2) - failedAttempts) + &quot;)&quot;);\n }\n else\n {\n Console.WriteLine(&quot;failed attempt: &quot; + userInput);\n failedAttempts++;\n if (failedAttempts == (Word.Length * 2))\n {\n Console.Write(&quot;\\ngame over. the hidden word was: &quot; + Word);\n break;\n }\n\n Console.WriteLine(&quot;score: &quot; + score + &quot; (must reach: &quot; + hiddenLetters.Length + &quot;)&quot;);\n Console.Write(&quot;failed attempts: &quot; + failedAttempts + &quot; (failed attempts left: &quot; + ((Word.Length * 2) - failedAttempts) + &quot;)&quot;);\n }\n }\n }\n\n Console.WriteLine(&quot;\\n----------&quot;);\n\n ShouldRestart shouldRestart = ShouldRestart.Invalid;\n\n while (shouldRestart == ShouldRestart.Invalid)\n {\n shouldRestart = Restart();\n }\n\n if (shouldRestart == ShouldRestart.No)\n {\n break;\n }\n }\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T18:06:07.947", "Id": "521477", "Score": "1", "body": "`ConsoleKey restartInput = Console.ReadKey().Key; Console.WriteLine(); if (restartInput == ConsoleKey.Y) { restart } else { exit }` - can work more friendly to user." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T18:09:56.627", "Id": "521479", "Score": "2", "body": "`lock` for Random is a kind of redundancy on a single thread, and it looks weird. Btw, if you need a cool thread-safety, try `[ThreadStatic]` above `Random` definition line instead of `lock`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T13:51:58.043", "Id": "521535", "Score": "0", "body": "sir. this is the most confusing C# code I have readen in my life" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T14:46:36.417", "Id": "521544", "Score": "0", "body": "@user13988674 the changes from your code are so very minimal, I'm genuinely surprised by that comment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T22:38:55.990", "Id": "521659", "Score": "0", "body": "but I am just a beginner" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T14:50:45.803", "Id": "264062", "ParentId": "264054", "Score": "1" } }, { "body": "<p>Right out of the gate, I would introduce OOP to this monolithic code, but I am unsure whether you are at the right stage of learning to develop to be ready for OOP, because it notably changes how you structure your code. It would also require an entire explanation of OOP principles, which is out of scope for the question at hand and is much better serviced by looking up OOP tutorials.</p>\n<p>Instead, for this answer I'm going to focus on smaller things in your code, in no particular order.</p>\n<p>If you're looking for overall advice on your code, starting to use OOP is a <strong>BIG</strong> improvement you could make, and eventually you will have to learn it if you want to develop in C#.</p>\n<hr />\n<h2>Recursion</h2>\n<p>What you've used here is a recursive pattern. <code>Main</code> calls <code>Restart</code>, which calls <code>Main</code>, which calls <code>Restart</code>, which ...</p>\n<p>There is a time and a place to use recursion, but this is not one of them. The problem with recursion is that the call stack is finite, and with each recursive step, you drill deeper into the call stack. Eventually, if you player keeps replaying the game, your code will crash because the call stack has grown too large, leading to a <code>StackOverflowException</code>.</p>\n<p>This would've been better expressed using an iteration, because this is not susceptible to stack overflows. There are three main iteration types: <code>for</code>, <code>while</code> and <code>do while</code>.<br />\nYou don't know in advance how often you'll repeat, so <code>for</code> is not right. Because you want to run your game <em>at least once</em>, a <code>do while</code> makes more sense than a <code>while</code> here.</p>\n<p>Your game logic can be repeated using:</p>\n<pre><code>bool shouldRestart;\n\ndo\n{\n shouldRestart = false;\n\n // Play the game\n\n Console.Write(&quot;restart? (y/n): &quot;);\n var restartInput = Console.ReadKey().KeyChar;\n\n shouldRestart = (restartInput.ToLower() == 'y');\n} while(shouldRestart);\n</code></pre>\n<hr />\n<h2>Game logic</h2>\n<p>You've used way too much if/else nesting in your logic for the code to be easily readable. Rather than tackle each individual thing you did, which requires a back and forth in understanding why you did it this way, I'm going to opt to rebuilt the logic from scratch, to give you an idea how you could've approached this without letting it devolve into such a branched logic.</p>\n<p><strong>Random start</strong></p>\n<p>I'm going to skip this because it's not part of Hangman. The only real random here would be the word selection, which you're not doing. This can be added later, when the base logic has been established.</p>\n<p><strong>Score</strong></p>\n<p>Similarly, I'm omitting the concept of a score. The goal in Hangman is to guess the word in as many tries as possible, so the score can be directly derived from the remaining attempts left when you guess the whole word. I would argue that the remaining attempt count <em>is</em> the score.</p>\n<p><strong>Game state</strong></p>\n<p>To store the state of the game, we need a few different things. Your approach wasn't bad, but I want to make some adjustments because they will make it easier to update the game state during the game.</p>\n<pre><code>const int MaximumAttempts = 7; // How many attempts a player has.\nconst string word = &quot;word&quot;; // The word to guess\n\nvar guessedLetters = new List&lt;char&gt;(); // Guesses the user has made\nint remainingAttempts = MaximumAttempts; // How many attempts left in this game?\n</code></pre>\n<p>For the sake of simplicity, we'll assume that the configured word is in lowercase.</p>\n<p><strong>Printing the hidden word</strong></p>\n<p>We need to obfuscate the word. We should replace all characters with <code>*</code> <em>unless</em> it is a character that the player has already guessed. We'll make a nice method for this:</p>\n<pre><code>public static string Obfuscate(string word, List&lt;char&gt; visibleLetters)\n{\n var characters = word.Distinct();\n string result = word;\n\n foreach(var character in characters)\n {\n bool isVisible = visibleLetters.Contains(character);\n\n if(!isVisible)\n {\n result = result.Replace(character, '*');\n }\n }\n \n return result;\n}\n</code></pre>\n<p><strong>Guessing</strong></p>\n<p>Now we want the player to guess a letter. For now, let's assume the player nicely inputs only lowercase letters. Validation can be written at a later stage.</p>\n<p>When a guess is made, we add this guess to the list of guessed characters (no matter if correct). If the word does not contain the guessed character, we decrease the remaining attempts. If the word has been guessed or the remaining attempts are 0, the game ends. Otherwise, we repeat this process.</p>\n<p>This, too, is an iterative process, and it also needs to run <em>at least once</em>, so another <code>do while</code> is warranted here.</p>\n<pre><code>bool gameWon = false;\nbool gameLost = false;\nstring obfuscatedWord = Obfuscate(word, guessedLetters);\n\ndo {\n Console.WriteLine(obfuscatedWord);\n Console.WriteLine($&quot;{remainingAttempts} attempts remaining!&quot;);\n Console.Write(&quot;Guess a letter: &quot;);\n\n char guess = Console.ReadKey().KeyChar;\n \n guessedLetters.Add(guess);\n\n if(!word.Contains(guessedLetter)) \n remainingAttempts--;\n\n // Generate a freshly obfuscated word\n obfuscatedWord = Obfuscate(word, guessedLetters);\n\n // The game is won when there is no more obfuscation,\n // i.e. the obfuscated word is equal to the original word\n gameWon = obfuscatedWord.Equals(word);\n\n // The game is lost when there are no remaining attempts\n gameLost = (remainingAttempts == 0);\n} while(!gameWon &amp;&amp; !gameLost);\n</code></pre>\n<p>We can only break out of this loop by either winning or losing the game. In other words, the subsequent code can trust for a fact that one of the booleans is true and will indicate whether the game was won or lost.</p>\n<pre><code>if(gameWon)\n Console.WriteLine($&quot;Victory! The word to guess was {word}!&quot;); \n\nif(gameLost)\n Console.WriteLine($&quot;Defeat! The word to guess was {word}!&quot;); \n</code></pre>\n<p>You <em>could</em> use an <code>else</code> here, because both booleans should never be true at the same time. However, I already know that there is no way for this logic to set both booleans to true at the same time, and I'd prefer to save myself the nesting logic because it detracts from code readability.</p>\n<p>It's perfectly okay to add the <code>else</code> if you prefer, but you went overboard with the nesting in your original code, so I want to urge you to avoid nesting where you can. Nested <code>if</code>s become really hard to follow.<br />\nI'll admit that I never even bothered to decode the branching logic you wrote, simply because it's just so hard to follow by reading it in a single pass. Don't worry about this, by the way. All developers learn to write working code (which you did) before they learn to write working <strong>and readable</strong> code. You'll get there :)</p>\n<p><strong>Bells and whistles</strong></p>\n<p>Note that I skipped a few bells and whistles, such as printing a list of guesses the player has already made, printing a list of available guesses, and printing the hangman himself. Those are all flourishes you can add yourself, which don't impact the core game logic.</p>\n<hr />\n<h2>Monolithic code</h2>\n<p>Your methods contained too much logic, and should be broken up into smaller submethods to make things easier to understand.</p>\n<p>I already broke up your code somewhat in the two section above, but I intentionally left some things that can still be improved. I already mentioned it: we should really be validating the user's input, and force them to retry when they input something bad.</p>\n<p>If we added this to the code directly, it would start distracting us from the core game logic. This is why we are going to put this logic in a submethod, so that we don't conflate the game logic with some nice-to-have validation.</p>\n<p>Coincidentally enough, this again warrants an iteration, and <code>do while</code> is again the appropriate choice as you want the player to input a character <em>at least once</em>.</p>\n<pre><code>public const string AllowedCharacters = &quot;abcdefghijklmnopqrstuvwxyz&quot;;\n\npublic static char MakeGuess(List&lt;char&gt; alreadyGuessed)\n{\n char guess;\n bool characterIsInvalid = false;\n\n do {\n // Reset validation flag\n characterIsInvalid = false;\n \n Console.Write(&quot;Guess a letter: &quot;);\n char guess = Console.ReadKey().KeyChar;\n\n // Ensure lower case\n guess = guess.ToLower();\n\n // Ensure it's a letter, otherwise repeat\n if(!AllowedCharacters.Contains(guess))\n {\n Console.WriteLine(&quot;Input is not a letter!&quot;);\n characterIsInvalid = true;\n }\n\n // Ensure this has not been guessed yet\n if(alreadyGuessed.Contains(guess))\n {\n Console.WriteLine(&quot;You already guessed this before!&quot;);\n characterIsInvalid = true;\n }\n\n } while(characterIsInvalid);\n\n return guess; \n}\n</code></pre>\n<p>We can be sure that the value returned by <code>MakeGuess</code> is valid. Our core game logic doesn't need to validate this input any further. All we need to do is change our game logic to rely on this method, instead of reading the input directly:</p>\n<pre><code>// ...\n\nConsole.WriteLine(obfuscatedWord);\nConsole.WriteLine($&quot;{remainingAttempts} attempts remaining!&quot;);\n\nchar guess = MakeGuess(guessedLetters);\n \nguessedLetters.Add(guess);\n\n// ...\n</code></pre>\n<p>There are other submethods ripe for developing, but I will leave these as an exercise to you. To help you identify some of these:</p>\n<ul>\n<li>The comment I made in the first snippet (<code>// Play the game</code>) should not be replaced by the game logic I wrote in a later snippet. Instead, the game logic should be in its own method, and <code>// Play the game</code> should be replaced with a call to that submethod.</li>\n<li><code>string ChooseWord()</code> (can return fixed value, or randomly chosen value from a list of words)</li>\n<li><code>void PrintHangmanImage(int remainingAttempts) {}</code></li>\n<li><code>void PrintVictory(string word, List&lt;char&gt; guessesMade, int remainingAttempts) {}</code></li>\n<li><code>void PrintDefeat(string word, List&lt;char&gt; guessesMade) {}</code></li>\n<li><code>void PrintAvailableGuesses(List&lt;char&gt; guessesMade) {}</code></li>\n</ul>\n<hr />\n<h2>Smaller feedback points</h2>\n<p><strong>String concatenation</strong></p>\n<pre><code>Console.WriteLine(&quot;score: &quot; + score + &quot; (must reach: &quot; + hidden_letters.Length + &quot;)&quot;);\n</code></pre>\n<p>Avoid <code>+</code> when concatenating strings. One <code>+</code> doesn't break your code but it's inefficient and will bring your application to its knees if you concatenate many values.</p>\n<p>Better approaches include <code>String.Format()</code>; <code>StringBuilder</code>, and IMO the best default approach is string interpolation (<code>$&quot;score: {score} (must reach: {hidden_letters.Length})&quot;</code>).</p>\n<p><strong>Goto</strong></p>\n<pre><code>goto label;\n \n</code></pre>\n<p>In short, <strong>never</strong> use <code>goto</code>. It's an archaic concept and only used as a crutch for badly designed logical flow. The better solution is to redesign your flow so that you don't need sudden jumps from one place to another.</p>\n<p>I often leave room for exceptions for most (if not all) coding guidelines, but not for <code>goto</code>. It is <em>that</em> bad.</p>\n<p><strong>Naming</strong></p>\n<pre><code>has_guessed_the_letter = false;\nint failed_attempts = 0;\nint random_int = random.Next(0, 2);\nchar[] char_array = word.ToCharArray();\nchar?[] hidden_letters = new char?[i];\n</code></pre>\n<p>Generally speaking, avoid underscores-as-spaces, and skip articles such as &quot;the&quot;.</p>\n<pre><code>hasGuessedLetter = false;\nint failedAttempts = 0;\nchar?[] hiddenLetters = new char?[i];\n</code></pre>\n<p>Additionally, avoid putting the type in the variable name (note that this advice becomes less relevant in OOP code, for different reasons).</p>\n<pre><code>int randomValue = random.Next(0, 2);\nchar[] characters = word.ToCharArray();\n</code></pre>\n<p><strong>Resizing arrays</strong></p>\n<pre><code>Array.Resize(ref hidden_letters, j);\n</code></pre>\n<p>Ever since the advent of LINQ, arrays and lists have both become rather easy to use, even interchangeably. However, lists have one clear advantage over arrays: they are <strong>dynamically sized</strong>. Arrays are fixed size.</p>\n<p>When you notice you want to resize your array, instead rewrite your code to use a <code>List&lt;T&gt;</code> instead of a <code>T[]</code>. Hardly any of your code will need to be changed (lists also allow for indexed access), and <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=net-5.0\" rel=\"nofollow noreferrer\">lists have nice and easy methods to add/remove members</a>.</p>\n<p><strong>Newlines</strong></p>\n<pre><code>Console.Write(&quot;\\nthere are no hidden letters, lucky :)&quot;);\n</code></pre>\n<p>This is a bit of a nitpick, but favor using <code>Environment.NewLine</code> over <code>'\\n'</code>, as a matter of readability.</p>\n<pre><code>Console.Write($&quot;{Environment.NewLine}there are no hidden letters, lucky :)&quot;);\n</code></pre>\n<p>Alternatively, you could also using an empty <code>WriteLine</code> call:</p>\n<pre><code>Console.WriteLine();\nConsole.Write(&quot;there are no hidden letters, lucky :)&quot;);\n</code></pre>\n<p>In either case, it becomes slightly easier to notice that the message you're writing doesn't begin with <code>nthere</code> but rather <code>there</code>.</p>\n<p>As I said, it'd a bit of a nitpick, but if you consistently use newline characters everywhere, it starts being a bit annoying.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T12:36:25.490", "Id": "266164", "ParentId": "264054", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T11:42:38.427", "Id": "264054", "Score": "3", "Tags": [ "c#", "beginner", "game", ".net", "hangman" ], "Title": "Hangman game with only one word" }
264054
<p>I'm trying to do a non equi self join with basic python libraries on a table that has 1.7 millions rows and 4 variables. the data look like this:</p> <pre><code>product position_min position_max count_pos A.16 167804 167870 20 A.18 167804 167838 15 A.15 167896 167768 18 A.20 238359 238361 33 A.35 167835 167837 8 </code></pre> <pre><code>import csv from collections import defaultdict import sys import os list_csv=[] l=[] with open(r'product.csv', 'r') as file1: my_reader1 = csv.reader(file1, delimiter=';') list_csv=[row for row in my_reader1 ] with open(r'product.csv', 'r') as file2: my_reader2 = csv.reader(file2, delimiter=';') with open('product_p.csv', &quot;w&quot;) as csvfile_write: ecriture = csv.writer(csvfile_write, delimiter=';', quotechar='&quot;', quoting=csv.QUOTE_ALL) for row in my_reader2: res = defaultdict(list) for k in range(len(list_csv)): comp= list_csv[k] try: if int(row[1]) &gt;= int(comp[1]) and int(row[2]) &lt;= int(comp[2]) and row[0] != comp[0]: res[row[0]].append([comp[0],comp[3]]) except: pass if bool(res): for key, value in res.items(): sublists = defaultdict(list) for sublist in value: l=[] sublists[sublist[0]].append(int(sublist[1])) l.append(str(key) + &quot;;&quot;+ str(min(sublists.keys(), key=(lambda k: sublists[k])))) ecriture.writerow(l) </code></pre> <p>I should get this in the &quot;product_p.csv&quot; file:</p> <pre><code>'A.18'; 'A.16' 'A.15'; 'A.18' 'A.35'; 'A.18' </code></pre> <p>What the code does is to read the same file twice, the first time completely, and convert it into a list, and the 2nd time line by line and that is to find for each product (1st variable) all the products to which it belongs by the condition on position_min and position_max and after that choose only one by keeping the product that has the minimum of count_pos .</p> <p>I tried it on a sample of the original data, it works, but with 1.7 millions rows, it runs for hours without giving any results. Is there a way to do that without for loops with basic python libraries ?</p> <p>Thank you in advance</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T22:42:05.147", "Id": "521491", "Score": "0", "body": "_with basic python libraries_? No. Why would you want this? Pandas/Numpy are built for this kind of scale." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T13:31:19.403", "Id": "521532", "Score": "0", "body": "I have to run it in a workflow as a shell action, and for that I have to use only basic python libraries. I want to use less loopsin my code, That's why I posted here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T13:38:36.367", "Id": "521533", "Score": "0", "body": "That doesn't seem like a good excuse? Any Python program with dependencies can be run from the shell." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T13:49:25.647", "Id": "521617", "Score": "0", "body": "The workflow have to be run on a hadoop cluster, that's why i need to use only basic python libraires." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T13:52:44.960", "Id": "521619", "Score": "0", "body": "Still not hearing a good reason. [Other people have been down this road.](https://stackoverflow.com/questions/48865615/installing-python-dependencies-in-hadoop-cluster)" } ]
[ { "body": "<h1 id=\"double-open-af7v\">Double Open</h1>\n<p>There is no reason to open the <code>product.csv</code> file twice.</p>\n<p>The first time you open the file, you are reading and storing the entire file in memory. Instead of opening and reading the file a second time line by line, you could simply loop over the <code>list_csv</code>. This:</p>\n<pre class=\"lang-py prettyprint-override\"><code>with open(r'product.csv', 'r') as file2:\n my_reader2 = csv.reader(file2, delimiter=';') \n with open('product_p.csv', &quot;w&quot;) as csvfile_write:\n ecriture = csv.writer(csvfile_write, delimiter=';',\n quotechar='&quot;', quoting=csv.QUOTE_ALL)\n for row in my_reader2:\n ...\n</code></pre>\n<p>becomes:</p>\n<pre class=\"lang-py prettyprint-override\"><code>with open('product_p.csv', &quot;w&quot;) as csvfile_write:\n ecriture = csv.writer(csvfile_write, delimiter=';',\n quotechar='&quot;', quoting=csv.QUOTE_ALL)\n for row in list_csv:\n ...\n</code></pre>\n<h1 id=\"save-your-work-doqo\">Save your work</h1>\n<p>With one million rows in your file, your <span class=\"math-container\">\\$O(N^2)\\$</span> algorithm is visiting one trillion row pairings. With each row pairing, you convert strings to integers up to 4 times with <code>int(row[1]) &gt;= int(comp[1]) and int(row[2]) &lt;= int(comp[2])</code>. That is four trillion string-to-integer conversions!</p>\n<p>Yeouch!</p>\n<p>If instead, as you read the file the first time, you convert the three strings into integer values and stored the already converted values in <code>list_csv</code>, validating in the process, your later code would cleaner and faster.</p>\n<pre class=\"lang-py prettyprint-override\"><code>with open(r'product.csv', 'r') as file1:\n my_reader1 = csv.reader(file1, delimiter=';')\n list_csv = []\n for row in my_reader1:\n try:\n product = row[0]\n pos_min, pos_max, count_pos = map(int, row[1:])\n list_csv.append((product, pos_min, pos_max, count_pos))\n except ValueError:\n pass\n\n # No int(...) or try-except required beyond this point\n</code></pre>\n<h1 id=\"bare-except-a3tz\">Bare Except</h1>\n<p><code>try: ... except: pass</code> is bad, bad, bad.</p>\n<p>What exception is expected? <code>except ValueError:</code> is better. It lets the reader know what type of exception might occur, giving context.</p>\n<p>It is also for your benefit. What if you accidentally wrote <code>... int(cmp[2]) ...</code> inside <code>try: ... except: pass</code>? You would get one trillion <code>NameError</code> exceptions raised and suppressed. After a long, long period of time, the program would complete and write an empty result file, leaving you with no clue what went wrong. Narrowing the type of exception caught to a <code>ValueError</code> would immediately reveal the issue.</p>\n<p>It would be much better to actually handle the error, instead of suppressing it. Print out a message explaining what the problem was: what row failed to convert properly. If there are known valid reasons why the conversion might fail, check that the failure was expected, and report if the failure was not of the expected variety.</p>\n<h1 id=\"named-tuples-hyta\">Named Tuples</h1>\n<p>Giving names to your data structure elements can help readability.</p>\n<p>What is <code>comp[1]</code>? <code>row[2]</code>? <code>comp[3]</code>? It is very difficult to tell from the code.</p>\n<p>Consider instead:</p>\n<pre class=\"lang-py prettyprint-override\"><code>...\nfrom typing import NamedTuple\n\nclass Product(NamedTuple):\n product: str\n pos_min: int\n pos_max: int\n count_pos: int\n\n...\n\nwith open(r'product.csv', 'r') as file1:\n my_reader = csv.reader(file1, delimiter=';')\n products = []\n for row in my_reader:\n try:\n product = row[0]\n pos_min, pos_max, count_pos = map(int, row[1:])\n products.append(Product(product, pos_min, pos_max, count_pos))\n except ValueError:\n pass\n\n for row in products:\n ...\n for comp in products:\n if row.pos_min &gt;= comp.pos_min and row.pos_max &lt;= comp.pos_max and row.product != comp.product:\n res[row.product].append([comp.product, comp.count_pos])\n\n ...\n</code></pre>\n<p>This is immediately more readable. We're not comparing some arbitrary thing at indices 1, 2, and 0; we're comparing named things.</p>\n<p>Speaking of names ...</p>\n<p>I've changed <code>list_csv</code> to <code>products</code>. It was read from a CSV file, but the elements are no longer comma-separated-values. The commas are long gone. Its just a list of products.</p>\n<p><code>row</code> and <code>comp</code> could use better names too.</p>\n<p>I've also replaced:</p>\n<pre class=\"lang-py prettyprint-override\"><code> for k in range(len(list_csv)):\n comp= list_csv[k]\n</code></pre>\n<p>with loop directly over the values of the list. There is no need for the <code>k</code> index variable.</p>\n<h1 id=\"algorithm-bpag\">Algorithm</h1>\n<p>With the above changes, your algorithm is still the same, which means it is still <span class=\"math-container\">\\$O(N^2)\\$</span>.</p>\n<p>Can we improve it? Sorting is <span class=\"math-container\">\\$O(N \\log N)\\$</span> which is better than <span class=\"math-container\">\\$O(N^2)\\$</span>, so is an easy thing to try. What can we sort on? Would sorting on <code>position_min</code> help us?</p>\n<p>Yes, it would, but we need to be careful.</p>\n<p>With products sorted on <code>position_min</code>, then <code>row.pos_min &gt;= comp.pos_min</code> would be true for all <code>comp</code> items occurring earlier than <code>row</code> in the <code>products</code> list. We might be tempted to loop <code>for row_idx in range(len(products))</code>, and <code>for comp_idx in range(row_idx)</code>, but we'd introduce a bug:</p>\n<p>Several items sorted after <code>row</code> might still have an <code>pos_min</code> equal to <code>row.pos_min</code>, so we can't just loop up to the current row. But we can stop when we reach the first <code>min_pos</code> value larger than <code>row.pos_min</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>\nsort(products, key=...)\n\nfor row in products:\n limit = row.min_pos\n for comp in products:\n if comp.min_pos &gt; limit:\n break\n if row.max_pos &lt;= comp.max_pos and row.product != comp.product:\n res[row.product].append([comp.product, comp.count_pos])\n\n ...\n</code></pre>\n<p>One trillion row-pairings just dropped to one-half trillion row-pairings. It is still <span class=\"math-container\">\\$O(N^2)\\$</span>, but we cut the time in half.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-18T16:55:43.273", "Id": "264160", "ParentId": "264060", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T14:15:31.507", "Id": "264060", "Score": "1", "Tags": [ "python", "performance", "time-limit-exceeded" ], "Title": "Non equi self join with basic python libraries" }
264060
<p>I have been attempting to implement a function calculating values of the sine function. I know that there are several similar threads regarding this topic but my goal was to try to implement such function in my own way as an excercise. I suppose that the argument will be in range <span class="math-container">\$\left&lt;-2\pi\, +2\pi\right&gt;\$</span>.</p> <p>In the time being I have below given code in C++ language which seems to be working (I have compared the outputs of that code with the sine values calculated by the Excel).</p> <pre><code>#define PI 3.14 #define TABLE_SIZE 256 #define STEP_SIZE (2*PI/255) double lut[TABLE_SIZE] = { 0.0000, 0.0245, 0.0490, 0.0735, 0.0980, 0.1223, 0.1467, 0.1709, 0.1950, 0.2190, 0.2429, 0.2666, 0.2901, 0.3135, 0.3367, 0.3597, 0.3825, 0.4050, 0.4274, 0.4494, 0.4712, 0.4927, 0.5139, 0.5348, 0.5553, 0.5756, 0.5954, 0.6150, 0.6341, 0.6529, 0.6713, 0.6893, 0.7068, 0.7240, 0.7407, 0.7569, 0.7727, 0.7881, 0.8029, 0.8173, 0.8312, 0.8446, 0.8575, 0.8698, 0.8817, 0.8930, 0.9037, 0.9140, 0.9237, 0.9328, 0.9413, 0.9493, 0.9568, 0.9636, 0.9699, 0.9756, 0.9806, 0.9852, 0.9891, 0.9924, 0.9951, 0.9972, 0.9988, 0.9997, 1.0000, 0.9997, 0.9988, 0.9974, 0.9953, 0.9926, 0.9893, 0.9854, 0.9810, 0.9759, 0.9703, 0.9640, 0.9572, 0.9498, 0.9419, 0.9333, 0.9243, 0.9146, 0.9044, 0.8937, 0.8824, 0.8706, 0.8583, 0.8454, 0.8321, 0.8182, 0.8039, 0.7890, 0.7737, 0.7580, 0.7417, 0.7251, 0.7080, 0.6904, 0.6725, 0.6541, 0.6354, 0.6162, 0.5967, 0.5769, 0.5566, 0.5361, 0.5152, 0.4941, 0.4726, 0.4508, 0.4288, 0.4065, 0.3840, 0.3612, 0.3382, 0.3150, 0.2917, 0.2681, 0.2444, 0.2205, 0.1966, 0.1724, 0.1482, 0.1239, 0.0996, 0.0751, 0.0506, 0.0261, 0.0016, -0.0229, -0.0475, -0.0719, -0.0964, -0.1208, -0.1451, -0.1693, -0.1934, -0.2174, -0.2413, -0.2650, -0.2886, -0.3120, -0.3352, -0.3582, -0.3810, -0.4036, -0.4259, -0.4480, -0.4698, -0.4913, -0.5125, -0.5334, -0.5540, -0.5743, -0.5942, -0.6137, -0.6329, -0.6517, -0.6701, -0.6881, -0.7057, -0.7229, -0.7396, -0.7559, -0.7717, -0.7871, -0.8020, -0.8164, -0.8303, -0.8437, -0.8566, -0.8690, -0.8809, -0.8923, -0.9031, -0.9133, -0.9230, -0.9322, -0.9408, -0.9488, -0.9563, -0.9632, -0.9695, -0.9752, -0.9803, -0.9849, -0.9888, -0.9922, -0.9950, -0.9971, -0.9987, -0.9996, -1.0000, -0.9998, -0.9989, -0.9975, -0.9954, -0.9928, -0.9895, -0.9857, -0.9813, -0.9762, -0.9706, -0.9644, -0.9577, -0.9503, -0.9424, -0.9339, -0.9249, -0.9153, -0.9051, -0.8944, -0.8832, -0.8714, -0.8591, -0.8463, -0.8330, -0.8191, -0.8048, -0.7900, -0.7747, -0.7590, -0.7428, -0.7262, -0.7091, -0.6916, -0.6736, -0.6553, -0.6366, -0.6175, -0.5980, -0.5782, -0.5580, -0.5374, -0.5166, -0.4954, -0.4740, -0.4522, -0.4302, -0.4080, -0.3854, -0.3627, -0.3397, -0.3166, -0.2932, -0.2696, -0.2459, -0.2221, -0.1981, -0.1740, -0.1498, -0.1255, -0.1011, -0.0767, -0.0522, -0.0277 }; double sine(double x, double lut[TABLE_SIZE]) { bool negateTableValue = false; if (x &lt; 0) { // sin(-x) = -sin(x) x = -x; negateTableValue = true; } uint8_t index_01 = x/STEP_SIZE; uint8_t index_02 = (index_01 + 1); double aux = (lut[index_02] - lut[index_01])/STEP_SIZE*(x - index_01*STEP_SIZE) + lut[index_01]; if (negateTableValue) { return -aux; } else { return aux; } } </code></pre> <p>The sine values calculation is based on the look-up table containing the pre-computed values of the sine function covering the whole period <span class="math-container">\$\left&lt;0, 2\pi\right&gt;\$</span> with 256 values. I have decided to use the linear interpolation method for improving the precision.</p> <p>I have one doubt regarding the linear interpolation. Namely I have been using table with 256 entries but most of the solutions exploiting the linear interpolation use look-up table with one additional entry. I would say that it isn't necessary in my case because the index variables are <code>uint8_t</code> type i.e. they can store values from range <code>0-255</code>. But I would like to know other ones opinion. Thank you in advance.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T23:08:11.720", "Id": "521493", "Score": "4", "body": "Please do not edit the question, especially the code after an answer has been posted. Everyone needs to be able to see what the reviewer was referring to. [What to do after the question has been answered](https://codereview.stackexchange.com/help/someone-answers)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T13:23:00.663", "Id": "521530", "Score": "0", "body": "@pacmaninbw but the edit you rolled back was not editing the code in the question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T22:31:35.560", "Id": "521658", "Score": "1", "body": "@thedefault. Any and all answer invalidation (AI) is not allowed. You should note pacmaninbw only emphasized \"the code\", as \"the code\" is normally how OPs AI. But pointed out any AI in any part of the question is not allowed; \"Please do not edit the question\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T19:11:51.263", "Id": "521809", "Score": "0", "body": "\" my goal was to try to implement such function in my own way as an excercise\" --> Why this approach? Speed? code size? Other approaches are better for both of those. Perhaps it is _only_ an exercise?" } ]
[ { "body": "<h1 id=\"you-only-need-to-store-values-for-16b511a5-fe0e-4d92-b3ca-28a5f8e81e17-p9fp\">You only need to store values for <span class=\"math-container\">\\$\\left[0, \\frac{1}{2}\\pi\\right)\\$</span></h1>\n<p>You can exploit the structure of the sine function, and only store values in the table for inputs between 0 and <span class=\"math-container\">\\$\\frac{1}{2}\\pi\\$</span>. Values between <span class=\"math-container\">\\$\\pi\\$</span> and <span class=\"math-container\">\\$2\\pi\\$</span> are just the negative of the values between <span class=\"math-container\">\\$0\\$</span> and <span class=\"math-container\">\\$\\pi\\$</span>, and values left and right of <span class=\"math-container\">\\$\\frac{1}{2}\\pi\\$</span> are mirrored. The upshot is that keeping the table size the same, you get four times the resolution.</p>\n<h1 id=\"use-a-proper-value-for-e923bd68-2b52-428a-b128-f5397c52d886-pc3m\">Use a proper value for <span class=\"math-container\">\\$\\pi\\$</span></h1>\n<p>Don't guess or use a low-precision estimate of <span class=\"math-container\">\\$\\pi\\$</span>. There are <a href=\"https://stackoverflow.com/questions/1727881/how-to-use-the-pi-constant-in-c\">several ways</a> to get a good value for it. A simple one is:</p>\n<pre><code>static const double PI = std::atan(1) * 4;\n</code></pre>\n<p>In C++20, you can use <a href=\"https://en.cppreference.com/w/cpp/numeric/constants\" rel=\"noreferrer\"><code>std::numbers::pi</code></a>.</p>\n<h1 id=\"the-step-size-is-slightly-wrong-q7cq\">The step size is slightly wrong</h1>\n<p>And not just because of the poor approximation of <span class=\"math-container\">\\$\\pi\\$</span>, but also because the values in your table are taken at intervals of <span class=\"math-container\">\\$\\pi/256\\$</span>, so <code>STEP_SIZE</code> should match that.</p>\n<h1 id=\"prefer-static-constexpr-over-define-pdeh\">Prefer <code>static constexpr</code> over <code>#define</code></h1>\n<p>Since C++11, you can use <code>static constexpr</code> to declare constants, and you can even use integers declared as such to specify the size of arrays.</p>\n<p>Note that since <code>std::atan()</code> is not <code>constexpr</code> itself, you can't use it to initialize a <code>constexpr</code> variable, but you can make <code>PI</code> <code>static const</code> instead, and most compilers will optimize it anyway. Of course, being able to use <code>std::numbers:pi</code> is even better.</p>\n<h1 id=\"avoid-hard-coding-the-table-2g6z\">Avoid hard-coding the table</h1>\n<p>You don't need to write all the values by hand, you can let the compiler generate the table for you at compile time, like so:</p>\n<pre><code>#include &lt;array&gt;\n#include &lt;cmath&gt;\n\nstatic constexpr size_t TABLE_SIZE = 256;\nstatic const double PI = std::atan(1) * 4;\n\nstatic std::array&lt;double, TABLE_SIZE&gt; make_lut() {\n std::array&lt;double, TABLE_SIZE&gt; lut{};\n\n for(size_t i = 0; i &lt; TABLE_SIZE; ++i) {\n lut[i] = std::sin(i * PI / 2 / TABLE_SIZE);\n }\n\n return lut;\n}\n\nstd::array&lt;double, TABLE_SIZE&gt; lut = make_lut();\n</code></pre>\n<h1 id=\"interpolation-lpxw\">Interpolation</h1>\n<p>If you can use C++20, then you can use <a href=\"https://en.cppreference.com/w/cpp/numeric/lerp\" rel=\"noreferrer\"><code>std::lerp()</code></a> to interpolate between two numbers. However, your implementation is fine since it interpolates between two numbers between -1 and 1, and not much can go <a href=\"https://www.youtube.com/watch?v=sBtAGxBh-XI\" rel=\"noreferrer\">wrong</a> there.</p>\n<h1 id=\"using-an-additional-entry-mri8\">Using an additional entry</h1>\n<p>The reason for an additional entry is that you only have to calculate <code>index_01</code>, and then you read two consecutive values from the table. This is slightly more efficient: no need for you or the compiler to handle wrapping of <code>index_02</code>, and reading memory locations sequentially might be faster than reading two locations that are far apart.</p>\n<p>Your code is fine, I don't think it will make a significant difference to add the additional entry. However, as soon as you want to change the size of the table to something that is not a power of two, it will pay off (modulo operations are basically divisions, and those are expensive).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T21:19:33.530", "Id": "521484", "Score": "0", "body": "BTW, you could _always_ use `const` integers to specify the size of an array, back to Cfront 1.x in the 80's." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T21:40:35.270", "Id": "521486", "Score": "0", "body": "@G. Sliepen thank you very much for your review. I have just added some notes regarding the step size selection to my question. May I ask you for your opinion?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T21:52:57.483", "Id": "521487", "Score": "0", "body": "Using 256 for STEP_SIZE is fine. If the input is 2π, then `index_01` is 0 and `index_02` is 1, but the interpolation should give the first index a weight of 1 and the second 0. I think `x - index_01 * STEP_SIZE` is wrong though; what if `x` is a much larger number than 2π?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T05:01:29.600", "Id": "521502", "Score": "0", "body": "I suppose that the arguments will be in range \\$\\left<0, 2\\pi\\right>\\$. I am sorry that I didn't mention that information in my question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T06:50:04.850", "Id": "521507", "Score": "0", "body": "Ok, but why then handle the case of negative values of `x`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T07:04:13.517", "Id": "521510", "Score": "0", "body": "I am sorry for misleading comment above. I suppose the arguments from range \\$\\left<-2\\pi, 2\\pi\\right>\\$." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T07:15:15.600", "Id": "521511", "Score": "0", "body": "As far as the \\$\\sin(2\\pi)\\$. I will have `index_01` with `0` value and `index_02` with value `1`. Based on the table above the linear interpolation gives \\$\\frac{lut[1] - lut[0]}{step}\\cdot(2\\pi - 0) + lut[0] = \\frac{0.0245 - 0.0000}{0.0246}\\cdot(2\\pi - 0) + 0.0000 = 6.2475\\$. Which is obviously wrong value." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T22:04:11.213", "Id": "521584", "Score": "1", "body": "@L3sek You already transform arguments from `[-2π,2π]` so that they end up in `[0,2π]`. G.Sliepen is suggesting a few more transformations so that your values end up in `[0,π/2]`, allowing you to have four times as many values in the table without needing to increase its space." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T03:11:56.073", "Id": "521664", "Score": "0", "body": "@L3sek: The transformation suggested in Teepeemm's comment is called \"range reduction\", taking advantage of periodicity and symmetry of the sine function. It's problematic for inputs values near Pi, because subtracting two nearby floats leaves very few significant bits. (https://randomascii.wordpress.com/2014/10/09/intel-underestimates-error-bounds-by-1-3-quintillion/). But you'll eventually have the same problem doing a LERP for `sin(Pi +- tiny_amount)`, if you care about relative error, because sin(pi) = 0 but its slope is at a maximum around that point." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T20:10:49.247", "Id": "264070", "ParentId": "264065", "Score": "21" } }, { "body": "<p><strong><code>double</code> vs. <code>float</code></strong></p>\n<p>Given the low precision OP's linear interpolation approach, <code>double lut[TABLE_SIZE]</code> could use <code>float lut[TABLE_SIZE]</code>. Or perhaps use a 2x <code>TABLE_SIZE</code> to maintain the same code space, but gain accuracy?</p>\n<p><strong><code>-0.0</code></strong></p>\n<p>To provide <code>sine(-0.0, ...)</code> --&gt; -0.0, use signbit test rather than a <code>x &lt; 0</code> test.</p>\n<p><strong>3.14 vs 3.1415926535897932384626433832795</strong></p>\n<p>Use a better machine pi.<br />\nRecommend at least the precision of <code>double</code>.</p>\n<p><strong>Magic number</strong></p>\n<p>Why 255 in <code>#define STEP_SIZE (2*PI/255)</code>? I'd expect <code>#define STEP_SIZE (2*PI/(TABLE_SIZE-1))</code></p>\n<p><strong>Reduce accumulated error</strong></p>\n<p>Rather than 255 in <code>(2*PI/255)</code>, consider a power-of-two to not introduce additional calculation error.</p>\n<p><strong>times vs divide</strong></p>\n<p>Consider multiplication is speedier.</p>\n<pre><code>// uint8_t index_01 = x/STEP_SIZE;\nuint8_t index_01 = x*STEP_SIZE_INVERSE;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T00:14:02.443", "Id": "264077", "ParentId": "264065", "Score": "7" } }, { "body": "<p>The <code>STEP_SIZE</code> value is tightly coupled with my doubt. In case the table covers <span class=\"math-container\">\\$\\left&lt;0, 2\\pi\\right&gt;\\$</span> with 256 values it would make more sense to have <code>#define STEP_SIZE (2*PI/256)</code> (because of 256 values divide unit circle into 256 segments of <span class=\"math-container\">\\$\\frac{2\\pi}{256}\\,\\mathrm{rad}\\$</span> each) instead of <code>#define STEP_SIZE (2*PI/255)</code>.</p>\n<p>The problem which I have with <code>#define STEP_SIZE (2*PI/256)</code> is that in case <code>x</code> is <code>2*PI</code> then <code>uint8_t index_01</code> overflows to <code>0</code> and then <code>uint8_t index_02</code> contains <code>1</code>. So the interpolation takes place between wrong look-up table entries. Let's say I would use <code>uint16_t</code> for <code>index_01</code> and <code>index_02</code> instead of <code>uint8_t</code> I would have for <code>2*PI</code> argument <code>index_01</code> with value <code>256</code> (so I would need one additional entry in the look-up table) and then I would need to somehow force wrapping up the <code>index_02</code> containing <code>257</code> to <code>0</code> which I could probably do in this manner:</p>\n<pre><code>#define TABLE_SIZE 257\n#define STEP_SIZE (2*PI/256)\n\ndouble lut[TABLE_SIZE] = {\n 0.0000, 0.0245, 0.0490, 0.0735, 0.0980, 0.1223, 0.1467, 0.1709, \n 0.1950, 0.2190, 0.2429, 0.2666, 0.2901, 0.3135, 0.3367, 0.3597, \n 0.3825, 0.4050, 0.4274, 0.4494, 0.4712, 0.4927, 0.5139, 0.5348, \n 0.5553, 0.5756, 0.5954, 0.6150, 0.6341, 0.6529, 0.6713, 0.6893, \n 0.7068, 0.7240, 0.7407, 0.7569, 0.7727, 0.7881, 0.8029, 0.8173, \n 0.8312, 0.8446, 0.8575, 0.8698, 0.8817, 0.8930, 0.9037, 0.9140, \n 0.9237, 0.9328, 0.9413, 0.9493, 0.9568, 0.9636, 0.9699, 0.9756, \n 0.9806, 0.9852, 0.9891, 0.9924, 0.9951, 0.9972, 0.9988, 0.9997, \n 1.0000, 0.9997, 0.9988, 0.9974, 0.9953, 0.9926, 0.9893, 0.9854, \n 0.9810, 0.9759, 0.9703, 0.9640, 0.9572, 0.9498, 0.9419, 0.9333, \n 0.9243, 0.9146, 0.9044, 0.8937, 0.8824, 0.8706, 0.8583, 0.8454, \n 0.8321, 0.8182, 0.8039, 0.7890, 0.7737, 0.7580, 0.7417, 0.7251, \n 0.7080, 0.6904, 0.6725, 0.6541, 0.6354, 0.6162, 0.5967, 0.5769, \n 0.5566, 0.5361, 0.5152, 0.4941, 0.4726, 0.4508, 0.4288, 0.4065, \n 0.3840, 0.3612, 0.3382, 0.3150, 0.2917, 0.2681, 0.2444, 0.2205, \n 0.1966, 0.1724, 0.1482, 0.1239, 0.0996, 0.0751, 0.0506, 0.0261, \n 0.0016, -0.0229, -0.0475, -0.0719, -0.0964, -0.1208, -0.1451, -0.1693, \n -0.1934, -0.2174, -0.2413, -0.2650, -0.2886, -0.3120, -0.3352, -0.3582, \n -0.3810, -0.4036, -0.4259, -0.4480, -0.4698, -0.4913, -0.5125, -0.5334, \n -0.5540, -0.5743, -0.5942, -0.6137, -0.6329, -0.6517, -0.6701, -0.6881, \n -0.7057, -0.7229, -0.7396, -0.7559, -0.7717, -0.7871, -0.8020, -0.8164, \n -0.8303, -0.8437, -0.8566, -0.8690, -0.8809, -0.8923, -0.9031, -0.9133, \n -0.9230, -0.9322, -0.9408, -0.9488, -0.9563, -0.9632, -0.9695, -0.9752, \n -0.9803, -0.9849, -0.9888, -0.9922, -0.9950, -0.9971, -0.9987, -0.9996, \n -1.0000, -0.9998, -0.9989, -0.9975, -0.9954, -0.9928, -0.9895, -0.9857, \n -0.9813, -0.9762, -0.9706, -0.9644, -0.9577, -0.9503, -0.9424, -0.9339, \n -0.9249, -0.9153, -0.9051, -0.8944, -0.8832, -0.8714, -0.8591, -0.8463, \n -0.8330, -0.8191, -0.8048, -0.7900, -0.7747, -0.7590, -0.7428, -0.7262, \n -0.7091, -0.6916, -0.6736, -0.6553, -0.6366, -0.6175, -0.5980, -0.5782, \n -0.5580, -0.5374, -0.5166, -0.4954, -0.4740, -0.4522, -0.4302, -0.4080, \n -0.3854, -0.3627, -0.3397, -0.3166, -0.2932, -0.2696, -0.2459, -0.2221, \n -0.1981, -0.1740, -0.1498, -0.1255, -0.1011, -0.0767, -0.0522, -0.0277,\n 0.0000\n};\n \nuint16_t index_01 = x/STEP_SIZE;\nuint16_t index_02 = index_01 + 1;\nif (index_02 == TABLE_SIZE) {\nindex_02 = 0;\n}\n</code></pre>\n<p>The reason for choosing <code>#define STEP_SIZE (2*PI/255)</code> was to avoid the <code>if</code> statement for wrapping-up the <code>index_02</code>. But when I am writting this edit I realized that the second variant is probably better because it doesn't bring the error and it is more comprehensible.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T05:10:53.970", "Id": "264082", "ParentId": "264065", "Score": "3" } }, { "body": "<p>One thing to add to what's been said already:</p>\n<pre><code>if (negateTableValue) {\n return -aux;\n } else {\n return aux;\n } \n</code></pre>\n<p>There's a lot of cognitive overhead to read this, when its meaning is very simple. As such, it's much clearer to write as:</p>\n<pre><code>return negateTableValue? -aux : aux;\n</code></pre>\n<p>You're not doing two arbitrary different things; you are returning, period. Pushing the condition into the return value itself takes it out of the main-line level of reading the code.</p>\n<hr />\n<p>Meanwhile, I note that you wrote this as an exercise... but I wonder, what might you really use this for?</p>\n<p>I imagine a situation like a small microcontroller that doesn't have floating-point hardware, and it's being used to decide how to move a robot limb or something so the accuracy doesn't need to be a huge number of significant digits.</p>\n<p>As such:</p>\n<h3 id=\"make-the-domain-type-a-template-argument-mnwg\">make the domain type a template argument.</h3>\n<p>You might be using your own fixed-point type, or your own take on &quot;floating&quot; point that only has a few different ranges it works in rather than general exponent, taylored to the needed precision at small angles vs large angles of the physical model.</p>\n<h3 id=\"make-the-table-size-a-non-type-template-argument-i5ee\">make the table size a (non-type) template argument.</h3>\n<p>Likewise, how much precision you actually need can be specified as needed for that particular project. If you are <em>generating</em> the table, using <code>constexpr</code> code, this is especially useful. If you are to explicitly give the table as you do in the original post, then use the actual number of values present to pick up on the table size.</p>\n<h3 id=\"make-the-domain-configurable-1gk4\">make the domain configurable</h3>\n<p>If you only have small angle deflections, you don't need to waste space in the table for the entire quarter-circle. Maybe it only needs to handle 10° max, e.g. you're modeling the movement of a clock pendulum. Or, perhaps the project only needs to work with angles between 35° and 55°.\nSo, give it arguments to configure the range of angles it is able to handle.</p>\n<h2 id=\"how-to-package-a-configurable-library-7qjh\">how to package a configurable library</h2>\n<p>The simplest thing is to use a class template. The table and helper functions are private members of the class.</p>\n<pre><code>using TestSign1 = fast_sign_library&lt;myfixed_t, 256, 0, 90&gt;; // used degrees so it can take ints easily. That's independent of what sin(θ) actually takes.\n\nmyfixed_t angle= .......;\nmyfixed_t sn_a = TestSign1::sin(angle);\n</code></pre>\n<p>You can further wrap that in a small inline function to give it a simple name.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T22:24:40.000", "Id": "264103", "ParentId": "264065", "Score": "3" } }, { "body": "<p>Additional to what is already said, make explicit that you are rounding downwards with <code>floor</code>, and simplify the interpolation computation as a weighted average:</p>\n<pre><code>double index_x = x / STEP_SIZE;\nuint8_t index_01 = floor(index_x);\nuint8_t index_02 = index_01 + 1;\n\ndouble aux = lut[index_01] * (index_02 - index_x) + lut[index_02] * (index_x - index_01);\n</code></pre>\n<p>Instead of a boolean <code>negateTableValue</code> you could use a double <code>sign</code>, to make it easier to read (for me, although that may be a personal preference):</p>\n<pre><code>double sign = 1;\nif (x &lt; 0) {\n sign = -1;\n x = -x;\n}\n...\nreturn sign * aux;\n</code></pre>\n<p>You should also make sure it works for values outside the -2π..2π range, but I leave that up to you as an exercise.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T15:42:52.167", "Id": "521627", "Score": "1", "body": "I too was going to mention something about using `fmod()` to support the full range of input, but I forgot, so thank you for adding that." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T15:32:17.667", "Id": "264119", "ParentId": "264065", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T15:59:57.387", "Id": "264065", "Score": "10", "Tags": [ "c++", "mathematics", "lookup", "interpolation" ], "Title": "Sine function calculated via look-up table and linear interpolation" }
264065
<p>I started learning MVVM and API data fetching, so I made this code:</p> <p>Function <code>loadDirector</code> in which <code>directorName</code> value is modified with fetched data:</p> <pre><code>func loadDirector(id: Int, completed: @escaping () -&gt; ()) { homeRepository.getDirector(id: id){ (creditReponse) -&gt; (Void) in self.directorName = &quot;&quot; creditReponse?.crew.forEach({ singleValue in if singleValue.knownForDepartment == .directing { self.directorName = singleValue.name } }) completed() } } </code></pre> <p>Function <em>getDirector</em> which is used for data fetch from Internet:</p> <pre><code>func getDirector(id:Int, _ completed: @escaping (CreditsResponse?) -&gt; (Void)) { movieServiceAPI.fetchData(from: NetworkData.directorUrl(id: id).value, by: completed) } </code></pre> <p>I am using <code>loadDirector</code> function in <code>didSelectRowAt</code> tableview function from my main VC:</p> <pre><code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let movie = homeViewModel.movieList[indexPath.row] homeViewModel.loadDirector(id: movie.id, completed: { self.changeVC(movie: movie, director: (self.homeViewModel.directorName), groups: self.homeViewModel.setupGenres(groups: movie.genreIds), movieIndex: indexPath.row) }) } </code></pre> <p>Code is working fine, but my question is how I can refactor code to switch completion handler from tableview function to viewmodel file so I can make call like this:</p> <pre><code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let movie = homeViewModel.movieList[indexPath.row] homeViewModel.loadDirector(id: movie.id) self.changeVC(movie: movie, director: (self.homeViewModel.directorName), groups: self.homeViewModel.setupGenres(groups: movie.genreIds), movieIndex: indexPath.row) }) } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-03T00:07:32.810", "Id": "524702", "Score": "1", "body": "To implement MVVM correctly you need to use a binding framework like Combine or Reactive Swift to bind code to the change of the director property. Without doing this, your first code is correct; You are initiating an asynchronous operation, so you need a completion handler to respond once the asynchronous operation is complete." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-08T22:59:43.237", "Id": "525128", "Score": "1", "body": "The idea of this site is to post working code for review. You have posted snippets of code and none of it compiles." } ]
[ { "body": "<p>The basic premise behind MVVM is that you have a ViewModel that tells the views in the view controller how they should look. The only properties that your view controller should have are the views it contains and a single view model object. No other properties should exist in it. Your view controller should be as dumb as possible...</p>\n<p>For example, your <code>tableView(_:didSelectRowAt:)</code> method should look like this:</p>\n<pre><code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {\n viewModel.selected(indexPath: indexPath)\n}\n</code></pre>\n<p>That's it.</p>\n<p>In your view controller's viewDidLoad, you would have something like this:</p>\n<pre><code>viewModel.subscribe { view in\n // here you would update all your views' properties based on the values in the `view` struct.\n // call `tableView.reloadData()` if a Bool in your view indicates that you should.\n // make sure you use weak or unowned self inside this closure.\n}\n</code></pre>\n<p>To populate your table view, you would have something like:</p>\n<pre><code>func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {\n viewModel.numberOfRowsInSection(section)\n}\n</code></pre>\n<p>and</p>\n<pre><code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {\n let cell = tableView.dequeueReusableCell(withIdentifier: &quot;cellTypeIdentifier&quot;, for: indexPath)\n let cellView = viewModel.cellViewForRowAt(indexPath)\n cell.configure(with: cellView)\n return cell\n}\n</code></pre>\n<p>Only reference your viewModel once in each method and don't store other properties in your view controller (other than the views) and you will be much closer to properly implementing the pattern.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T15:47:55.267", "Id": "528282", "Score": "0", "body": "As I mentioned in the comment, the `view` is a struct that contains the values needed to update the view. Likely just a bunch of Strings and Bools. I'd love to see your answer showing the difference between what I have a MVVM." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T16:49:46.047", "Id": "528283", "Score": "0", "body": "Re `viewModel.update { view in ... }`, my minor observation is merely that the choice of a parameter name of `view` for a struct with lots of values, none of which are views, is curious naming choice. Hence my suggestion of something like `model` (or `value` or `movie` or whatever)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T16:49:56.717", "Id": "528284", "Score": "0", "body": "Re: MVVM, see Paulw11’s comment above. MVVM entails _data binding,_ which you are not doing here. See https://medium.com/@dev.omartarek/mvp-vs-mvvm-in-ios-using-swift-337884d4fc6f or https://medium.com/@ahmedragabissa/mvp-vs-mvvm-in-ios-development-450d354300df or https://www.appventurez.com/blog/ios-architecture-patterns/. Often frameworks like React or Combine are used to simplify this. Again, no criticism intended re your pattern here (it is actually my preferred pattern), but just that most would not consider it MVVM." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T17:19:30.677", "Id": "528287", "Score": "1", "body": "Interesting nuance. I *am* using data binding just like in the example of your first article, except I call the binding `update` instead of `subscribe` and the binding is to the entire view model as a unit instead of to each individual property. I can see where that's enough of a difference that it could be considered an entirely different architecture. I transitioned from code like the above to a full Rx(Swift) implementation for my architecture quite a while ago..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T15:16:51.533", "Id": "528361", "Score": "0", "body": "I would suggest `[weak self]` in the `subscribe` closure to avoid strong reference cycle." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-08T23:16:00.007", "Id": "265864", "ParentId": "264069", "Score": "1" } }, { "body": "<p>What I am missing in your code, is a clear definition of the <em>what</em> the view (which is also your View Controller) should render. That value basically constitutes the &quot;binding&quot;.</p>\n<p>Let's give it a name and make a struct for this, <code>struct ViewState {...}</code>.</p>\n<p><strong>Introducing ViewState</strong></p>\n<p>From the <em>perspective of the View</em> this is the &quot;single source of truth&quot;. A view does not know or need anything else. The view state completely determines how it renders itself.</p>\n<p>The view state is const, means, the view will not mutate it. However, the view (ViewController) will maintain a copy of it in a property and updates the copy whenever it finished rendering the new state:</p>\n<pre><code>private var viewState: ViewState = .init()\n</code></pre>\n<p>It's obvious, that the view state gets generated by the view model and the view <em>observes</em> it. When the value changes, the view renders the new view state, possibly performing nice animations from the difference of the new and the old view state.</p>\n<p><strong>Actions</strong></p>\n<p>What's also required is a means to signal &quot;events&quot; (aka &quot;actions&quot;) from the view (a user clicks the &quot;Submit&quot; button, etc.) to the view model.</p>\n<p>That means, your View Model should have corresponding functions which perform such events respectively actions. Those can also have parameters.</p>\n<p><strong>Crafting a ViewState</strong></p>\n<p>When I look into your code, your view state is literally &quot;anaemic&quot; ;)\nI mean, you should enrich it with more information, so the view can render appropriately.</p>\n<p>As your function which fetches data is asynchronous, you have an initial situation in your view which shows &quot;no content&quot;. The view must know how to draw absent data - and the view model should tell the view what to render in this case.</p>\n<p>Your users also may benefit from the fact, that they get informed when the view is loading data - means, you may show an appropriate loading state.</p>\n<p>Finally, your load function may fail. It also might be a good idea to show an error to the user.</p>\n<p>So, let's gather this together and let's define the enriched view state. First, lets try to identify the various states a view may be in:</p>\n<p>DirectorView view state:</p>\n<pre><code>enum ViewState {\n case initial\n case loading\n case error\n case idle\n}\n</code></pre>\n<p>Well, the view state is not complete yet. We still missing the &quot;data&quot; which should be rendered. In your code, you seem to just need a String, the &quot;directorName&quot;:</p>\n<pre><code>enum ViewState {\n case initial\n case loading(name: String?)\n case error(name: String?, error: Error)\n case idle(name: String?)\n\n init() { self = .initial }\n}\n</code></pre>\n<p><strong>Applying View Updates</strong></p>\n<p>If I am not missing something, you should be able to nicely draw any state of your Director View now from just taking the view state from above.</p>\n<p>The good thing also with using an Enum, it's basically <em>impossible</em> to set a state which is not legally covered by the view state - means, your view will never be in some &quot;illegal&quot; state.</p>\n<p>How the view is rendering this, is of course the ViewController and its view's part. Usually, you will implement a function in your view controller, like:</p>\n<pre><code>func update(new: ViewState, old: ViewState) -&gt; Void\n</code></pre>\n<p>You can imagine easily, I guess, that you can calculate a diff of new and old, and then apply nice animations for the changed content.</p>\n<p>After the update function returns, you set the new view state in the view controller. Remember, that the ViewController maintains a copy of view state (UIKit only).</p>\n<p><strong>Subtleties</strong></p>\n<p>In UIKit, you may face a couple subtle issues here: since animations may be asynchronous you should take care of that. So, <code>update</code> may have a completion handler and update functions should not overlap! Well, in general, but maybe not always... I won't go into details here, though.</p>\n<p><strong>View Model</strong></p>\n<p>As said in the beginning, your ViewModel generates the view state and provides functions which perform &quot;actions&quot; which get triggered by the view or elsewhere.</p>\n<p>Given you can use Combine a simple View Model may look like this:</p>\n<pre><code>final class ViewModel: ObservableObject {\n @Published private(set) var viewState: ViewState = .init()\n\n func load() { ... }\n func dismissError() { ... }\n}\n</code></pre>\n<p>What you have to do, is to move your fetch function to the view model, basically somehow into the new <code>load</code> function:</p>\n<p>You execute the &quot;load&quot; event taking the <em>current</em> view state into account, and generate a new view state.</p>\n<p>There are various ways one can implement this. I personally prefer to use a FSM. Here, I use a more &quot;free style&quot; way to implement it:</p>\n<pre><code>func load() {\n guard case .loading != self.viewState else {\n return \n } \n guard case .error != self.viewState else {\n return\n }\n let prevName: String? = self.viewState.name // defined in an extension\n newViewState = .loading(name: prevName)\n \n do {\n let director = try await fetchDirector()\n self.viewState = .idle(name: director.name)\n } catch {\n self.viewState = .error(name: prevName, error: error)\n } \n} \n\n</code></pre>\n<p>So, this should give you an idea how to implement the view model's action functions. It's not complete yet, though. You need to implement the <code>dismissError</code> otherwise, you stuck in your error state.</p>\n<p><strong>What's next you can consider to refactor:</strong></p>\n<p><code>load</code> is just handling a certain event, namely <code>load</code>, we might now consider a more general function <code>perform</code> that handles <em>all</em> events:</p>\n<pre><code>static func perform(old: ViewState, event: Event) \n</code></pre>\n<p>where Event might be an Enum:</p>\n<pre><code>enum Event {\n case load \n case dismissError\n}\n</code></pre>\n<p>Here, you switched to an &quot;event driven approach&quot;. With hat technique, you can easily implement your &quot;logic&quot; with Swift Combine.</p>\n<p><strong>More Refactoring Using &quot;Side Effects&quot;</strong></p>\n<p>Note, this is more advanced, and I only give some ideas. Doing research in this area is recommended.</p>\n<p>A side effect is simply everything that access the &quot;outer world&quot; - where the inner world is your view model. So, reading a date, calling a network endpoint, printing to the console, getting a random Int, this <em>all</em> are side effects.</p>\n<p>It would be nice to have a way to configure the concrete side effects, because this tremendously simplifies testing.</p>\n<p>So, this might require some more changes in the <code>perform</code> function: it should become <em>pure</em> and synchronous and most importantly, it should not start async tasks like in the former implementation, but rather do it in an &quot;indirect way&quot;:</p>\n<pre><code>func update(old: ViewState, event: Event) -&gt; (ViewState, Command)\n</code></pre>\n<p>Where &quot;Command&quot; is a representation of a &quot;Side Effect&quot;, which get started later in the processing and the task's (eventual) result, an Event variable, gets fed into the <code>update</code> function again.</p>\n<p>That also means in your case, you would need a new Event case which represents the result or the &quot;Output&quot; of your fetch function:</p>\n<pre><code>enum Event {\n // Actions:\n case load \n case dismissError\n\n // Outputs from &quot;Side Effects&quot;:\n case data(Director)\n case error(error: Error)\n}\n</code></pre>\n<p>Since update now only depends on its input parameters and does not perform any side effects, it becomes super easy to test (that way, you made the function <code>update </code> a <em>pure</em> function). Note, this update function contains the <em>whole</em> presentation logic of the view model.</p>\n<p>Usually, your View Model gets a list of concrete Side Effects when it is initialised. So, using &quot;Side Effects&quot; you can use this as a &quot;Dependency Injection Point&quot;, where you can inject Mocks for testing.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-19T12:18:09.470", "Id": "268146", "ParentId": "264069", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T19:27:30.903", "Id": "264069", "Score": "4", "Tags": [ "swift", "ios" ], "Title": "Fetching data closure completion" }
264069
<p>I'm <a href="https://commons.wikimedia.org/wiki/File:Julia_set_for_f(z)%3D1_over_(z3%2Ba*z%2B_b)_with_a_%3D_2.099609375_and_b_%3D_0.349609375_with_critical_orbits.png" rel="nofollow noreferrer">making images</a>. My steps are:</p> <ul> <li>create PGM files using a C program</li> <li>convert/resize PGM to PNG using Image Magic</li> <li>remove (big) PGM files</li> </ul> <p>To do it I use Make and a Bash script.</p> <p>The Makefile is very simple:</p> <pre><code>all: chmod +x d.sh ./d.sh </code></pre> <p>Most things are done by the script:</p> <pre class="lang-bsh prettyprint-override"><code>#!/bin/bash # script file for BASH # which bash # save this file as d.sh # chmod +x d.sh # ./d.sh # checked in https://www.shellcheck.net/ printf &quot;make pgm files \n&quot; gcc f.c -lm -Wall -march=native -fopenmp if [ $? -ne 0 ] then echo ERROR: compilation failed !!!!!! exit 1 fi export OMP_DISPLAY_ENV=&quot;TRUE&quot; printf &quot;display OMP info \n&quot; printf &quot;run the compiled program\n&quot; time ./a.out &gt; a.txt export OMP_DISPLAY_ENV=&quot;FALSE&quot; printf &quot;change Image Magic settings\n&quot; export MAGICK_WIDTH_LIMIT=100MP export MAGICK_HEIGHT_LIMIT=100MP printf &quot;convert all pgm files to png using Image Magic v 6 convert \n&quot; # for all pgm files in this directory for file in *.pgm ; do # b is name of file without extension b=$(basename &quot;$file&quot; .pgm) # convert using ImageMagic convert &quot;${b}&quot;.pgm -resize 2000x2000 &quot;${b}&quot;.png echo &quot;$file&quot; done printf &quot;delete all pgm files \n&quot; rm ./*.pgm echo OK printf &quot;info about software \n&quot; bash --version make -v gcc --version convert -version convert -list resource # end </code></pre> <p>I do not know Make well so I used Bash which I know better. It works well for me, but I read about Make and CMake. Should I change it?</p> <hr /> <h2 id="naive-explanation-hdfr">naive explanation:</h2> <ul> <li>My program is small (one file).</li> <li>The dependency tree is very simple (2 libraries which I do not have to recompile).</li> <li>Compilation time is very short, so I do not need a staged compilation</li> <li>Usually, I create a directory with a descriptive name for the program so the files (now 3) do not need descriptive names and I use short names with an extension that explains the function of the file.</li> </ul> <p>I like that I can run all the tasks with one command (with the easy name <code>make</code>) and go away.</p>
[]
[ { "body": "<ul>\n<li>Your <code>chmod</code> needs to go away; <code>d.sh</code> should already have the correct permissions, including when extracted from a source archive</li>\n<li>You should probably delete all of your output diagnostic fluff.</li>\n<li><code>f.c</code> and <code>d.sh</code> are very bad filenames. The former should probably be renamed to <code>fractal.c</code> or somesuch.</li>\n<li>You've mis-used make. The whole point of make is to express a dependency tree, and to be able to ask for anything in that tree to be generated, in turn generating any missing or out-of-date dependencies on the filesystem. You need to re-think output files (e.g. <code>png</code>) to be make targets, input files (<code>.pgm</code>, <code>.c</code>) to be inputs to recipes, and programs <code>gcc</code> and <code>convert</code> to be the commands within those recipes. Once done, your bash script can go away entirely.</li>\n<li>Don't use <code>a.out</code>. Give your binary a meaningful name.</li>\n<li>A side-effect of the above is that checking like this:</li>\n</ul>\n<pre><code>if [ $? -ne 0 ]\nthen\n echo ERROR: compilation failed !!!!!!\n exit 1\nfi\n</code></pre>\n<p>can be deleted; <code>make</code> is smart enough to understand when commands fail.</p>\n<p>Re. image filenames such as <code>1_4000_Fatou_abi_LSCM_zp_cr</code>: you ask</p>\n<blockquote>\n<p>do I have to list manually all the files or can I use wildcards like *.pgm ?</p>\n</blockquote>\n<p>It depends on the desired invocation of your makefile. If you want to start with an empty directory and magically <code>make</code> and have all of your images generate and convert, then you have to manually list all of the file stems in your makefile. If instead you're comfortable with an invocation that looks like</p>\n<pre><code>make 1_4000_Fatou_abi_LSCM_zp_cr.png\n</code></pre>\n<p>then you do not have to list out all of your stems. Either you would have your current program just generate all of them (as it would happen now), or (probably better) rework your program so that it accepts a command-line argument and generates a single image on demand. The latter would be much easier to code a meaningful makefile for.</p>\n<p>If I were to take a guess, your dependency tree basically looks like this. Beware that it's half untested, and in particular <code>$(IMAGES)</code> will change based on a few factors including whether you know your image file stems.</p>\n<pre><code>#!/usr/bin/make -f\n\nexport\n\nCFLAGS=-O3 -lm -Wall -march=native -fopenmp --std=c17\nOMP_DISPLAY_ENV=FALSE\nMAGICK_WIDTH_LIMIT=100MP\nMAGICK_HEIGHT_LIMIT=100MP\n\nIMAGES=image1 image2\nPGMS=$(IMAGES:=.pgm)\nPNGS=$(IMAGES:=.png)\n\n\nall: $(PNGS)\n\n%.png: %.pgm\n convert $^ -resize 2000x2000 $@\n\n$(PGMS): fractal\n ./$^\n\nfractal: fractal.o\n gcc $$CFLAGS -o $@ $^\n\n%.o: %.c\n gcc $$CFLAGS -o $@ $^ -c\n\nclean:\n rm -f fractal *.o *.pgm *.png\n</code></pre>\n<p>Output:</p>\n<pre><code>$ make\ngcc $CFLAGS -o fractal.o fractal.c -c\ngcc $CFLAGS -o fractal fractal.o\n./fractal\nconvert image1.pgm -resize 2000x2000 image1.png\n</code></pre>\n<p>(<code>convert</code> then fails for me due to it being fed a dummy image but the concept is there.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T14:46:35.763", "Id": "521543", "Score": "0", "body": "Thx for the answer . In \"IMAGES=image1 image2\" do I have to list manually all the files or can I use wildcards like *.pgm ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T14:47:07.550", "Id": "521545", "Score": "0", "body": "Depends. What are the image names? How many are there?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T14:51:24.743", "Id": "521546", "Score": "0", "body": "How many : my record is 39 . https://github.com/adammaj1/implodedcauliflower" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T14:52:36.757", "Id": "521547", "Score": "0", "body": "Names are descriptive, like 1_4000_Fatou_abi_LSCM_zp_cr.pgm" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T15:29:31.873", "Id": "521549", "Score": "0", "body": "@Adam See edit; there are a few ways you can go but none of them involve wildcards" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T08:26:20.493", "Id": "521607", "Score": "0", "body": "If you have `CC=gcc`, then you don't need the rules for `fractal` or `%.o`, because Make's built-in rules will do a better job (in particular, putting the libraries into `$(LIBS)` will put them _after_ our own files, ensuring correct linking). Prefer `$(RM)` over `rm -f` for portability, and no need for `-r` there. I also don't see why `fractal` has to be run for every file in `$(PGMS)` - in the original, it only has to run once." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T16:38:41.947", "Id": "521636", "Score": "0", "body": "@TobySpeight re. built-in CC - agreed, but the purpose here was to show an explicit dependency chain since this OP seems new to the concept." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T16:42:33.963", "Id": "521637", "Score": "0", "body": "@TobySpeight re. multiple runs - make is smart enough to see that after the first run, multiple targets are satisfied. e.g. `make image1.pgm image2.pgm` shows `./fractal` / `make: 'image2.pgm' is up to date.`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T06:53:35.347", "Id": "521783", "Score": "0", "body": "My point is that if `image1.pgm` and `image2.pgm` both need remaking, the command will be run for each. Since it only needs to be run once, we need to make an intermediate phony target `$(PGMS): fractal_is_run` and `fractal_is_run:⤶→./$^`." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T23:19:18.850", "Id": "264076", "ParentId": "264071", "Score": "3" } } ]
{ "AcceptedAnswerId": "264076", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T20:13:42.483", "Id": "264071", "Score": "3", "Tags": [ "beginner", "c", "bash", "makefile" ], "Title": "Compiling and running a program to generate fractal images" }
264071
<p>Here is a minimal example of my task...</p> <p>I have four 2-column files. <code>profile1.data</code></p> <pre><code> zone luminosity 1 1 1359.019 2 2 1359.030 3 3 1359.009 4 4 1358.988 5 5 1358.969 6 6 1358.951 7 7 1358.934 8 8 1358.917 9 9 1358.899 10 10 1358.881 </code></pre> <p><code>profile2.data</code></p> <pre><code> zone luminosity 1 1 1357.336 2 2 1357.352 3 3 1357.332 4 4 1357.310 5 5 1357.289 6 6 1357.270 7 7 1357.252 8 8 1357.233 9 9 1357.214 10 10 1357.194 </code></pre> <p><code>profile3.data</code></p> <pre><code> zone luminosity 1 1 1355.667 2 2 1355.687 3 3 1355.667 4 4 1355.644 5 5 1355.622 6 6 1355.602 7 7 1355.582 8 8 1355.562 9 9 1355.541 10 10 1355.520 </code></pre> <p><code>profile4.data</code></p> <pre><code> zone luminosity 1 1 1354.008 2 2 1354.032 3 3 1354.013 4 4 1353.990 5 5 1353.967 6 6 1353.945 7 7 1353.923 8 8 1353.902 9 9 1353.879 10 10 1353.857 </code></pre> <p>I also have a vector named <code>phases</code>. There is one <code>phase</code> value for each <code>profile.data</code></p> <pre><code> rsp_phase1 rsp_phase2 rsp_phase3 rsp_phase4 0.002935897 0.004602563 0.006269230 0.007935897 </code></pre> <p>Finally, there are profile files for one of FOUR sets labeled A to D. Each set's directory, which is named <code>LOGS_A1a</code>, <code>LOGS_B1a</code>, etc. (and contains the profile files), does NOT have the same number of profiles.</p> <p>What I am doing with this data is plotting luminosity vs phase for each zone, and putting one each of the four plots for each set on one canvas altogether.</p> <p><a href="https://i.stack.imgur.com/grx8P.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/grx8P.png" alt="Example of plot with a subplot for each set" /></a></p> <p>For example, to create a luminosity vs phase plot of the first zone, I grab the luminosity value from every profile in the directory at zone 1. This is my first plot. Then I do the same for the other zones. At the moment, I am accomplishing this through for loops in R.</p> <pre><code>convection.sets &lt;- c('A','B','C','D') for (zone_num in 1:4){ png(file.path(paste(&quot;Light_Curve_&quot;&quot;test/Light_Curve_&quot;,&quot;Zone_&quot;,zone_num,&quot;.png&quot;,sep=&quot;&quot;)), width = 1200, height = 960) par(mfrow = c(2, 2)) # Set up a 2 x 2 plotting space par(mar=c(5,4,4,2) + 2) # Control space between subplots for (set in convection.sets){ LOG.directory &lt;- paste0(&quot;LOGS_&quot;,set,&quot;1a/&quot;) hstry &lt;- fread(file.path(LOG.directory, 'history.data'), header=TRUE, skip=5) prof.idx &lt;- fread(file.path(LOG.directory, 'profiles.index'), skip=1, col.names=c('mdl_num', 'priority', 'prof_num')) phases &lt;- hstry$rsp_phase luminosities &lt;- c() for (prof_num in 1:4prof.idx$prof_num) { prof.path &lt;- file.path('LOGS_A1a'LOG.directory, paste0('profile', prof_num, '.data')) if (!file.exists(prof.path)) next #print(prof.path) DF.profile &lt;- fread(prof.path, header=TRUE, skip=5) luminosity &lt;- DF.profile$luminosity[zone_num] luminosities &lt;- c(luminosities, luminosity) # luminosity &lt;- DF.profile[[prof_num]]$luminosity[zone_num] # luminosities &lt;- c(luminosities, luminosity) cat(paste(&quot;Set&quot;,set,&quot;Zone&quot;,zone_num,&quot;prof_num&quot;,prof_num,'\n')) } plot.table &lt;- data.frame(phases, luminosities) o &lt;- order(phases) with(plot.table, plot(x=phases[o], y=luminosities[o], main=paste(&quot;Zone&quot;,zone_num,&quot;Light Curve&quot;,sep=&quot; &quot;), type=&quot;l&quot;, pch=3, lwd = 6, col=&quot;purple&quot;, xlab=expression(&quot;Phase&quot;), ylab=expression(&quot;Luminosity &quot; (L/L['\u0298'])), cex.main=1.60, cex.lab=1.80, cex.axis=1.60)) } dev.off() } </code></pre> <p>As you will realize, it seems that the biggest problem is that I am repeatedly reading the same files into R. This should be done once separately. Is there a way to avoid this and speed it up?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T20:17:16.793", "Id": "264072", "Score": "0", "Tags": [ "r" ], "Title": "R code that creates stellar interior light curves" }
264072
<h2 id="problem-jj2g">Problem</h2> <p>I would like to make an efficient, extensible, and potentially asynchronous parallelizable event system using modern features in <code>c++20</code>.</p> <h2 id="my-solution-gsrl">My solution</h2> <p>I've constructed a templated event struct by category and group:</p> <pre class="lang-cpp prettyprint-override"><code> #include &lt;algorithm&gt; #include &lt;execution&gt; #include &lt;functional&gt; #include &lt;vector&gt; namespace System::Event { enum class Type { Group = 0, Tick, Update, Render, Terminate, Connect, Disconnect, Move, Close, Resize, Refresh, Focus, Defocus, Maximize, Minimize, Restore, Press, Release, Type, Scroll, }; enum class Group { Undefined = 0, Instance = Numerics::Bit(0), // 1 Monitor = Numerics::Bit(1), // 2 Window = Numerics::Bit(2), // 4 Input = Numerics::Bit(3), Keyboard = Numerics::Bit(4), Mouse = Numerics::Bit(5), Controller = Numerics::Bit(6), Button = Numerics::Bit(7), }; Structure::Concept::Tag bitmask(System::Event::Group); } </code></pre> <p>Where the group acts as a type safe bitmask with overloaded operators. (Usage below)</p> <p>The base event class only contains a status member variable (used, unused, lost, etc).</p> <pre class="lang-cpp prettyprint-override"><code> namespace System::Event { template&lt;Type T, Group G&gt; struct Event { System::Structure::Status::Event status; }; } </code></pre> <p>There are various implementations of events, but here is a simple Window Close Event:</p> <pre class="lang-cpp prettyprint-override"><code> namespace System::Event::Window { struct Close : public Event &lt;Type::Close, Group::Instance + Group::Window&gt; { Close() : Event({System::Structure::Status::Event::Unused}) {} class Manager; }; } </code></pre> <p>Now, I want a method to dispatch a <code>Window::Close event</code>.</p> <pre class="lang-cpp prettyprint-override"><code>namespace System::Event::Window { class Close::Manager { private: using Callback = Structure::Callback&lt;System::Event::Window::Close &amp;&gt;; // std::function&lt;&gt; public: void listen(Callback callback) { m_Callbacks.push_back(callback); } void deafen(Callback callback) { m_Callbacks.erase(std::remove_if(std::execution::par_unseq, std::begin(m_Callbacks), std::end(m_Callbacks), [&amp;callback](const Callback &amp; other) { return callback.target&lt;Callback&gt;() == other.target&lt;Callback&gt;(); })); } void queue(Window::Close &amp; event) { m_Event = event; } void latest() { std::for_each(std::begin(m_Callbacks), std::end(m_Callbacks), [&amp;](const Callback &amp; callback) { callback(m_Event); }); } private: std::vector&lt;Callback&gt; m_Callbacks; Window::Close m_Event; }; } </code></pre> <h2 id="usage-ybln">Usage</h2> <p>This is an example unit test. (Not final, demonstrates usage)</p> <pre class="lang-cpp prettyprint-override"><code> auto callback = [](System::Event::Window::Close &amp; event) { EXPECT_TRUE(event.status == System::Structure::Status::Event::Unused); event.status = System::Structure::Status::Event::Used; }; System::Event::Window::Close::Manager manager; manager.listen(callback); manager.latest(); System::Event::Window::Close event; manager.queue(event); manager.deafen(callback); manager.latest(); manager.listen(callback); manager.latest(); </code></pre> <p><a href="https://godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAM1QDsCBlZAQwBtMQBGAFlJvoCqAZ0wAFAB4gA5AAYppAFZdSrZrVDIApACYAQjt2kR7ZATx1KmWugDCqVgFcAtrRC8r6ADJ5amAHLOAEaYxFwArACcpAAOqEKE5rR2ji5uMXEJdN6%2BAU7BoZyRRpgmZnQMBMzEBMnOrrzGmKaJFVUE2f5BIeFRQpXVtakN/e0%2BnXndhREAlEaoDsTIHFI6AMw%2ByI5YANSaqzZswCSECE572JoyAIJrG1uYu/totEvRBELnlzfa6y/3jzZMOImg4yrRPtdbn8HDs9jYqA4XmC2BDvr9NjCHnCAG5NIjEVFfKEY2H7ZhCETVAB0CEJ11ozCcmCE0WYS22uRCeGQQl2AHZ9NdtsLts8%2BkDosRtoj4sBfOhtj4CNtdIQIDK8HLMAqldtxNN%2BYKriKTdtiJgCAtaNtOAC4Xq9kaTZo%2BQARIlur4MpkstkPCrEBymBZYgVfE3e5ms9l2F6YN6G8Om4V9QOmbYAFWYwETntWTuTuyFhYImCc0VUpYBm3JvIuqwuxeTz1eyuwtGcIWYYMerrNmAAjg48OahBBsNtMAaXQXCyK%2BugQCA8EIAPpWZyr7Fw%2Bv12dz7YLpfPXHVPCBdirog70iHgiLkCIrDEVgATx8wCvr%2BimB3nwbjpJged4PkqmDAMQKL7Eej7WCEb4fl%2BP5/gBqH7s6eb7i67qQk22yluWla/k8qgUtsohVIyFohKiJoOPE6jbAcrCsIEbIANa9iBS4IkiiQ4qgeAKhAFGQUypZSjoABs0z/ka2FEvSVG%2BuyAZBpa5pLrGraJnhBEVt2WIkbWma0SKLbxsqqoEE45KcXsfbmkOI7MhAGb4dOYZ4Sa7adpBYJwhmclAaaM4hXOgSELZQjsRABCyd5IoKYlwoALTnNxIBCFRq7knCanBppIDaZZS5ZsAwV4Qp%2BYejhNzXPpREAgVGkcMVdCtku1nRZx2DsEy9ComKpbiJK2x9WWVjKqgP7%2BSQuzaFJ2zjv1U3bKwCBCLeE0DcqxCbZ5%2B70R%2BmZcTBT7we%2B6hIZgV47qtg1oSF5oadafTdtyq4sH092TY92AQO9ZjIF95IEIF5wQBtQjTotd4fSD33g/sQUNhA%2B0w7JNWQp6DVlgZVb5QQaatVpHWlSA3V2eND3I42VzDRKUo7Wt0nbDNXb4gtUkOctLP0Nz62bdttNmgdunGiK0NcdLbMY4BeEvVaQsfNjNy41cjWGc1xPqSGZNxm8XVRdT/N018jOjczosc3Nkl6HzovQyLf17eLYV4cdjHubz51wS%2BV2fgQ363cjNhm5VkvCkrxBvZUwOgz9%2BwR2jQOfUjENo9Dnk2PDCcZyjkMY9MWPyRrWuE/sLX6%2B1hsEMbNmm7TQ10OKVs067gu29280GLzK2d2zzsd7tYswxLJqy6sfayw78tqyaMfWtDCvq3VFdGTY1dFSVRuUybMUj1NLe0G3Y1m%2Bzs095JYQTgPo/DxfxcTyKXs5j70%2BZRdAeIcHP53cnZuT1FYWmVmnRGYNfq7UhuAxOYdUYA2zrsW%2Bed06QMLmjYupdapfA3jrEmNdd7133o3Q%2BKd6aW3PqLNm3cuaaFvv3C%2BQ9hZHwFs/D2UcVYy02sgic899xLxVqvZKmt8ZNSJgQne5M95UzIUAihrcRpUM7rQ%2BaqVHad0fqLdhXlOGCNligqGPC5YHWEeXMR2sJF6ykXXBuPVWHm2uJQ62g84aqKlOlT%2B99WZwy0Z3HR%2B4p4zx4eo/hz1QGxyEWrEReCrGFTakQuxTdXYnzPlKQIqB7CX05r3BsGiH4sKfu7XRdEGLvzOveJc38ELXT/qHKBx9gF6IiXHBGcDM6IOMXDdheSZBmPXhYyuW9dbxINp1Eh9jyEW0UUzbYGSsnuMePWPs3iBZ%2BNHgE8Jr1lpTz4cUmwLpc5GN5A5Xmxd%2Bm4MGZvbeCTpHENkb1eR0zT5KPSZk1g2S7a9kYU7Qp2jikCJaVw05n8wk4wGYRSxVcRmk1ruMh5DjUmvLme8z5187ReIvustamyQHbOOQCMeOdDk7OMdPM5pjonmMhUMm5YyKYIqmU4mZ7d5kfMWfaVZypsVsIBSFN%2Bp1faVNgs%2BGpQcQ4APDk8heIpBGwILjYBBBLQnu3JZ/PpVK6pemUtGf0r5xROCXHSkArRLQnJKSKDcThRSkV5AAJURGYJkL9kwAElaAJDYHgAAXtqLiMhSDhRFAzMw2JDLoEDSlbY7qJKBjeNqSNnCTQZhCE4Hw4bE1zgCCxPAVA8AJpCtVfcVqbUmWwLiAWHC5wCA7CIBUvMA1BuFMIAtUa7VllQLiCNTbtgAFkVwGSWN2qN2BiDEBIK2zhRaQolprGRUd47JIWuTDWrAeb5T%2BszYWPwdBMBbuFNO8FikriRhUnqg1S5y2s10bO21mYQ4uu2AAcXHQ4aIm6QoZm5OxW8AhojoEMredt/tbwpuIGmhkpZ91MToL4Uwt5XQrmeHBgg0He2dr3UxVgcRMPtviL6oDmAqCjgQLeAAYqgZA9EENEco9RvtzBxB4DTQRvtPhmM%2Btw8yfEe6QqiFHFtbY7b2DkkwxmEO0GmDjpYomw99Uri3pMi%2B%2BY76q0ilXURsYCoD3qug%2B696cZnSf05MQbkQgG4QBkLMbYAB6GzNoQroY9VzIzfYTNmYs5wazdntjaBCgAdR8OgVAAB3ZMvN3M8gs9obz9nuAhXddEUEhYIt%2BQ8yQiAqxZghQANKYFfBkqo2mdNubS1FjL3Bst4XQ/RB44XjNlfMxlsIVXOGxmJvYdgUouKRaa9ZCAMloO6FBEQa0oUGtMlM%2BV/rfJWtyaNTCwhdyyrZjmQfWKDB9UEUvRW4hym33YNwqImlxFFUPozLefb76n1mRTDC8au3H0mk2xek1i2iqmvojttaQN6Krwwu6TVx7T26u2C97bIAr30CXIF6woXH2pnUlhnD2wQDbCSxebkD3Wb7HvT%2BLS2GRCXdfdEJc%2BnKiGYMM%2BknMOgvw4ymp5MNhCeYAgAaNHUOCAQBnODssC3JFtU%2B01znS4a21fQNhQ6Ii5xzt5L2tQ2YaIyoPZhEKsvkciCXPLhkwAQhPZFJKPAYbSwgB7aUk6zFWIcS4vz6xCS2BW%2BQOxfKW2%2BeQ927TuHIWCco%2BkpHOcGPWDclN1Gk02JBIKiD%2BKWgEBLdsSd6KB38f2JS9D4WJwq448cSEFSJLQgECrmTxAFgLFk%2BHaTSljWwFhTh6EtsLAzAqBWFj0n63JfHcp/18BDPWenc567CIQGwrzROAw6uXNQ%2BHxAhBGCJcrJiCrhlIOW8MFgjAB8BAHvre%2B/WZgh4Tfmft/sRhreeh%2BhFrt%2BT/Q10xfFFMSP13AgCAQip4r9X2VQLL8cSpP0XXYde/O5ozThqp9ioBP4hA/5VB/5wgAGQzl7v4A4lz/bV7S7V614KhDiYAOCs6w7Bbe7FQs6CyYC7av4IEigZ6c5cTEGNLoSV51Tv7oHrSGR9Bs5d4HgwQ0AL6YBsgICT5LjT5Uaz4gDz6L6nzL6ZRr4b5b6l7Z677Cr77SEd4n7ILn48xhA37DT34yEJ5sxf5O6kFkGmh6GxQUEkHIFkGS7mEHioHJiG7G4cBm7zjCq4imAkAwFH4ZSKHJ6qy0HJi4GhY%2B4iDbCmE0E9pyYiJfC6i2Qb4GHCjMCgioCJ7aH2Sfxn7X4QC86Gru5TSe54GBFYhwzUH0CxGmi1ghBc5FEEBUi/YnIgFg6u5ZHGpC7fbQ4gBi51rwGFiVHVHxz0RcSZG26jJvbdhfbZGtEtoS7K78iA77gDFjHEL%2BH4HM44Za4K665Si2Q65K77ibGK7EBUhR6lgx7GGdHCi7HrEHHMFc6nH1GvYi4gCLH5GTi7ZWHnEQGYHYEQCVE3FvH7EN5N7HFH4/FrEQFEQsHAlbH7GHHN4nGvEglQlXFs5WGCIaplyuhSCzCsDSBhDyCuCyDyCoDSAHJ6BU5CDzCLAFGrCcDyD1z4klykDsQgCRBUhSQyB8h8jcCrBSTcARARCLQyBSQqDSDcC4nSByCkCElSDyDmYBq0lyCzBwCwAwCIAoCoDlh4BdbkCUBoDqldYoCqDqCcDaAyABp5qsASTmYQCBBinyCRQMjECvjSDUmkA6m7QADytAb4NppAWAmxwA7A3p%2BA5ozQuI5m%2BJpAAhoIyw4pYEWJ4ZQegQkEDpdgWA3pxMzGTpGJfAdAjAJeHAPA2ZggIgEg3pSg2gKgagGgfcegKg545mkAswM0YIYZqUC4DkWgJJegxp0pJQeIiQlg1ggwrgnAEZ1gHQuQ%2BQygsQ8QYIQ5U5GQYI45XQBQxQpQLQIwc5I5jQzQ5QIwS5EwK570Aw9gdQygR5owOQy5XAswZJCwSw15QpUgOJpAeJ4pkp4gAAHFJKlNyaWoxEaVSDIIBXzPgHQj8COTBrqXrmsDFkxNWboDSTafSc/swM%2BJQLMIydoB%2BVSKsGEMaVJNoFMHyGyZwIKXGSKaQIamEAGq%2BQSdINKSALKUhaQIqSqfMAQElqhhQLflBaEOWdqIQCQMoPwLmWwPmYKSJS2iWeGSFpBKTlINSZidiaKeGZKW6aCJxezFQHqF%2BT%2BdwH%2BTmABUBTIMtHYLxQtKsDFohXSbMChWhWzo%2BRRVRTRd6ZKQxUxTZQyW4EBasHydoGEFJLhSaXyL5VyY%2BasCpW%2BfRaQHKRiUpVINoJFXRVKTFUhbMKePEBYNwEAA%3D%3D" rel="nofollow noreferrer">Live Example</a></p> <h2 id="commentsquestions-s742">Comments/Questions</h2> <ol> <li>This method will produce a large amount of redundant code, I'd like to make the <code>Manager</code> class a template specialization at some point.</li> <li>This will require each type of event to have a manager. How can I consolidate all Window events into one manager without impacting performance or using runtime polymorphism?</li> <li>I will migrate to use <code>std::ranges</code> after <code>clang</code> supports it.</li> <li>At some point, I'd like to additionally include execution policies in the dispatch methods, I have yet to determine the best choices.</li> <li><code>queue</code> will eventually involve a stack of stored events so that I can determine how to interpolate which events matter if the system is lagging or otherwise. For example if there is a Mouse move from (1,1) to (180,180), with a (1,1) delta, it'd be scaled to frame-rates instead of rendering every delta.</li> <li>I understand this is not the intended use of <code>namespace</code> or <code>class</code> namespaces, it is a personal preference.</li> <li>This is not the best design, I'm exploring, please be critical of all flaws!</li> <li>Owning <a href="https://github.com/Maelkevejen/Andromeda" rel="nofollow noreferrer">repository</a>, for the curious. I am continuing to change the design since this post, however.</li> </ol> <h2 id="notes-pcn1">Notes</h2> <p>I am very intentionally avoiding run time polymorphism. Thank you for reviewing!</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-14T21:05:17.467", "Id": "264073", "Score": "3", "Tags": [ "c++", "game", "template", "event-handling", "c++20" ], "Title": "A Compile-time templated event system and dispatch manager" }
264073
<p>I was trying to make a simple noise visualizer using the <code>noise</code>, <code>pygame</code> and <code>pygame_gui</code> libraries. I wanted it to have UI features like buttons, drop down menus, sliders, etc. And the <code>pygame_gui</code> library is perfect for this.</p> <p>The code is clearly not very clean, so any suggestions are well appreciated.</p> <p><code>noise_visualizer.py</code></p> <pre class="lang-py prettyprint-override"><code>from random import randint, uniform import sys import pygame import pygame_gui from pygame_gui import UIManager from pygame_gui.elements.ui_button import UIButton from pygame_gui.elements.ui_drop_down_menu import UIDropDownMenu from pygame_gui.elements.ui_horizontal_slider import UIHorizontalSlider from pygame_gui.elements.ui_label import UILabel from pygame_gui.elements.ui_panel import UIPanel from pygame_gui.elements.ui_text_entry_line import UITextEntryLine from constants import * import core # --------------------------------------------------------------------------- # pygame.init() screen = pygame.display.set_mode((750, 500)) pygame.display.set_caption(&quot;Noise Visualizer&quot;) clock = pygame.time.Clock() running = True apply_color = APPLY_COLOR use_falloff = USE_FALLOFF map_surf = pygame.Surface((500, 500)) # --------------------------------------------------------------------------- # ui_manager = UIManager((750, 500)) panel = UIPanel( relative_rect=pygame.Rect((MAP_SIZE, 0, *PANEL_SIZE)), manager=ui_manager, starting_layer_height=0, margins={ &quot;left&quot;: 5, &quot;right&quot;: 5, &quot;top&quot;: 5, &quot;bottom&quot;: 5 } ) UILabel( relative_rect=pygame.Rect((0, 0, 240, 27)), manager=ui_manager, container=panel, text=&quot;Map type&quot; ) map_type_menu = UIDropDownMenu( relative_rect=pygame.Rect((0, 27*1, 240, 27)), manager=ui_manager, container=panel, options_list=MAP_OPTIONS, starting_option=MAP_OPTIONS[0] ) UILabel( relative_rect=pygame.Rect((0, 27*2, 120, 27)), manager=ui_manager, container=panel, text=&quot;Tile Size&quot; ) tile_size_entry = UITextEntryLine( relative_rect=pygame.Rect((0, 27*3, 120, 27)), manager=ui_manager, container=panel ) tile_size_entry.set_text(str(TILE_SIZE)) tile_size_entry.set_allowed_characters(&quot;numbers&quot;) UILabel( relative_rect=pygame.Rect((120, 27*2, 120, 27)), manager=ui_manager, container=panel, text=&quot;Seed&quot; ) seed_entry = UITextEntryLine( relative_rect=pygame.Rect((120, 27*3, 120, 27)), manager=ui_manager, container=panel ) seed_entry.set_text(str(SEED)) seed_entry.set_allowed_characters(&quot;numbers&quot;) UILabel( relative_rect=pygame.Rect((0, 27*4, 120, 27)), manager=ui_manager, container=panel, text=&quot;Apply Colors&quot; ) apply_color_button = UIButton( relative_rect=pygame.Rect((120, 27*4, 120, 27)), manager=ui_manager, container=panel, text=str(apply_color) ) UILabel( relative_rect=pygame.Rect((0, 27*5, 120, 27)), manager=ui_manager, container=panel, text=&quot;Falloff Map&quot; ) use_falloff_button = UIButton( relative_rect=pygame.Rect((120, 27*5, 120, 27)), manager=ui_manager, container=panel, text=str(use_falloff) ) UILabel( relative_rect=pygame.Rect((0, 27*6, 120, 27)), manager=ui_manager, container=panel, text=&quot;Scale&quot; ) scale_entry = UITextEntryLine( relative_rect=pygame.Rect((120, 27*6, 120, 27)), manager=ui_manager, container=panel ) scale_entry.set_text(str(SCALE)) scale_slider = UIHorizontalSlider( relative_rect=pygame.Rect((0, 27*7, 240, 27)), manager=ui_manager, container=panel, start_value=SCALE, value_range=SCALE_RANGE ) UILabel( relative_rect=pygame.Rect((0, 27*8, 120, 27)), manager=ui_manager, container=panel, text=&quot;Octaves&quot; ) octaves_entry = UITextEntryLine( relative_rect=pygame.Rect((120, 27*8, 120, 27)), manager=ui_manager, container=panel ) octaves_entry.set_text(str(OCTAVES)) octaves_entry.set_allowed_characters(&quot;numbers&quot;) octaves_slider = UIHorizontalSlider( relative_rect=pygame.Rect((0, 27*9, 240, 27)), manager=ui_manager, container=panel, start_value=OCTAVES, value_range=OCTAVES_RANGE ) UILabel( relative_rect=pygame.Rect((0, 27*10, 120, 27)), manager=ui_manager, container=panel, text=&quot;Persistence&quot; ) persistence_entry = UITextEntryLine( relative_rect=pygame.Rect((120, 27*10, 120, 27)), manager=ui_manager, container=panel ) persistence_entry.set_text(str(PERSISTENCE)) persistence_slider = UIHorizontalSlider( relative_rect=pygame.Rect((0, 27*11, 240, 27)), manager=ui_manager, container=panel, start_value=PERSISTENCE, value_range=PERSISTENCE_RANGE ) UILabel( relative_rect=pygame.Rect((0, 27*12, 120, 27)), manager=ui_manager, container=panel, text=&quot;Lacunarity&quot; ) lacunarity_entry = UITextEntryLine( relative_rect=pygame.Rect((120, 27*12, 120, 27)), manager=ui_manager, container=panel ) lacunarity_entry.set_text(str(LACUNARITY)) lacunarity_slider = UIHorizontalSlider( relative_rect=pygame.Rect((0, 27*13, 240, 27)), manager=ui_manager, container=panel, start_value=LACUNARITY, value_range=LACUNARITY_RANGE ) generate_rand_button = UIButton( relative_rect=pygame.Rect((60, 27*14, 120, 27)), manager=ui_manager, container=panel, text=&quot;Random&quot; ) # --------------------------------------------------------------------------- # def regenerate_map(): global apply_color global use_falloff map_type = map_type_menu.selected_option tile_size = int(tile_size_entry.get_text()) seed = int(seed_entry.get_text()) scale = int(scale_entry.get_text()) octaves = int(octaves_entry.get_text()) persistence = float(persistence_entry.get_text()) lacunarity = float(lacunarity_entry.get_text()) if map_type == &quot;Random Noise Map&quot;: noise_map = core.random_noise(500//tile_size, seed) use_falloff_button.enable() scale_entry.disable() scale_slider.disable() octaves_entry.disable() octaves_slider.disable() persistence_entry.disable() persistence_slider.disable() lacunarity_entry.disable() lacunarity_slider.disable() elif map_type == &quot;Perlin Noise Map&quot;: noise_map = core.perlin_noise(500//tile_size, seed, scale, octaves, persistence, lacunarity) use_falloff_button.enable() scale_entry.enable() scale_slider.enable() octaves_entry.enable() octaves_slider.enable() persistence_entry.enable() persistence_slider.enable() lacunarity_entry.enable() lacunarity_slider.enable() elif map_type == &quot;Simplex Noise Map&quot;: noise_map = core.simplex_noise(500//tile_size, seed, scale, octaves, persistence, lacunarity) use_falloff_button.enable() scale_entry.enable() scale_slider.enable() octaves_entry.enable() octaves_slider.enable() persistence_entry.enable() persistence_slider.enable() lacunarity_entry.enable() lacunarity_slider.enable() elif map_type == &quot;Falloff Map&quot;: noise_map = core.generate_falloff_map(500//tile_size) use_falloff_button.disable() scale_entry.disable() scale_slider.disable() octaves_entry.disable() octaves_slider.disable() persistence_entry.disable() persistence_slider.disable() lacunarity_entry.disable() lacunarity_slider.disable() map_size = len(noise_map) if use_falloff and map_type != &quot;Falloff Map&quot;: falloff_map = core.generate_falloff_map(map_size) for x in range(map_size): for y in range(map_size): noise_map[x][y] = max(0, min(noise_map[x][y] - falloff_map[x][y], 1)) if apply_color: color_map = core.generate_color_map(noise_map, REGION_COLORS) for x in range(map_size): for y in range(map_size): color = color_map[x][y] map_surf.fill(color, ((x*tile_size, y*tile_size), (tile_size, tile_size))) else: for x in range(map_size): for y in range(map_size): color = BLACK.lerp(WHITE, noise_map[x][y]) map_surf.fill(color, ((x*tile_size, y*tile_size), (tile_size, tile_size))) def randomize(): map_type = map_type_menu.selected_option if map_type != &quot;Falloff Map&quot;: seed_entry.set_text(str(randint(*SEED_RANGE))) if map_type != &quot;Random Noise Map&quot;: scale_entry.set_text(str(randint(*SCALE_RANGE))) octaves_entry.set_text(str(randint(*OCTAVES_RANGE))) persistence_entry.set_text(str(uniform(*PERSISTENCE_RANGE))) lacunarity_entry.set_text(str(uniform(*LACUNARITY_RANGE))) # --------------------------------------------------------------------------- # regenerate_map() while running: ui_manager.draw_ui(screen) screen.blit(map_surf, (0, 0)) for event in pygame.event.get(): ui_manager.process_events(event) if event.type == pygame.QUIT: running = False if event.type == pygame.USEREVENT: if (event.user_type == pygame_gui.UI_DROP_DOWN_MENU_CHANGED or event.user_type == pygame_gui.UI_TEXT_ENTRY_FINISHED): regenerate_map() elif event.user_type == pygame_gui.UI_HORIZONTAL_SLIDER_MOVED: if event.ui_element == scale_slider: scale_entry.set_text(str(scale_slider.get_current_value())) elif event.ui_element == octaves_slider: octaves_entry.set_text(str(octaves_slider.get_current_value())) elif event.ui_element == persistence_slider: persistence_entry.set_text(str(persistence_slider.get_current_value())) elif event.ui_element == lacunarity_slider: lacunarity_entry.set_text(str(lacunarity_slider.get_current_value())) regenerate_map() elif event.user_type == pygame_gui.UI_BUTTON_PRESSED: if event.ui_element == apply_color_button: if apply_color: apply_color = False apply_color_button.set_text(str(False)) else: apply_color = True apply_color_button.set_text(str(True)) elif event.ui_element == use_falloff_button: if use_falloff: use_falloff = False use_falloff_button.set_text(str(False)) else: use_falloff = True use_falloff_button.set_text(str(True)) elif event.ui_element == generate_rand_button: randomize() regenerate_map() time_delta = clock.tick(60) / 1000.0 ui_manager.update(time_delta) pygame.display.update() </code></pre> <p><code>constants.py</code></p> <pre class="lang-py prettyprint-override"><code>import pygame MAP_SIZE = 500 BLACK = pygame.Color((0, 0, 0)) WHITE = pygame.Color((255, 255, 255)) BLUE = pygame.Color((0, 0, 255)) YELLOW = pygame.Color((255, 255, 0)) GREEN = pygame.Color((0, 255, 0)) GRAY = pygame.Color((55, 55, 55)) REGION_COLORS = { 0.45: BLUE, 0.55: YELLOW, 0.6: GREEN, 0.8: GRAY, 1: WHITE } PANEL_SIZE = (250, 500) MARGIN = 5 ELEMENT_HEIGHT = 27 SEED = 0 MAP_OPTIONS = [ &quot;Random Noise Map&quot;, &quot;Perlin Noise Map&quot;, &quot;Simplex Noise Map&quot;, &quot;Falloff Map&quot; ] TILE_SIZE = 5 APPLY_COLOR = False USE_FALLOFF = False SCALE = 15 OCTAVES = 8 PERSISTENCE = 0.5 LACUNARITY = 2.0 SEED_RANGE = (0, 100) SCALE_RANGE = (1, 30) OCTAVES_RANGE = (1, 8) PERSISTENCE_RANGE = (0.0, 5.0) LACUNARITY_RANGE = (0.0, 5.0) </code></pre> <p><code>core.py</code></p> <pre class="lang-py prettyprint-override"><code>import random import noise import numpy as np import pygame def random_noise(size, seed): random.seed(seed) map_ = np.zeros((size, size)) for x in range(size): for y in range(size): map_[x][y] = random.random() return map_ def perlin_noise(size, seed, scale, octaves, persistence, lacunarity): noise_map = np.zeros((size, size)) for x in range(size): for y in range(size): noise_map[x][y] = noise.pnoise3(x/scale, y/scale, seed, octaves=octaves, persistence=persistence, lacunarity=lacunarity) noise_map[x][y] = (noise_map[x][y] + 1) / 2 return noise_map def simplex_noise(size, seed, scale, octaves, persistence, lacunarity): noise_map = np.zeros((size, size)) for x in range(size): for y in range(size): noise_map[x][y] = noise.snoise3(x/scale, y/scale, seed, octaves=octaves, persistence=persistence, lacunarity=lacunarity) noise_map[x][y] = (noise_map[x][y] + 1) / 2 return noise_map def generate_color_map(noise_map, region_colors): size = len(noise_map) color_map = np.empty((size, size), dtype=pygame.Color) for x in range(size): for y in range(size): for key, value in region_colors.items(): if noise_map[x][y] &lt;= key: color_map[x][y] = value break return color_map def generate_falloff_map(map_size, a=3, b=2.2): falloff_map = np.zeros((map_size, map_size)) for i in range(map_size): for j in range(map_size): x = i / map_size * 2 - 1 y = j / map_size * 2 - 1 value = max(abs(x), abs(y)) falloff_map[i][j] = pow(value, a) / (pow(value, a) + pow(b - b*value, a)) return falloff_map if __name__ == '__main__': m = simplex_noise(5, 5, 5) print(m) <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T02:20:18.127", "Id": "521587", "Score": "0", "body": "This won't run? `simplex_noise` is being called with the wrong number of arguments." } ]
[ { "body": "<ul>\n<li>Your <code>core</code> has what looks to be an abandoned main guard that calls <code>simplex_noise</code> with an incorrect number of arguments. This should probably just be deleted.</li>\n<li>Consider adding PEP484 type hints to all of your function signatures, like <code>def random_noise(size: int, seed: int) -&gt; np.ndarray:</code></li>\n<li>The x/y loops in your noise functions should probably be converted into Numpy vectorized operations</li>\n<li>In <code>noise_visualizer</code>, there are two big chunks of global code that need to be moved into functions - one at the top, and one at the bottom; to be called perhaps &quot;setup&quot; and &quot;main_loop&quot; and invoked from a main guard at the bottom</li>\n<li>Your reliance on a large collection of globals in that module means that it's non-reentrant. There are several ways around this - you can do a bunch of setup in a function, define local closure functions and then return references to those functions; or you can make classes. But as it is now, it's effectively impossible to run two instances of your program in the same process, which hinders testing.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T02:32:16.283", "Id": "264106", "ParentId": "264080", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T02:50:53.430", "Id": "264080", "Score": "1", "Tags": [ "python", "random", "pygame" ], "Title": "A simple noise visualizer made using Pygame GUI" }
264080
<p>This is something I made as an input display resembling NohBoard because I need to make a video for a video game, but it's on Linux which doesn't have any good input display programs. One thing I'm worried about is the way I'm making the scroll wheel flash last for exactly three frames in a 60 FPS recording. I checked how many frames it lasted by checking from a recording, and it seemed to be working fine, but I'm still not 100% sure if it's the best way to achieve making it last for exactly three frames in a 60 FPS recording.</p> <pre class="lang-py prettyprint-override"><code>import pygame import pynput import threading def main(): lock_for_dict = threading.Lock() lock_for_scroll = threading.Lock() pygame.init() win = pygame.display.set_mode((343, 229)) pygame.display.set_caption(&quot;test&quot;) font = pygame.font.Font(pygame.font.get_default_font(), 15) down_font = pygame.font.Font(pygame.font.get_default_font(), 14) # {key_or_mouse_button: (rect_location_and_size, (black_key_text, white_key_text), key_text_location)} # 0 and 1 are left mouse and right mouse shown_keys = { 0: ((250,94,41,41), (font.render(&quot;LM&quot;, True, (0,0,0)), font.render(&quot;LM&quot;, True, (255,255,255))), (260,106)), 1: ((292,94,41,41), (font.render(&quot;RM&quot;, True, (0,0,0)), font.render(&quot;RM&quot;, True, (255,255,255))), (300,106)), &quot;a&quot;: ((72,94,41,41), (font.render(&quot;A&quot;, True, (0,0,0)), font.render(&quot;A&quot;, True, (255,255,255))), (87,106)), &quot;w&quot;: ((114,52,41,41), (font.render(&quot;W&quot;, True, (0,0,0)), font.render(&quot;W&quot;, True, (255,255,255))), (127,64)), &quot;s&quot;: ((114,94,41,41), (font.render(&quot;S&quot;, True, (0,0,0)), font.render(&quot;S&quot;, True, (255,255,255))), (129,106)), &quot;d&quot;: ((156,94,41,41), (font.render(&quot;D&quot;, True, (0,0,0)), font.render(&quot;D&quot;, True, (255,255,255))), (171,106)), &quot;q&quot;: ((72,52,41,41), (font.render(&quot;Q&quot;, True, (0,0,0)), font.render(&quot;Q&quot;, True, (255,255,255))), (87,64)), &quot;e&quot;: ((156,52,41,41), (font.render(&quot;E&quot;, True, (0,0,0)), font.render(&quot;E&quot;, True, (255,255,255))), (171,64)), &quot;r&quot;: ((198,52,41,41), (font.render(&quot;R&quot;, True, (0,0,0)), font.render(&quot;R&quot;, True, (255,255,255))), (213,64)), &quot;f4&quot;: ((198,10,41,41), (font.render(&quot;F4&quot;, True, (0,0,0)), font.render(&quot;F4&quot;, True, (255,255,255))), (210,22)), &quot;tab&quot;: ((10,52,61,41), (font.render(&quot;TAB&quot;, True, (0,0,0)), font.render(&quot;TAB&quot;, True, (255,255,255))), (25,64)), &quot;alt&quot;: ((72,178,61,41), (font.render(&quot;ALT&quot;, True, (0,0,0)), font.render(&quot;ALT&quot;, True, (255,255,255))), (87,190)), &quot;shift&quot;: ((10,136,81,41), (font.render(&quot;SHIFT&quot;, True, (0,0,0)), font.render(&quot;SHIFT&quot;, True, (255,255,255))), (28,148)), &quot;ctrl&quot;: ((10,178,61,41), (font.render(&quot;CTRL&quot;, True, (0,0,0)), font.render(&quot;CTRL&quot;, True, (255,255,255))), (20,190)), &quot;enter&quot;: ((134,178,81,41), (font.render(&quot;ENTER&quot;, True, (0,0,0)), font.render(&quot;ENTER&quot;, True, (255,255,255))), (148,190)), &quot;down&quot;: ((216,178,41,41), (down_font.render(&quot;down&quot;, True, (0,0,0)), down_font.render(&quot;down&quot;, True, (255,255,255))), (217,190)) } held_or_released = dict() for v in shown_keys.values(): pygame.draw.rect(win, (0,0,0), v[0]) win.blit(v[1][1], v[2]) scroll_up_text = (font.render(&quot;SU&quot;, True, (0,0,0)), font.render(&quot;SU&quot;, True, (255,255,255))) scroll_down_text = (font.render(&quot;SD&quot;, True, (0,0,0)), font.render(&quot;SD&quot;, True, (255,255,255))) scroll_time_remaining = [None, 0, 0] # [None, up, down] def on_scroll( x, y, dx, dy, lock_for_scroll_=lock_for_scroll, scroll_time_remaining_=scroll_time_remaining ): # dy is 1 when scrolling up and -1 when scrolling down with lock_for_scroll_: scroll_time_remaining_[dy] = 42 # midpoint between 2 frames and 3 frames at 60 FPS def on_click( x, y, button, pressed, lock_for_dict_=lock_for_dict, held_or_released_=held_or_released ): with lock_for_dict_: held_or_released_[button.name == &quot;right&quot;] = pressed def on_press( key, lock_for_dict_=lock_for_dict, held_or_released_=held_or_released, shown_keys_=shown_keys, hasattr_=hasattr, str_lower=str.lower ): # this gets called repeatedly if the key is held down if hasattr_(key, &quot;char&quot;) and (k := key.char) is not None: k = str_lower(k) if k not in held_or_released_ and k in shown_keys_: with lock_for_dict_: held_or_released_[k] = True elif hasattr_(key, &quot;name&quot;) and (k := key.name) is not None: if k not in held_or_released_ and k in shown_keys_: with lock_for_dict_: held_or_released_[k] = True else: with lock_for_dict_: held_or_released_[(&quot;tab&quot;, &quot;alt&quot;)[key.vk % 2]] = True def on_release( key, lock_for_dict_=lock_for_dict, held_or_released_=held_or_released, shown_keys_=shown_keys, hasattr_=hasattr, str_lower=str.lower ): if hasattr_(key, &quot;char&quot;) and (k := key.char) is not None: k = str_lower(k) if k in shown_keys_: with lock_for_dict_: held_or_released_[k] = False elif hasattr_(key, &quot;name&quot;) and (k := key.name) is not None: if k in shown_keys_: with lock_for_dict_: held_or_released_[k] = False else: with lock_for_dict_: held_or_released_[(&quot;tab&quot;, &quot;alt&quot;)[key.vk % 2]] = False key_listener = pynput.keyboard.Listener(on_press=on_press, on_release=on_release) mouse_listener = pynput.mouse.Listener(on_scroll=on_scroll, on_click=on_click) key_listener.daemon = True mouse_listener.daemon = True key_listener.start() mouse_listener.start() pygame_time_wait = pygame.time.wait pygame_display_update = pygame.display.update pygame_draw_rect = pygame.draw.rect win_blit = win.blit held_or_released_items = held_or_released.items held_or_released_clear = held_or_released.clear pygame_QUIT = pygame.QUIT pygame_event_get = pygame.event.get any_ = any while not any_(event.type == pygame_QUIT for event in pygame_event_get()): waited_time = pygame_time_wait(1) pygame_display_update() with lock_for_scroll: if scroll_time_remaining[1] &gt;= 0: scroll_time_remaining[1] -= waited_time pygame_draw_rect(win, ((0,0,0), (255,255,255))[scroll_time_remaining[1] &gt;= 0], (271,52,41,41)) win_blit(scroll_up_text[scroll_time_remaining[1] &lt; 0], (281, 64)) if scroll_time_remaining[2] &gt;= 0: scroll_time_remaining[2] -= waited_time pygame_draw_rect(win, ((0,0,0), (255,255,255))[scroll_time_remaining[2] &gt;= 0], (271,136,41,41)) win_blit(scroll_down_text[scroll_time_remaining[2] &lt; 0], (281, 148)) with lock_for_dict: for k, v in held_or_released_items(): args = shown_keys[k] pygame_draw_rect(win, ((0,0,0), (255,255,255))[v], args[0]) win_blit(args[1][not v], args[2]) held_or_released_clear() pygame.quit() main() </code></pre>
[]
[ { "body": "<blockquote>\n<p>Linux which doesn't have any good input display programs</p>\n</blockquote>\n<p>I deeply doubt this, but moving on:</p>\n<ul>\n<li>You have a one-outer-function program that leans heavily on closures. This is not a good way to represent state, and is untestable. There are better ways to pass around state. In my recommendation I show two based on context: either bind to some separated functions with <code>partial</code>, or use a class.</li>\n<li>Add some PEP484 type hints.</li>\n<li>Don't use anonymous tuples; use named tuples, dataclasses or normal classes for your shown keys.</li>\n<li>Remove the redundancy from <code>shown_keys</code> - you rewrite the constants for black and white several times, as well as your antialias setting, etc.</li>\n<li>Perhaps do not represent <code>held_or_released</code> as a dictionary of booleans, but instead as a set. Membership in the set indicates held.</li>\n<li>Centralize the repeated code chunk to draw a character.</li>\n<li>Your <code>scroll_time_remaining</code> indexing strategy is downright nasty. A list of two elements with re-mapped indices, or perhaps a dictionary, will be less hacky. Among other side-effects of your current design decision, the fact that you have a <code>None</code> in the mix means you require <code>Optional</code> where you shouldn't.</li>\n<li>Why are you aliasing a bunch of built-ins (<code>hasattr</code>, <code>lower</code>, <code>any</code>)? Don't do this. <code>pygame_time_wait = pygame.time.wait</code> is equally unhelpful.</li>\n<li>Don't <code>held_or_released_clear()</code> at all. This looks to be a hack to work around the fact that you're ignoring the <code>pressed</code> parameter to <code>on_click</code>.</li>\n<li><code>held_or_released_[(&quot;tab&quot;, &quot;alt&quot;)[key.vk % 2]]</code> is nasty and probably several kinds of fragile. If you know the virtual codes for tab and alt, just use the codes directly. In my sample code I've skipped over this and the only combination I've found not to work is shift+tab.</li>\n<li>Instead of <code>hasattr</code>, you can check for the actual instance type using <code>isinstance</code>, and reflect this decision in a <code>Union</code> parameter.</li>\n<li>You don't have any animation, so you should altogether discard the idea of FPS and <code>event.get</code>, replacing it with <code>event.wait</code>. For your scrolling timeout logic you can use a timer instead of a polling loop. I have not dug into this in my sample code.</li>\n<li>Add a <code>__main__</code> guard.</li>\n</ul>\n<h2 id=\"suggested\">Suggested</h2>\n<pre><code>from functools import partial\nfrom typing import Optional, List, Union, Tuple, Dict, Set, Callable\n\nimport pygame\nimport pynput\nimport threading\n\nfrom pygame.font import Font\nfrom pynput.keyboard import Key, KeyCode\nfrom pynput.mouse import Button\n\nBLACK = 0, 0, 0\nWHITE = 255, 255, 255\nANTIALIAS = True\n\n\nKeyType = Union[str, bool]\n\n\nclass ShownKey:\n def __init__(\n self,\n key: KeyType,\n name: str,\n font: Font,\n rect: Tuple[int, int, int, int],\n text_pos: Tuple[int, int],\n ):\n self.key, self.name, self.rect, self.text_pos = key, name, rect, text_pos\n self.black_text: pygame.Surface = font.render(name, ANTIALIAS, BLACK)\n self.white_text: pygame.Surface = font.render(name, ANTIALIAS, WHITE)\n\n def draw(self, win: pygame.Surface, held: bool) -&gt; None:\n if held:\n background = WHITE\n text = self.black_text\n else:\n background = BLACK\n text = self.white_text\n pygame.draw.rect(win, background, self.rect)\n win.blit(text, self.text_pos)\n\n\nShownKeyDict = Dict[KeyType, ShownKey]\nHeldSet = Set[KeyType]\n\n\ndef on_scroll(\n x: int, y: int, dx: int, dy: int,\n lock_for_scroll: threading.Lock,\n scroll_time_remaining: List[Optional[int]],\n) -&gt; None:\n # dy is 1 when scrolling up and -1 when scrolling down\n with lock_for_scroll:\n scroll_time_remaining[dy] = 42 # midpoint between 2 frames and 3 frames at 60 FPS\n\n\ndef on_click(\n x: int, y: int, button: Button, pressed: bool,\n lock_for_dict: threading.Lock,\n held_or_released: HeldSet,\n) -&gt; None:\n with lock_for_dict:\n val = button.name == &quot;right&quot;\n if pressed:\n held_or_released.add(val)\n else:\n held_or_released.discard(val)\n\n\ndef on_press_or_release(\n key: Union[Key, KeyCode],\n lock_for_dict: threading.Lock,\n is_shown: Callable[[KeyType], bool],\n update_held: Callable[[KeyType], None],\n) -&gt; None:\n # this gets called repeatedly if the key is held down\n if isinstance(key, KeyCode):\n if key.char is None:\n # Deal with virtual keys here\n return\n k = key.char.lower()\n elif isinstance(key, Key):\n k = key.name\n else:\n raise NotImplementedError()\n\n if is_shown(k):\n with lock_for_dict:\n update_held(k)\n\n\ndef main():\n lock_for_dict = threading.Lock()\n lock_for_scroll = threading.Lock()\n\n pygame.init()\n\n win = pygame.display.set_mode((343, 229))\n pygame.display.set_caption(&quot;test&quot;)\n font = pygame.font.Font(pygame.font.get_default_font(), 15)\n down_font = pygame.font.Font(pygame.font.get_default_font(), 14)\n\n # {key_or_mouse_button: (rect_location_and_size, (black_key_text, white_key_text), key_text_location)}\n # 0 and 1 are left mouse and right mouse\n LEFT_MOUSE = False\n RIGHT_MOUSE = True\n\n shown_keys: ShownKeyDict = {\n key: ShownKey(key, name, font, rect, text_pos)\n for key, rect, name, text_pos in (\n (LEFT_MOUSE, (250, 94, 41, 41), &quot;LM&quot;, (260, 106)),\n (RIGHT_MOUSE, (292, 94, 41, 41), &quot;RM&quot;, (300, 106)),\n (&quot;a&quot;, (72, 94, 41, 41), &quot;A&quot;, (87, 106)),\n (&quot;w&quot;, (114, 52, 41, 41), &quot;W&quot;, (127, 64)),\n (&quot;s&quot;, (114, 94, 41, 41), &quot;S&quot;, (129, 106)),\n (&quot;d&quot;, (156, 94, 41, 41), &quot;D&quot;, (171, 106)),\n (&quot;q&quot;, (72, 52, 41, 41), &quot;Q&quot;, (87, 64)),\n (&quot;e&quot;, (156, 52, 41, 41), &quot;E&quot;, (171, 64)),\n (&quot;r&quot;, (198, 52, 41, 41), &quot;R&quot;, (213, 64)),\n (&quot;f4&quot;, (198, 10, 41, 41), &quot;F4&quot;, (210, 22)),\n (&quot;tab&quot;, (10, 52, 61, 41), &quot;TAB&quot;, (25, 64)),\n (&quot;alt&quot;, (72, 178, 61, 41), &quot;ALT&quot;, (87, 190)),\n (&quot;shift&quot;, (10, 136, 81, 41), &quot;SHIFT&quot;, (28, 148)),\n (&quot;ctrl&quot;, (10, 178, 61, 41), &quot;CTRL&quot;, (20, 190)),\n (&quot;enter&quot;, (134, 178, 81, 41), &quot;ENTER&quot;, (148, 190)),\n )\n }\n shown_keys['down'] = ShownKey('down', 'down', down_font, (216, 178, 41, 41), (217, 190))\n all_keys = set(shown_keys.keys())\n held_or_released: HeldSet = set()\n\n for key in shown_keys.values():\n key.draw(win, held=False)\n\n scroll_up_text = (font.render(&quot;SU&quot;, ANTIALIAS, BLACK), font.render(&quot;SU&quot;, ANTIALIAS, WHITE))\n scroll_down_text = (font.render(&quot;SD&quot;, ANTIALIAS, BLACK), font.render(&quot;SD&quot;, ANTIALIAS, WHITE))\n scroll_time_remaining = [None, 0, 0] # [None, up, down]\n\n key_listener = pynput.keyboard.Listener(\n on_press=partial(\n on_press_or_release, lock_for_dict=lock_for_dict,\n is_shown=shown_keys.__contains__, update_held=held_or_released.add,\n ),\n on_release=partial(\n on_press_or_release, lock_for_dict=lock_for_dict,\n is_shown=shown_keys.__contains__, update_held=held_or_released.discard,\n ),\n )\n mouse_listener = pynput.mouse.Listener(\n on_scroll=partial(on_scroll, lock_for_scroll=lock_for_scroll, scroll_time_remaining=scroll_time_remaining),\n on_click=partial(on_click, lock_for_dict=lock_for_dict, held_or_released=held_or_released),\n )\n key_listener.daemon = True\n mouse_listener.daemon = True\n key_listener.start()\n mouse_listener.start()\n\n while not any(event.type == pygame.QUIT for event in pygame.event.get()):\n\n waited_time = pygame.time.wait(1)\n\n pygame.display.update()\n\n with lock_for_scroll:\n if scroll_time_remaining[1] &gt;= 0:\n scroll_time_remaining[1] -= waited_time\n pygame.draw.rect(win, (BLACK, WHITE)[scroll_time_remaining[1] &gt;= 0], (271, 52, 41, 41))\n win.blit(scroll_up_text[scroll_time_remaining[1] &lt; 0], (281, 64))\n if scroll_time_remaining[2] &gt;= 0:\n scroll_time_remaining[2] -= waited_time\n pygame.draw.rect(win, (BLACK, WHITE)[scroll_time_remaining[2] &gt;= 0], (271, 136, 41, 41))\n win.blit(scroll_down_text[scroll_time_remaining[2] &lt; 0], (281, 148))\n\n with lock_for_dict:\n for key in held_or_released:\n shown_keys[key].draw(win, held=True)\n for key in all_keys - held_or_released:\n shown_keys[key].draw(win, held=False)\n # held_or_released.clear()\n\n pygame.quit()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-18T21:02:02.363", "Id": "264164", "ParentId": "264081", "Score": "2" } } ]
{ "AcceptedAnswerId": "264164", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T02:56:15.367", "Id": "264081", "Score": "3", "Tags": [ "python", "python-3.x", "pygame" ], "Title": "Pygame program made to look like NohBoard" }
264081
<p>Imagine we have a function that returns a Promise, ie call a GET endpoint of an api and return the response data.</p> <pre><code>function testFn() { return fetch('http://localhost/ep') } </code></pre> <p>The response will remain valid for some unknown period of time but may need to be refetched later. Basically anytime somebody needs it, it needs to be fresh.</p> <p>Now let's say multiple asynchronous functions need to call this method at some point for different purposeses.</p> <p>If for some reason one function calls this method and lets say is waiting for its completion. And another function calls the method while the first promise not yet resolved I want to avoid calling the function again and instead return a promise to the second caller that will resolve/reject at the same time and with the same data as the first one.</p> <p>To generalize, the input async method may accept arguments and we need to group the calls by those arguments. To do that I use a Map with keys being JSON stringified array of arguments, but I also allow to override this strategy using the <code>options.keyFn</code></p> <p>In the following code the <code>bottleneck</code> function accepts the input async method and returns the wrapped method with the same signature.</p> <pre><code>export type BottleneckOptions&lt;P extends unknown[]&gt; = { keyFn?: (...args: P) =&gt; string } export function bottleneck&lt;T, P extends unknown[]&gt;( neck: (...args: P) =&gt; Promise&lt;T&gt;, options: BottleneckOptions&lt;P&gt; = {}, ): (...args: P) =&gt; Promise&lt;T&gt; { type QueueItem = { resolve: (value: T) =&gt; void reject: (error: any) =&gt; void } const bottles: Map&lt;string, QueueItem[]&gt; = new Map() return (...args: P) =&gt; { const resolveAll = (result: T) =&gt; { for (const item of bottle) { item.resolve(result) } clear() } const rejectAll = (error: any) =&gt; { for (const item of bottle) { item.reject(error) } clear() } const clear = () =&gt; { bottle.length = 0 bottles.delete(key) } const key = options.keyFn ? options.keyFn(...args) : JSON.stringify(args) const bottle: QueueItem[] = bottles.get(key) || [] bottles.set(key, bottle) const result = new Promise&lt;T&gt;((resolve, reject) =&gt; { bottle.push({ resolve, reject }) }) if (bottle.length === 1) { neck(...args).then(resolveAll).catch(rejectAll) } return result } } </code></pre> <p>Now an example where we just wrap the standard fetch function.</p> <pre><code>const neck = bottleneck(fetch) const result = await Promise.all([ neck(url1), neck(url1), neck(url1), neck(url2), neck(url2), ]) console.log(result) // fetch only called twice (most likely) but all results for url1 (resp. url2) are same </code></pre> <p>The <code>keyFn</code> of the options allows to change the grouping for example stacking all calls ignoring the first argument and using only the second.</p> <pre><code>const testFn: &lt;A, T&gt;(a: A, b: string) =&gt; Promise&lt;T&gt; = ... const wrappedFn = bottleneck(testFn, { keyFn: (a, b) =&gt; b } </code></pre> <p>Or to ignore all arguments entirely:</p> <pre><code>const wrappedFn = bottleneck(testFn, { keyFn: () =&gt; '' } </code></pre> <p>Lastly, let me provide a real use case</p> <p>There is an api that is authenticated with bearer token.</p> <p>Whenever the token expires the api responds with 401 and the client is supposed to request a new token via refresh token endpoint and then retry the original request with the new bearer token.</p> <p>Multiple client app components may call different endpoints of the api in parallel. This means that if they are all invoked with an expired token they will all receive 401 and attempt to refresh the token, invoking multiple calls to the refresh token endpoint.</p> <p>The <code>bottleneck</code> function would be used to wrap the refresh token function causing all parallel requests that fail with 401 to wait for the same refreshed token from the first invoker until they retry their request.</p>
[]
[ { "body": "<p>You don't need to create a new promise for each call. A promise can be reused multiple times, so all you have to do is cache the promise. Something like this:</p>\n<pre><code>if (bottles.has(key)) {\n return bottles.get(key)\n}\n\nconst p = neck(...args).finally(() =&gt; {\n bottles.delete(key)\n})\n\nbottles.set(key, p)\n\nreturn p\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T11:16:37.950", "Id": "521523", "Score": "0", "body": "That's excellent. KISS!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T10:34:04.120", "Id": "264090", "ParentId": "264083", "Score": "3" } } ]
{ "AcceptedAnswerId": "264090", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T06:33:30.857", "Id": "264083", "Score": "3", "Tags": [ "typescript", "promise" ], "Title": "Wrap async method in a way that the method is invoked only once for all calls that occur while the first of them is not resolved" }
264083
<p>I used uniform crossover to solve eight queens problem. It is taking more than an hour to get the result. Is there any way to reduce the running time or improve the crossover to solve eight queens problem? Following is the code:</p> <pre><code>import random import numpy as np from math import gamma as G def random_chromosome(size): #making random chromosomes return [ random.randint(1, nq) for _ in range(nq) ] def fitness(chromosome): horizontal_collisions = sum([chromosome.count(queen)-1 for queen in chromosome])/2 diagonal_collisions = 0 n = len(chromosome) left_diagonal = [0] * 2*n right_diagonal = [0] * 2*n for i in range(n): left_diagonal[i + chromosome[i] - 1] += 1 right_diagonal[len(chromosome) - i + chromosome[i] - 2] += 1 diagonal_collisions = 0 for i in range(2*n-1): counter = 0 if left_diagonal[i] &gt; 1: counter += left_diagonal[i]-1 if right_diagonal[i] &gt; 1: counter += right_diagonal[i]-1 diagonal_collisions += counter / (n-abs(i-n+1)) return int(maxFitness - (horizontal_collisions + diagonal_collisions)) #28-(2+3)=23 def probability(chromosome, fitness): return fitness(chromosome) / maxFitness def random_pick(population, probabilities): populationWithProbabilty = zip(population, probabilities) total = sum(w for c, w in populationWithProbabilty) r = random.uniform(0, total) upto = 0 for c, w in zip(population, probabilities): if upto + w &gt;= r: return c upto += w assert False, &quot;Shouldn't get here&quot; #Uniform crossover def reproduce(x, y): #doing cross_over between two chromosomes n = len(x) c = random.randint(0, n - 1) x = c*x+(1-c)*y; y = c*y+(1-c)*x; return x[0:c] + y[c:n] def mutate(x): #randomly changing the value of a random index of a chromosome n = len(x) c = random.randint(1,n-1) m = random.randint(1, n) x[c] = m #x = x+[c]; #y = y+[c]; return x def genetic_queen(population, fitness): mutation_probability = 0.03 #eta_m=20 new_population = [] probabilities = [probability(n, fitness) for n in population] for i in range(len(population)): x = random_pick(population, probabilities) #best chromosome 1 y = random_pick(population, probabilities) #best chromosome 2 child = reproduce(x, y) #creating two new chromosomes from the best 2 chromosomes if random.random() &lt; mutation_probability: child = mutate(child) print_chromosome(child) new_population.append(child) if fitness(child) == maxFitness: break return new_population def print_chromosome(chrom): print(&quot;Chromosome = {}, Fitness = {}&quot; .format(str(chrom), fitness(chrom))) if __name__ == &quot;__main__&quot;: nq = int(input(&quot;Enter Number of Queens: &quot;)) #say N = 8 maxFitness = (nq*(nq-1))/2 # 8*7/2 = 28 population = [random_chromosome(nq) for _ in range(50)] generation = 1 while not maxFitness in [fitness(chrom) for chrom in population]: print(&quot;=== Generation {} ===&quot;.format(generation)) population = genetic_queen(population, fitness) print(&quot;&quot;) print(&quot;Maximum Fitness = {}&quot;.format(max([fitness(n) for n in population]))) generation += 1 chrom_out = [] print(&quot;Solved in Generation {}!&quot;.format(generation-1)) for chrom in population: if fitness(chrom) == maxFitness: print(&quot;&quot;); print(&quot;One of the solutions: &quot;) chrom_out = chrom print_chromosome(chrom) board = [] for x in range(nq): board.append([&quot;x&quot;] * nq) for i in range(nq): board[nq-chrom_out[i]][i]=&quot;Q&quot; def print_board(board): for row in board: print (&quot; &quot;.join(row)) print() print_board(board) </code></pre> <p>where x and y are offspring.</p> <p>I am not sure uniform crossover is more suitable for eight queens problem. At last I am getting the following output,</p> <p>Maximum Fitness = 28 Solved in Generation 2972!</p> <p>One of the solutions: Chromosome = [6, 4, 7, 1, 3, 5, 2, 8], Fitness = 28</p> <pre><code>x x x x x x x Q x x Q x x x x x Q x x x x x x x x x x x x Q x x x Q x x x x x x x x x x Q x x x x x x x x x Q x x x x Q x x x x </code></pre> <p>Any answer regarding this will be appreciated.</p>
[]
[ { "body": "<p>The number of potential crossovers is much larger (read: exponentially) than the number of solutions since the next crossover can easily end up in the same row, column or (not covered by your code:) diagonal occupied by an earlier queen.\nKeeping track of the state (previous generations) to quickly prune branches that are doomed to fail would certainly help, but in the end you'd just be implementing an &quot;ordinary&quot; algorithm.\nSo I'm inclined to answer as follows: don't use crossover.</p>\n<p>PS: just to make sure I'm not misunderstood: the key problem of using crossover here is that next generations/sub-solutions don't nicely converge towards an optimum.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-23T07:05:42.720", "Id": "521985", "Score": "0", "body": "What your are saying is correct. Here I am using Evolutionary Algorithms to implement eight queens problems, so need to use crossover or mutation to create offspring. I am wondering is there any crossover or mutation would reduce running time of my code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-23T08:18:59.583", "Id": "521989", "Score": "0", "body": "I understand that, but I don't believe it exists. The whole foundation of this approach is essentially that the probability of stumbling upon a solution is an increasing function of the number of generations, and for this particular problem I can't imagine such a function exists. I admit there's a big chunk of intuition behind my reasoning and I'm no expert, so keep looking." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-23T08:23:02.713", "Id": "521991", "Score": "0", "body": "PS: I'm not the author of the imperative solution that was posted. If I had thought you'd be interested in such a version I would simply have posted a link to some (more solid-looking) implementation." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T10:41:54.957", "Id": "264091", "ParentId": "264085", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T07:11:39.070", "Id": "264085", "Score": "1", "Tags": [ "python", "performance", "genetic-algorithm" ], "Title": "Crossover in eight queens" }
264085
<p>I'm trying to scrape arrival data from <a href="https://www.flightradar24.com" rel="nofollow noreferrer">Flight Radar 24</a></p> <p>My script takes extremely long time to scrape the data. Is there any way I can speed up the scraping process?</p> <p>Here's my script:</p> <pre><code>import time from selenium import webdriver from bs4 import BeautifulSoup from urllib.parse import urljoin from selenium.webdriver.chrome.options import Options import pandas as pd import requests def getArrivals(): urls = { 'Alor Island Airport': 'https://www.flightradar24.com/data/airports/ard/arrivals', 'Ambon Pattimura Airport': 'https://www.flightradar24.com/data/airports/amq/arrivals', 'Atambua Haliwen Airport': 'https://www.flightradar24.com/data/airports/abu/arrivals', 'Babo Airport': 'https://www.flightradar24.com/data/airports/bxb/arrivals', 'Bajawa Turelelo Soa Airport': 'https://www.flightradar24.com/data/airports/bjw/arrivals', 'Balikpapan Sepinggan Airport': 'https://www.flightradar24.com/data/airports/bpn/arrivals', 'Banda Aceh International Airport': 'https://www.flightradar24.com/data/airports/btj/arrivals', 'Bandar Lampung Radin Inten II Airport': 'https://www.flightradar24.com/data/airports/tkg/arrivals', 'Bandung Husein Sastranegara International Airport': 'https://www.flightradar24.com/data/airports/bdo/arrivals', 'Banjarmasin Syamsudin Noor Airport': 'https://www.flightradar24.com/data/airports/bdj/arrivals', 'Batam Hang Nadim Airport': 'https://www.flightradar24.com/data/airports/bth/arrivals', 'Batu Licin Airport': 'https://www.flightradar24.com/data/airports/btw/arrivals', 'Bau-Bau Betoambari Airport': 'https://www.flightradar24.com/data/airports/buw/arrivals', 'Bengkulu Fatmawati Soekarno Airport': 'https://www.flightradar24.com/data/airports/bks/arrivals', 'Biak Frans Kaisiepo Airport': 'https://www.flightradar24.com/data/airports/bik/arrivals', 'Bima Sultan Muhammad Salahudin Airport': 'https://www.flightradar24.com/data/airports/bmu/arrivals', 'Blimbingsari Airport': 'https://www.flightradar24.com/data/airports/bwx/arrivals', 'Buol Airport': 'https://www.flightradar24.com/data/airports/uol/arrivals', 'Dekai Nop Goliat Airport': 'https://www.flightradar24.com/data/airports/dex/arrivals', 'Denpasar Ngurah Rai International Airport': 'https://www.flightradar24.com/data/airports/dps/arrivals', 'Dumai Pinang Kampai Airport': 'https://www.flightradar24.com/data/airports/dum/arrivals', 'Ende H. Hasan Aroeboesman Airport': 'https://www.flightradar24.com/data/airports/ene/arrivals', 'Fakfak Torea Airport': 'https://www.flightradar24.com/data/airports/fkq/arrivals', 'Gorontalo Jalaluddin Airport': 'https://www.flightradar24.com/data/airports/gto/arrivals', 'Gunung Sitoli Binaka Airport': 'https://www.flightradar24.com/data/airports/gns/arrivals', 'Jakarta Halim Perdanakusuma Airport': 'https://www.flightradar24.com/data/airports/hlp/arrivals', 'Jakarta Soekarno Hatta International Airport': 'https://www.flightradar24.com/data/airports/cgk/arrivals', 'Jambi Sultan Thaha Airport': 'https://www.flightradar24.com/data/airports/djb/arrivals', 'Jayapura Sentani Airport': 'https://www.flightradar24.com/data/airports/djj/arrivals', 'Jember Notohadinegoro Airport': 'https://www.flightradar24.com/data/airports/jbb/arrivals', 'Kaimana Utarom Airport': 'https://www.flightradar24.com/data/airports/kng/arrivals', 'Kalimarau Airport': 'https://www.flightradar24.com/data/airports/bej/arrivals', 'Kebar Airport': 'https://www.flightradar24.com/data/airports/keq/arrivals', 'Kendari Haluoleo Airport': 'https://www.flightradar24.com/data/airports/kdi/arrivals', 'Ketapang Airport': 'https://www.flightradar24.com/data/airports/ktg/arrivals', 'Kotabaru Gusti Syamsir Alam Airport': 'https://www.flightradar24.com/data/airports/kbu/arrivals', 'Kupang El Tari Airport': 'https://www.flightradar24.com/data/airports/koe/arrivals', 'Labuan Bajo Komodo Airport': 'https://www.flightradar24.com/data/airports/lbj/arrivals', 'Labuha Oesman Sadik Airport': 'https://www.flightradar24.com/data/airports/lah/arrivals', 'Langgur Karel Sadsuitubun Airport': 'https://www.flightradar24.com/data/airports/luv/arrivals', 'Larantuka Gewayantana Airport': 'https://www.flightradar24.com/data/airports/lka/arrivals', 'Lewoleba Wunopito Airport': 'https://www.flightradar24.com/data/airports/lwe/arrivals', 'Lhokseumawe Malikus Saleh Airport': 'https://www.flightradar24.com/data/airports/lsw/arrivals', 'Lombok International Airport': 'https://www.flightradar24.com/data/airports/lop/arrivals', 'Lubuklinggau Silampari Airport': 'https://www.flightradar24.com/data/airports/llj/arrivals', 'Luwuk Bubung Airport': 'https://www.flightradar24.com/data/airports/luw/arrivals', 'Majalengka Kertajati International Airport': 'https://www.flightradar24.com/data/airports/kjt/arrivals', 'Makassar Sultan Hasanuddin International Airport': 'https://www.flightradar24.com/data/airports/upg/arrivals', 'Malang Abdul Rachman Saleh Airport': 'https://www.flightradar24.com/data/airports/mlg/arrivals', 'Malinau Kolonel RA Bessing Airport': 'https://www.flightradar24.com/data/airports/lnu/arrivals', 'Mamuju Tampa Padang Airport': 'https://www.flightradar24.com/data/airports/mju/arrivals', 'Manado Sam Ratulangi International Airport': 'https://www.flightradar24.com/data/airports/mdc/arrivals', 'Manokwari Rendani Airport': 'https://www.flightradar24.com/data/airports/mkw/arrivals', 'Matak Tarempa Airport': 'https://www.flightradar24.com/data/airports/mwk/arrivals', 'Maumere Frans Seda Airport': 'https://www.flightradar24.com/data/airports/mof/arrivals', 'Medan Kuala Namu International Airport': 'https://www.flightradar24.com/data/airports/kno/arrivals', 'Melangguane Airport': 'https://www.flightradar24.com/data/airports/mna/arrivals', 'Merauke Mopah International Airport': 'https://www.flightradar24.com/data/airports/mkq/arrivals', 'Muara Bungo Airport': 'https://www.flightradar24.com/data/airports/buu/arrivals', 'Nabire Airport': 'https://www.flightradar24.com/data/airports/nbx/arrivals', 'Nanga Pinoh Airport': 'https://www.flightradar24.com/data/airports/npo/arrivals', 'Nunukan Airport': 'https://www.flightradar24.com/data/airports/nnx/arrivals', 'Oksibil Airport': 'https://www.flightradar24.com/data/airports/okl/arrivals', 'Padang Minangkabau International Airport': 'https://www.flightradar24.com/data/airports/pdg/arrivals', 'Palangkaraya Tjilik Riwut Airport': 'https://www.flightradar24.com/data/airports/pky/arrivals', 'Palembang International Airport': 'https://www.flightradar24.com/data/airports/plm/arrivals', 'Palopo Lagaligo Airport': 'https://www.flightradar24.com/data/airports/llo/arrivals', 'Palu Mutiara Airport': 'https://www.flightradar24.com/data/airports/plw/arrivals', 'Pangkal Pinang Airport': 'https://www.flightradar24.com/data/airports/pgk/arrivals', 'Pangkalan Bun Iskandar Airport': 'https://www.flightradar24.com/data/airports/pkn/arrivals', 'Pekanbaru Sultan Syarif Kasim II Airport': 'https://www.flightradar24.com/data/airports/pku/arrivals', 'Pomala Airport': 'https://www.flightradar24.com/data/airports/pum/arrivals', 'Pontianak Supadio Airport': 'https://www.flightradar24.com/data/airports/pnk/arrivals', 'Putussibau Pangsuma Airport': 'https://www.flightradar24.com/data/airports/psu/arrivals', 'Raha Sugimanuru Airport': 'https://www.flightradar24.com/data/airports/raq/arrivals', 'Ranai Airport': 'https://www.flightradar24.com/data/airports/ntx/arrivals', 'Rengat Japura Airport': 'https://www.flightradar24.com/data/airports/rgt/arrivals', 'Roti David C. Saudale Airport': 'https://www.flightradar24.com/data/airports/rti/arrivals', 'Ruteng Frans Sales Lega Airport': 'https://www.flightradar24.com/data/airports/rtg/arrivals', 'Sabang Maimun Saleh Airport': 'https://www.flightradar24.com/data/airports/sbg/arrivals', 'Samarinda AP Tumenggung Pranoto Airport': 'https://www.flightradar24.com/data/airports/aap/arrivals', 'Sampit Airport': 'https://www.flightradar24.com/data/airports/smq/arrivals', 'Saumlaki Mathilda Batlayeri Airport': 'https://www.flightradar24.com/data/airports/sxk/arrivals', 'Selayar Islands H. Aroeppala Airport': 'https://www.flightradar24.com/data/airports/ksr/arrivals', 'Semarang Achmad Yani International Airport': 'https://www.flightradar24.com/data/airports/srg/arrivals', 'Sibolga Ferdinand Lumban Tobing Airport': 'https://www.flightradar24.com/data/airports/flz/arrivals', 'Siborong-Borong Silangit Airport': 'https://www.flightradar24.com/data/airports/dtb/arrivals', 'Sintang Airport': 'https://www.flightradar24.com/data/airports/sqg/arrivals', 'Sorong Dominique Edward Osok Airport': 'https://www.flightradar24.com/data/airports/soq/arrivals', 'Sumbawa Besar Airport': 'https://www.flightradar24.com/data/airports/swq/arrivals', 'Sumenep Trunojoyo Airport': 'https://www.flightradar24.com/data/airports/sup/arrivals', 'Surabaya Juanda International Airport': 'https://www.flightradar24.com/data/airports/sub/arrivals', 'Surakarta Adisumarmo International Airport': 'https://www.flightradar24.com/data/airports/soc/arrivals', 'Tahuna Naha Airport': 'https://www.flightradar24.com/data/airports/nah/arrivals', 'Tambolaka Airport': 'https://www.flightradar24.com/data/airports/tmc/arrivals', 'Tana Toraja Pongtiku Airport': 'https://www.flightradar24.com/data/airports/ttr/arrivals', 'Tanahmerah Airport': 'https://www.flightradar24.com/data/airports/tmh/arrivals', 'Tanjung Pandan Buluh Tumbang Airport': 'https://www.flightradar24.com/data/airports/tjq/arrivals', 'Tanjung Pinang Raja Haji Fisabilillah Airport': 'https://www.flightradar24.com/data/airports/tnj/arrivals', 'Tanjung Selor Tanjung Harapan Airport': 'https://www.flightradar24.com/data/airports/tjs/arrivals', 'Tarakan Juwata International Airport': 'https://www.flightradar24.com/data/airports/trk/arrivals', 'Tasikmalaya Cibeureum Airport': 'https://www.flightradar24.com/data/airports/tsy/arrivals', 'Ternate Babullah Airport': 'https://www.flightradar24.com/data/airports/tte/arrivals', 'Timika Airport': 'https://www.flightradar24.com/data/airports/tim/arrivals', 'Waingapu Mau Hau Airport': 'https://www.flightradar24.com/data/airports/wgp/arrivals', 'Wamena Airport': 'https://www.flightradar24.com/data/airports/wmx/arrivals', 'Yogyakarta Adisucipto International Airport': 'https://www.flightradar24.com/data/airports/jog/arrivals', 'Yogyakarta International Airport': 'https://www.flightradar24.com/data/airports/yia/arrivals' } options = Options() options.add_argument(&quot;--window-size=1920,1080&quot;) driver = webdriver.Chrome(options=options) driver = webdriver.Chrome() airport_name = [] times = [] dates = [] flight=[] flightfrom = [] airlines = [] aircrafts = [] flight_status = [] abbrs = [] for key, value in urls.items(): driver.get(value) time.sleep(4) scroll_pause_time = 1 # You can set your own pause time. My laptop is a bit slow so I use 1 sec screen_height = driver.execute_script(&quot;return window.screen.height;&quot;) # get the screen height of the web i = 1 while True: # scroll one screen height each time driver.execute_script(&quot;window.scrollTo(0, {screen_height}*{i});&quot;.format(screen_height=screen_height, i=i)) i += 1 time.sleep(scroll_pause_time) # update scroll height each time after scrolled, as the scroll height can change after we scrolled the page scroll_height = driver.execute_script(&quot;return document.body.scrollHeight;&quot;) # Break the loop when the height we need to scroll to is larger than the total scroll height if (screen_height) * i &gt; scroll_height: break soup = BeautifulSoup(driver.page_source, &quot;html.parser&quot;) #Time time_div=soup.find_all('div',{'class':'col-xs-3 col-sm-3 p-xxs'}) for a in time_div: time_span = a.find_all('span',{'class':'ng-binding'}) for b in time_span: time_text = b.text.strip() times.append(time_text) #Date date_tr=soup.find_all('tr',{'class':'hidden-xs hidden-sm ng-scope'}) for d in date_tr: date = d.get('data-date') dates.append(date) #flight flight_td=soup.find_all('td',{'class':'p-l-s cell-flight-number'}) for a in flight_td: aflight = a.find_all('a',{'class':'notranslate ng-binding'}) for b in aflight: flight_text = b.get('title') flight.append(flight_text) #from asal = [link.get_text().strip() for link in soup.find_all(&quot;span&quot;, {&quot;class&quot;: &quot;hide-mobile-only ng-binding&quot;})] flightfrom.extend(asal) abbreviation=soup.find_all('div',{'ng-show':'(objFlight.flight.airport.origin)'}) for a in abbreviation: abbr_a = a.find_all('a',{'class':'fs-10 fbold notranslate ng-binding'}) for b in abbr_a: abbr_text = b.text.strip() abbrs.append(abbr_text) #airline airline_td=soup.find_all('td',{'class':'cell-airline'}) for a in airline_td: airline_a = a.find_all('a',{'class':'notranslate ng-binding'}) for b in airline_a: airline = b.get('title') airlines.append(airline) #aircraft aircraft_td = soup.find_all('td') for a in aircraft_td: aircraft_span = a.find_all('span',{'class':'notranslate ng-binding'}) for b in aircraft_span: aircraft = b.text.strip() aircrafts.append(aircraft) #flight_status status_td = soup.find_all('td',{'class':'ng-binding'}) for a in status_td: status_span = a.find_all('span',{'class':'ng-binding'}) for b in status_span: status = b.text.strip() flight_status.append(status) airport_tmp = [key] * len(asal) airport_name.extend(airport_tmp) df = pd.DataFrame() df[&quot;Dates&quot;] = dates df[&quot;Time&quot;] = times df[&quot;Flight&quot;] = flight df[&quot;From&quot;] = list(map(' '.join, zip(flightfrom, abbrs))) df[&quot;Airlines&quot;] = airlines df[&quot;Aircrafts&quot;] = aircrafts df[&quot;Status&quot;] = flight_status df[&quot;Airport&quot;] = airport_name return(df) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-18T15:22:26.260", "Id": "521712", "Score": "3", "body": "@PavloSlavynskyy Whether it is or not, is not our concern. If Flight Radar has a problem with this question, they can sent an e-mail to legal@stackoverflow.com." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-18T15:30:24.220", "Id": "521713", "Score": "2", "body": "@lockey If your motivation to delete your code was that you're concerned about legal liability, one option is to request that this question be dissociated from your account. The code will remain up but will be tied to a new, anonymous account instead of yours. However, deleting the question or the code in it is against policy and considered vandalism." } ]
[ { "body": "<p>First: As @PavloSlavynskyy warns, FlightRadar24 has attempted to make it very clear that they do <strong>not</strong> want you to scrape their site or use their API. Among other verbiage, they say:</p>\n<blockquote>\n<p>Copyright (c) 2014-2021 Flightradar24 AB. All rights reserved.</p>\n<p>The contents of this file and all derived data are the property of Flightradar24 AB for use exclusively by its products and applications. Using, modifying or redistributing the data without the prior written permission of Flightradar24 AB is not allowed and may result in prosecutions.</p>\n<p>[...]</p>\n<p>Please note that scraping or any other form of automatic data download is in violation of our Terms of Service (<a href=\"https://www.flightradar24.com/terms-and-conditions\" rel=\"nofollow noreferrer\">https://www.flightradar24.com/terms-and-conditions</a>) and may result in lost access to Flightradar24. Please contact business@fr24.com should you wish to have access to our data services.</p>\n</blockquote>\n<p>Also note that if you attempt to hit their API directly without configuring it correctly, you get an <a href=\"https://en.wikipedia.org/wiki/HTTP_451\" rel=\"nofollow noreferrer\">HTTP 451 Unavailable For Legal Reasons</a>, in case you hadn't gotten the point.</p>\n<p>I am not a legal expert. You have been warned.</p>\n<p>As for an actual review:</p>\n<ul>\n<li>Consider moving your URL list to a separate JSON file</li>\n<li>Your dictionary of URLs should remove the <code> Airport</code> suffix seen on every title, and don't store the URL - only store what changes, which is the airport code</li>\n<li>You've decided to take the worst of all worlds - you have the slowness and inefficiency of Selenium, but you've thrown away the result of its DOM and are parsing its source into BeautifulSoup for some reason. You don't need to do either of these.</li>\n<li>If you do some trivial network analysis of their website and hit the REST API the same way that your browser does, Requests on its own - with no HTML parsing needed, only JSON - works fine. I am not going to spell out how this is done.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T03:25:11.370", "Id": "521724", "Score": "0", "body": "Thank you for the warning, I didn't use this code for business affairs, just for learning about dynamic web. Can I ask about the point two? Why should I remove the ```Airport``` suffix to be ```'Alor Island': 'https://www.flightradar24.com/data/airports/ard/arrivals'```? what is the effect? pls explain thankyou" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T07:09:01.087", "Id": "521728", "Score": "0", "body": "From the point three, did you not recommend Selenium to scrape dynamic website? Do you have any recommendation for that in order to scrape fastly and efficient?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T12:42:24.877", "Id": "521747", "Score": "0", "body": "_Why should I remove the Airport suffix to be 'Alor Island': 'https://www.flightradar24.com/data/airports/ard/arrivals'_ - you shouldn't; it should be `'Alor Island': 'ard'`. This is to remove redundancy from your stored data." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T12:43:25.117", "Id": "521748", "Score": "1", "body": "Correct; Selenium should not be used to scrape here. In general it should be avoided unless strictly necessary, and in the past few years I've only encountered one case of many that needed it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T08:03:34.243", "Id": "521784", "Score": "0", "body": "It actually didn't answered the second point, I used selenium because the code contains javascript" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T13:50:09.183", "Id": "264146", "ParentId": "264088", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T10:13:37.937", "Id": "264088", "Score": "2", "Tags": [ "python", "python-3.x", "web-scraping", "selenium", "webdriver" ], "Title": "Extract flight arrival data from web" }
264088
<p>This code is from my blog project. This project is almost done. This is working well. I can create new posts and update and display all saved posts.</p> <pre><code>const express = require(&quot;express&quot;); const router = express.Router(); const Article = require(&quot;../models/BlogPost.model&quot;); router.get(&quot;/&quot;, (req, res) =&gt; { res.redirect(&quot;/&quot;); }); </code></pre> <p>code for new article</p> <pre><code>router.get(&quot;/new&quot;, (req, res) =&gt; { res.render(&quot;new&quot;, { post: new Article() }); }); router.post(&quot;/new&quot;, (req, res) =&gt; { let post = new Article({ title: req.body.title, author: req.body.author, post: req.body.post, }); post.save((err, data) =&gt; { if (err) { res.render(&quot;posts&quot;, { post: post }); } else { res.render(&quot;mypost&quot;, { result: data }); } }); }); </code></pre> <p>Find a certain id article in database and update that article</p> <pre><code>router.get(&quot;/edit/:id&quot;, async (req, res) =&gt; { await Article.findById(req.params.id, (err, data) =&gt; { if (err) { res.send(&quot;error occured&quot; + err); } else { res.render(&quot;edit&quot;, { post: data }); } }); }); router.post(&quot;/edit/:id&quot;, async (req, res) =&gt; { try { await Article.findOneAndUpdate( { _id: req.params.id }, { title: req.body.title, author: req.body.author, post: req.body.post }, { new: true }) .then((data) =&gt; { res.render(&quot;mypost&quot;, { result: data }); }); } catch (error) { console.log(&quot;Error found &quot; + error); } }); router.get(&quot;/view/:id&quot;, async (req, res) =&gt; { await Article.findById(req.params.id, (err, data) =&gt; { if (err) { res.send(&quot;error occured&quot; + err); } else { res.render(&quot;mypost&quot;, { result: data }); } }); }); module.exports = router; </code></pre> <p>I want my code to reviewed and some tips like how to write better code. Formatted by <a href="https://st.elmah.io" rel="nofollow noreferrer">https://st.elmah.io</a></p>
[]
[ { "body": "<p>Since you want tips on how to write better code, I think what you're doing right now is great! Creating your own blog and asking for feedback is a great way to improve. Keep at it.</p>\n<p>As for the code, I want to hone in on one aspect that can be quite impactful on code quality, and that is error handling. Right now you're making sure to handle errors, which is good, but notice how the error handling is obscuring the rest of the program? Our goal should be to handle errors without letting it take over the entire codebase.</p>\n<p>I would do the following:</p>\n<ul>\n<li>Separate <em>known failures</em> from <em>unknown errors</em>. A known failure can be that the article id doesn't exist. An unknown error can be that the database is unavailable.</li>\n<li>Handle known failures explicitly. E.g. return 404 when a record doesn't exist. Handle unknown errors more generally. The point is that with the former you may have\na reasonable strategy to deal with the failure, and with the latter you just want to not die.</li>\n</ul>\n<p>So for expressjs you can wrap your routes in order to catch thrown errors, convert them to expressjs errors, and add express error middleware to handle the error (<a href=\"https://expressjs.com/en/guide/error-handling.html\" rel=\"nofollow noreferrer\">https://expressjs.com/en/guide/error-handling.html</a>). It would look something like this:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const viewArticleByIdRoute = async (req, res) =&gt; {\n const data = await Article.findById(req.params.id)\n if (data === null) {\n return render404() // Just a dummy, fill in the blanks\n }\n res.render(&quot;mypost&quot;, { result: data })\n}\n\nconst route = fn =&gt; (req, res, next) =&gt; {\n fn(req, res).catch(next)\n}\n\nrouter.get(&quot;/view/:id&quot;, route(viewArticleByIdRoute))\n\nrouter.use((err, req, res, next) =&gt; {\n // render general error page\n})\n</code></pre>\n<p>Notice how the known failure (article doesn't exist) is handled explicitly, while all other errors are just thrown and caught by the general error middleware.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T17:21:20.607", "Id": "521682", "Score": "0", "body": "I was actually unsure for my question being answered, Thanks" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T17:55:08.197", "Id": "264098", "ParentId": "264089", "Score": "2" } }, { "body": "<h2 id=\"usage-of-async-and-await-o3hy\">Usage of <code>async</code> and <code>await</code></h2>\n<p>It appears that <code>async</code> and <code>await</code> are being used but not fully utilized. Typically when using <code>await</code> the return value can be stored in a variable instead of using a callback handler (e.g. in a chained <code>.then()</code>). For instance:</p>\n<blockquote>\n<pre><code>router.post(&quot;/edit/:id&quot;, async (req, res) =&gt; {\n try {\n await Article.findOneAndUpdate(\n { _id: req.params.id },\n { title: req.body.title, author: req.body.author, post: req.body.post },\n { new: true })\n .then((data) =&gt; {\n res.render(&quot;mypost&quot;, { result: data });\n });\n } catch (error) {\n console.log(&quot;Error found &quot; + error);\n }\n });\n</code></pre>\n</blockquote>\n<p>This could be updated like this:</p>\n<pre><code>router.post(&quot;/edit/:id&quot;, async (req, res) =&gt; {\n try {\n const data = await Article.findOneAndUpdate(\n { _id: req.params.id },\n { title: req.body.title, author: req.body.author, post: req.body.post },\n { new: true })\n res.render(&quot;mypost&quot;, { result: data });\n } catch (error) {\n console.log(&quot;Error found &quot; + error);\n }\n});\n</code></pre>\n<p>With this approach there is no need to have the <code>.then()</code> callback. Since I can't see the source of the BlogPost model I may be incorrect about the methods but presumably the calls can be converted as well. For example:</p>\n<blockquote>\n<pre><code>await Article.findById(req.params.id, (err, data) =&gt; {\n if (err) {\n res.send(&quot;error occured&quot; + err);\n } else {\n res.render(&quot;mypost&quot;, { result: data });\n }\n});\n</code></pre>\n</blockquote>\n<p>Can be instead:</p>\n<pre><code>const data = await Article.findById(req.params.id).catch(err =&gt; {\n res.send(&quot;error occured&quot; + err);\n});\nres.render(&quot;mypost&quot;, { result: data });\n</code></pre>\n<p>This is much more succinct.</p>\n<h2 id=\"indentation-isq7\">Indentation</h2>\n<p>While it could be due to copy and paste issues, the indentation is not always consistent. For example:</p>\n<blockquote>\n<pre><code>router.post(&quot;/new&quot;, (req, res) =&gt; {\n let post = new Article({\n title: req.body.title,\n author: req.body.author,\n post: req.body.post,\n});\npost.save((err, data) =&gt; {\n if (err) {\n res.render(&quot;posts&quot;, { post: post });\n } else {\n res.render(&quot;mypost&quot;, { result: data });\n }\n});\n});\n</code></pre>\n</blockquote>\n<p>The line before the line containing <code>post.save()</code> through the second to last line should be indented one level for consistent formatting.</p>\n<h2 id=\"variable-naming-o9xa\">Variable Naming</h2>\n<p>Names like <code>data</code> aren't very informative. A name like <code>post</code> or <code>article</code> would be more appropriate.</p>\n<h2 id=\"variable-declarations-swx6\">Variable declarations</h2>\n<p>Variable <code>post</code> can be declared with <code>const</code> instead, since it is only assigned once. This can help avoid <a href=\"https://softwareengineering.stackexchange.com/a/278653/244085\">accidental re-assignment and other bugs</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T17:22:44.957", "Id": "521683", "Score": "0", "body": "Thanks Sam for you advice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T23:01:55.663", "Id": "521778", "Score": "0", "body": "You are welcome. Maybe you have already seen [the help center page _What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers) but if not please check it out." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T18:23:09.273", "Id": "264099", "ParentId": "264089", "Score": "2" } } ]
{ "AcceptedAnswerId": "264099", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T10:27:21.337", "Id": "264089", "Score": "2", "Tags": [ "node.js", "promise", "mongodb", "express.js", "ecmascript-8" ], "Title": "Blog API implementation in node.js" }
264089
<p>I am currently writing a <a href="https://github.com/SuchtyTV/Odin" rel="nofollow noreferrer">chess engine</a> to improve my C++. I was able to improve my first results in terms of performance. (It is still really weak, but it does not lose a queen in one move)</p> <p>I ended up having massive problems regarding namespaces in move generation.</p> <p>It is really not great.</p> <p>Here is some code:</p> <pre><code>#pragma once #include &lt;list&gt; #include &lt;memory&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;thread&gt; #include &lt;functional&gt; #include &quot;Board.h&quot; #include &quot;Node.h&quot; #include &quot;Utility.h&quot; namespace OdinConstants { static const std::string standardBoardFen = &quot;rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1&quot;; static const double cpuct = 2.0f; } class Node; class Odin { public: Odin(); long positions_calculated_{0}; std::shared_ptr&lt;Node&gt; start_node_; inline void searchOn() { searching_ = true; setUpForCalculations(); } inline void searchOff() { searching_ = false; } void search(); void setPosition(const std::string&amp; fen, const std::vector&lt;std::string&gt;&amp; moves); inline void setPosition(const Board&amp; board) { start_node_ = std::make_shared&lt;Node&gt;(board,std::nullopt, std::nullopt, nullptr); positions_calculated_ = 0; } static double evaluatePosition(const Board &amp;board); std::tuple&lt;int, int, Figure&gt; bestMove() const; private: std::thread computingThread_{}; bool searching_{false}; bool in_chess_{true}; void setUpForCalculations(); void computeNext(); }; /* ////////////////////////////////////////////////// * Move Generation */////////////////////////////////////////////////// Board makeMove(const Board &amp;b, std::tuple&lt;int, int, Figure&gt;); /* * Checks if king could be &quot;captured&quot; in the next move and would therefore be in * check. */ bool isCheck(const Board &amp;board, Color to_be_checked); //all moves disregardingCheck void generateAllMoves(std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt;&amp; moves, const Board&amp; board); //Checks if any move, can reach this field bool hasMoveToField(std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt;&amp; moves, const Board&amp; board, int to_field); //all moves regarding check void generateAllLegalMoves(std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt; &amp;moves, const Board&amp; board); /* * filters all Moves which would be illegal, because color would check itself or * not escape a check */ void extractLegalMoves(std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt;&amp; moves, const Board &amp; board, std::function&lt;void(std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt;&amp;, const Board &amp;)&gt; generator); namespace PAWNMOVES { void generateAllPawnMovesWithWhite(std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt; &amp;pawn_moves, const Board &amp;board, int field_num); void generateAllPawnMovesWithBlack(std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt; &amp;pawn_moves, const Board &amp;board, int field_num); void generateAllPawnMoves(std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt;&amp; , const Board&amp; board); } namespace KNIGHTMOVES { void addIfMoveable(std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt;&amp; moves, const int fromi, const int fromj, const int toi, const int toj, const Board&amp; b); void generateAllKnightMoves(std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt; &amp;, const Board &amp;board); } namespace LONGRANGEPIECEMOVES { template &lt;int dX, int dY&gt; void generateMoves(std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt;&amp; moves, const Board&amp; board, const int y, const int x); void generateAllBishopMoves(std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt;&amp; , const Board&amp; board); void generateAllRookMoves(std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt;&amp; , const Board&amp; board); void generateAllQueenMoves(std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt;&amp;, const Board&amp; board); } namespace KINGMOVES { /* * Generates a king step in any direction. Where dX, dY is the directrion. * For some weird reason, I do not fully understand: generateOneSteps needs to be header defined. */ template&lt;int dX, int dY&gt; void generateOneSteps(const int j, const int i, std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt; &amp;moves, const Board &amp;board) { int toi = i + dY; int toj = j + dX; if (!inBounds(toi, toj)) { return; } if (board[toi][toj] == EMPTY.value()) { moves.push_back(std::make_tuple((8 * i + j), (8 * toi + toj), EMPTY)); } else if (board[toi][toj] * (static_cast&lt;int&gt;(board.to_move_)) &lt;= EMPTY.value()) { moves.push_back(std::make_tuple((8 * i + j), (8 * toi + toj), EMPTY)); } } void generateAllCastling(int i, int j, std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt; &amp;moves, const Board &amp;board); void generateAllKingMoves(std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt;&amp;, const Board&amp; board); } inline bool hasNoFigure(const Board&amp; board, const int rank, const int line) { if (!inBounds(rank, line)) { return false; } return board[rank][line] == 0; } inline bool hasBlackFigure(const Board&amp; board, const int rank, const int line) { if (!inBounds(rank, line)) { return false; } return board[rank][line] &lt; 0; } inline bool hasWhiteFigure(const Board&amp; board, const int rank, const int line) { if (!inBounds(rank, line)) { return false; } return board[rank][line] &gt; 0; } /* * This method checks if the given move, does not make the king takeable, ensures the King is still protected. */ bool checkIfMoveIsIllegalDueCheck(const Board &amp;b, std::tuple&lt;int, int, Figure&gt; move); /* * This currys checkIfMoveIsIllegalDueCheck(const Board &amp;b, std::tuple&lt;int, int, Figure&gt; move); */ inline std::function&lt;bool(std::tuple&lt;int, int, Figure&gt;)&gt; checkIfMoveIsIllegalDueCheck(const Board&amp; b){ return [b](std::tuple&lt;int, int, Figure&gt; move) -&gt; bool { return checkIfMoveIsIllegalDueCheck(b, move); }; } bool isCheckMate(const Board&amp; b); bool isStaleMate(const Board&amp; b); </code></pre> <p>And here are additional files.</p> <pre><code>// Pawnlogic.cc // Created by Niclas Schwalbe on 30.05.21. // #include &quot;Odin.h&quot; inline void generatePawnPromotion(std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt; &amp;seq, const int field, const int new_field) { seq.push_back(std::make_tuple(field, new_field, BKNIGHT)); seq.push_back(std::make_tuple(field, new_field, BBISHOP)); seq.push_back(std::make_tuple(field, new_field, BROOK)); seq.push_back(std::make_tuple(field, new_field, BQUEEN)); } void PAWNMOVES::generateAllPawnMovesWithWhite(std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt; &amp;pawn_moves, const Board &amp;board, int field_num) { int rank = field_num / 8; int line = field_num % 8; if (hasNoFigure(board, rank + 1, line)) { int new_field{field_num + 8}; if (rank == 6) { generatePawnPromotion(pawn_moves, field_num, new_field); } else { pawn_moves.push_back(std::make_tuple(field_num, new_field, EMPTY)); } } if (rank == 1 &amp;&amp; hasNoFigure(board, rank + 2, line) &amp;&amp; hasNoFigure(board, rank + 1, line)) { pawn_moves.push_back(std::make_tuple(field_num, field_num + 16, EMPTY)); } int left = line - 1; int right = line + 1; if (0 &lt;= left &amp;&amp; left &lt; 8 &amp;&amp; hasBlackFigure(board, rank + 1, left)) { int new_field{field_num + 7}; if (rank == 6) { generatePawnPromotion(pawn_moves, field_num, new_field); } else { pawn_moves.push_back(std::make_tuple(field_num, new_field, EMPTY)); } } if (0 &lt;= right &amp;&amp; right &lt; 8 &amp;&amp; hasBlackFigure(board, rank + 1, right)) { int new_field{field_num + 9}; if (rank == 6) { generatePawnPromotion(pawn_moves, field_num, new_field); } else { pawn_moves.push_back(std::make_tuple(field_num, new_field, EMPTY)); } } } void PAWNMOVES::generateAllPawnMovesWithBlack(std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt; &amp;pawn_moves, const Board &amp;board, int field_num) { int rank = field_num / 8; int line = field_num % 8; if (hasNoFigure(board, rank - 1, line)) { int new_field{field_num - 8}; if (rank == 1) { generatePawnPromotion(pawn_moves, field_num, new_field); } else { pawn_moves.push_back(std::make_tuple(field_num, new_field, EMPTY)); } } if (rank == 6 &amp;&amp; hasNoFigure(board, rank - 2, line) &amp;&amp; hasNoFigure(board, rank - 1, line)) { pawn_moves.push_back(std::make_tuple(field_num, field_num - 16, EMPTY)); } int left = line - 1; int right = line + 1; if (0 &lt;= left &amp;&amp; left &lt; 8 &amp;&amp; hasWhiteFigure(board, rank - 1, left)) { int new_field{field_num - 9}; if (rank == 1) { generatePawnPromotion(pawn_moves, field_num, new_field); } else { pawn_moves.push_back(std::make_tuple(field_num, new_field, EMPTY)); } } if (0 &lt;= right &amp;&amp; right &lt; 8 &amp;&amp; hasWhiteFigure(board, rank - 1, right)) { int new_field{field_num - 7}; if (rank == 1) { generatePawnPromotion(pawn_moves, field_num, new_field); } else { pawn_moves.push_back(std::make_tuple(field_num, new_field, EMPTY)); } } } void PAWNMOVES::generateAllPawnMoves(std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt; &amp;moves, const Board &amp;board) { auto pawn = board.to_move_ == Color::WHITE ? WPAWN : BPAWN; for(int fieldnum = 0; fieldnum &lt; 64; fieldnum++){ if(board(fieldnum) == pawn.value()){ switch (board.to_move_) { case Color::BLACK: generateAllPawnMovesWithBlack(moves, board, fieldnum); break; case Color::WHITE: generateAllPawnMovesWithWhite(moves, board, fieldnum); break; } } } } </code></pre> <p>Movegeneration.cc</p> <pre><code> // // Created by Niclas Schwalbe on 13.07.21. // #include &quot;Odin.h&quot; Board makeMove(const Board &amp;old_b, std::tuple&lt;int, int, Figure&gt; t) { // copy Board Board new_b{old_b}; const auto from_field{std::get&lt;0&gt;(t)}; const auto to_field{std::get&lt;1&gt;(t)}; const auto promotion{std::get&lt;2&gt;(t)}; // value of the piece to be moved. int temp = new_b(from_field); new_b(from_field) = EMPTY.value(); // is the move an en passant? auto pawn = old_b.to_move_ == Color::WHITE ? WPAWN : BPAWN; if (old_b(from_field) == pawn.value() &amp;&amp; old_b.en_passant_field_ == to_field) { if (old_b.to_move_ == Color::WHITE) { new_b(to_field - 8) = EMPTY.value(); } else { new_b(to_field + 8) = EMPTY.value(); } } // is it pawn move with 2 steps, if yes set en_passant if (old_b(from_field) == pawn.value() &amp;&amp; abs(from_field - to_field) == 16) { new_b.en_passant_field_ = new_b.to_move_ == Color::WHITE ? from_field + 8 : from_field - 8; } else { new_b.en_passant_field_ = -1; } // if move is castle, then set rook and remove castling rights auto king = old_b.to_move_ == Color::WHITE ? WKING : BKING; if (old_b(from_field) == king.value() &amp;&amp; abs(from_field - to_field) == 2) { if (to_field % 8 &lt; 5) { new_b((from_field / 8) * 8) = EMPTY.value(); new_b((from_field / 8) * 8 + 3) = king.color() * WROOK.value(); } else { new_b((from_field / 8) * 8 + 7) = EMPTY.value(); new_b((from_field / 8) * 8 + 5) = king.color() * WROOK.value(); } if (old_b.to_move_ == Color::WHITE) { new_b.long_castle_white_ = false; new_b.short_castle_white_ = false; } else { new_b.long_castle_black_ = false; new_b.short_castle_black_ = false; } } // Set new position, promote pawn if necessary if (promotion.value() == 0) { new_b(to_field) = temp; } else { new_b(to_field) = promotion.value(); } // change color new_b.to_move_ = old_b.to_move_ == Color::WHITE ? Color::BLACK : Color::WHITE; return new_b; } void generateAllLegalMoves(std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt; &amp;moves, const Board &amp;board) { extractLegalMoves(moves, board, generateAllMoves); } void generateAllMoves(std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt; &amp;moves, const Board &amp;board) { bool colb = Color::WHITE == board.to_move_; auto pawn = colb ? WPAWN : BPAWN; auto knight = colb ? WKNIGHT : BKNIGHT; auto bishop = colb ? WBISHOP : BBISHOP; auto rook = colb ? WROOK : BROOK; auto queen = colb ? WQUEEN : BQUEEN; auto king = colb ? WKING : BKING; for (int fieldnum = 0; fieldnum &lt; 64; fieldnum++) { auto val = board(fieldnum); int y = fieldnum / 8; int x = fieldnum % 8; if (val == pawn.value()) { switch (board.to_move_) { case Color::WHITE: PAWNMOVES::generateAllPawnMovesWithWhite(moves, board, fieldnum); break; case Color::BLACK: PAWNMOVES::generateAllPawnMovesWithBlack(moves, board, fieldnum); } } else if (val == knight.value()) { KNIGHTMOVES::addIfMoveable(moves, y, x, y - 2, x + 1, board); KNIGHTMOVES::addIfMoveable(moves, y, x, y - 2, x - 1, board); KNIGHTMOVES::addIfMoveable(moves, y, x, y + 2, x + 1, board); KNIGHTMOVES::addIfMoveable(moves, y, x, y + 2, x - 1, board); KNIGHTMOVES::addIfMoveable(moves, y, x, y - 1, x + 2, board); KNIGHTMOVES::addIfMoveable(moves, y, x, y - 1, x - 2, board); KNIGHTMOVES::addIfMoveable(moves, y, x, y + 1, x + 2, board); KNIGHTMOVES::addIfMoveable(moves, y, x, y + 1, x - 2, board); } else if (val == bishop.value()) { LONGRANGEPIECEMOVES::generateMoves&lt;1, 1&gt;(moves, board, y, x); LONGRANGEPIECEMOVES::generateMoves&lt;1, -1&gt;(moves, board, y, x); LONGRANGEPIECEMOVES::generateMoves&lt;-1, -1&gt;(moves, board, y, x); LONGRANGEPIECEMOVES::generateMoves&lt;-1, 1&gt;(moves, board, y, x); } else if (val == rook.value()) { LONGRANGEPIECEMOVES::generateMoves&lt;1, 0&gt;(moves, board, y, x); LONGRANGEPIECEMOVES::generateMoves&lt;0, -1&gt;(moves, board, y, x); LONGRANGEPIECEMOVES::generateMoves&lt;-1, 0&gt;(moves, board, y, x); LONGRANGEPIECEMOVES::generateMoves&lt;0, 1&gt;(moves, board, y, x); } else if (val == queen.value()) { LONGRANGEPIECEMOVES::generateMoves&lt;1, 1&gt;(moves, board, y, x); LONGRANGEPIECEMOVES::generateMoves&lt;1, 0&gt;(moves, board, y, x); LONGRANGEPIECEMOVES::generateMoves&lt;1, -1&gt;(moves, board, y, x); LONGRANGEPIECEMOVES::generateMoves&lt;-1, -1&gt;(moves, board, y, x); LONGRANGEPIECEMOVES::generateMoves&lt;-1, 0&gt;(moves, board, y, x); LONGRANGEPIECEMOVES::generateMoves&lt;-1, 1&gt;(moves, board, y, x); LONGRANGEPIECEMOVES::generateMoves&lt;0, -1&gt;(moves, board, y, x); LONGRANGEPIECEMOVES::generateMoves&lt;0, 1&gt;(moves, board, y, x); } else if (val == king.value()) { KINGMOVES::generateOneSteps&lt;1, 0&gt;(x, y, moves, board); KINGMOVES::generateOneSteps&lt;1, 1&gt;(x, y, moves, board); KINGMOVES::generateOneSteps&lt;1, -1&gt;(x, y, moves, board); KINGMOVES::generateOneSteps&lt;-1, 0&gt;(x, y, moves, board); KINGMOVES::generateOneSteps&lt;-1, -1&gt;(x, y, moves, board); KINGMOVES::generateOneSteps&lt;-1, 1&gt;(x, y, moves, board); KINGMOVES::generateOneSteps&lt;0, -1&gt;(x, y, moves, board); KINGMOVES::generateOneSteps&lt;0, 1&gt;(x, y, moves, board); KINGMOVES::generateAllCastling(x, y, moves, board); } } } void extractLegalMoves( std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt; &amp;moves, const Board &amp;board, std::function&lt;void(std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt; &amp;, const Board &amp;)&gt; generator) { std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt; new_moves; generator(new_moves, board); for (auto &amp;t : new_moves) { if (!checkIfMoveIsIllegalDueCheck(board, t)) { moves.push_back(t); } } } bool checkIfMoveIsIllegalDueCheck(const Board &amp;b, std::tuple&lt;int, int, Figure&gt; move) { Board new_board = makeMove(b, move); return isCheck(new_board, b.to_move_); } bool hasMoveToField(const Board &amp;old_b, int to_field) { auto color = old_b.to_move_ == Color::WHITE ? 1 : -1; int x = to_field % 8; int y = to_field / 8; Figure pawn{WPAWN.value(), color}; Figure knight{WKNIGHT.value(), color}; Figure bishop{WBISHOP.value(), color}; Figure rook{WROOK.value(), color}; Figure queen{WQUEEN.value(), color}; Figure king{WKING.value(), color}; Board board{old_b}; board.to_move_ = (board.to_move_ == Color::WHITE) ? Color::BLACK : Color::WHITE; std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt; knightmoves; KNIGHTMOVES::addIfMoveable(knightmoves, y, x, y - 2, x + 1, board); KNIGHTMOVES::addIfMoveable(knightmoves, y, x, y - 2, x - 1, board); KNIGHTMOVES::addIfMoveable(knightmoves, y, x, y + 2, x + 1, board); KNIGHTMOVES::addIfMoveable(knightmoves, y, x, y + 2, x - 1, board); KNIGHTMOVES::addIfMoveable(knightmoves, y, x, y - 1, x + 2, board); KNIGHTMOVES::addIfMoveable(knightmoves, y, x, y - 1, x - 2, board); KNIGHTMOVES::addIfMoveable(knightmoves, y, x, y + 1, x + 2, board); KNIGHTMOVES::addIfMoveable(knightmoves, y, x, y + 1, x - 2, board); for(auto&amp; [from, to, E] : knightmoves){ if(board(to) == knight.value()){ return true; } } std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt; bishopmoves; LONGRANGEPIECEMOVES::generateMoves&lt;1, 1&gt;(bishopmoves, board, y, x); LONGRANGEPIECEMOVES::generateMoves&lt;1, -1&gt;(bishopmoves, board, y, x); LONGRANGEPIECEMOVES::generateMoves&lt;-1, -1&gt;(bishopmoves, board, y, x); LONGRANGEPIECEMOVES::generateMoves&lt;-1, 1&gt;(bishopmoves, board, y, x); for(auto&amp; [from, to, E] : bishopmoves){ if(board(to) == bishop.value() || board(to) == queen.value()){ return true; } } std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt; rookmoves; LONGRANGEPIECEMOVES::generateMoves&lt;1, 0&gt;(rookmoves, board, y, x); LONGRANGEPIECEMOVES::generateMoves&lt;0, -1&gt;(rookmoves, board, y, x); LONGRANGEPIECEMOVES::generateMoves&lt;-1, 0&gt;(rookmoves, board, y, x); LONGRANGEPIECEMOVES::generateMoves&lt;0, 1&gt;(rookmoves, board, y, x); for(auto&amp; [from, to, E] : rookmoves){ if(board(to) == rook.value() || board(to) == queen.value()){ return true; } } std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt; kingmoves; KINGMOVES::generateOneSteps&lt;1, 0&gt;(x, y, kingmoves, board); KINGMOVES::generateOneSteps&lt;1, 1&gt;(x, y, kingmoves, board); KINGMOVES::generateOneSteps&lt;1, -1&gt;(x, y, kingmoves, board); KINGMOVES::generateOneSteps&lt;-1, 0&gt;(x, y, kingmoves, board); KINGMOVES::generateOneSteps&lt;-1, -1&gt;(x, y, kingmoves, board); KINGMOVES::generateOneSteps&lt;-1, 1&gt;(x, y, kingmoves, board); KINGMOVES::generateOneSteps&lt;0, -1&gt;(x, y, kingmoves, board); KINGMOVES::generateOneSteps&lt;0, 1&gt;(x, y, kingmoves, board); for(auto&amp; [from, to, E] : kingmoves){ if(board(to) == king.value()){ return true; } } switch (old_b.to_move_) { case Color::WHITE: return (inBounds(x-1,y-1) &amp;&amp; board[y-1][x-1] == pawn.value()) || (inBounds(x+1,y-1) &amp;&amp; board[y-1][x+1] == pawn.value()); case Color::BLACK: return (inBounds(x-1,y+1) &amp;&amp; board[y+1][x-1] == pawn.value()) || (inBounds(x+1,y+1) &amp;&amp; board[y+1][x+1] == pawn.value()); } } bool isCheck(const Board &amp;b, Color color_to_be_checked) { std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt; moves; if (b.to_move_ == color_to_be_checked) { Board passTurn{b}; passTurn.to_move_ = b.to_move_ == Color::WHITE ? Color::BLACK : Color::WHITE; return isCheck(passTurn, color_to_be_checked); } else { int field_num{0}; auto figure = b.to_move_ == Color::WHITE ? BKING : WKING; for (auto p : b) { if (p == figure.value()) { break; } field_num++; } return hasMoveToField(b, field_num); } } bool isCheckMate(const Board &amp;board) { if (!isCheck(board, board.to_move_)) { return false; } //smarter way if (board.is_end_position.has_value()) { return board.is_end_position.value(); } //else Bruteforce std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt; vec{}; generateAllLegalMoves(vec, board); return vec.size() == 0; } bool isStaleMate(const Board &amp;board) { if (isCheck(board, board.to_move_)) { return false; } //smarter way if (board.is_end_position.has_value()) { return board.is_end_position.value(); } //else Brutforce std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt; vec{}; generateAllLegalMoves(vec, board); return vec.size() == 0; } </code></pre> <p>Longrangepiecelogic.cc</p> <pre><code>#include &quot;Odin.h&quot; /* * Generates long range piece moves. Where dX, dY is the direction the piece is going to. * A rook and a rook need 4 directions * A queen needs 6 directions */ template &lt;int dX, int dY&gt; void LONGRANGEPIECEMOVES::generateMoves(std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt;&amp; moves, const Board&amp; board, const int y, const int x) { int tox = x; int toy = y; for (int i = 0; i &lt; 8 &amp;&amp; inBounds(tox + dX, toy + dY); i++) { tox += dX; toy += dY; if (board[toy][tox] == EMPTY.value()) { moves.push_back(std::make_tuple((8 * y + x), (8 * toy + tox), EMPTY)); continue; } else if (board[toy][tox] * (static_cast&lt;int&gt;(board.to_move_)) &lt;= EMPTY.value()) { moves.push_back(std::make_tuple((8 * y + x), (8 * toy + tox), EMPTY)); break; } break; } } void LONGRANGEPIECEMOVES::generateAllBishopMoves(std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt;&amp; moves, const Board&amp; board) { auto piece = board.to_move_ == Color::WHITE ? WBISHOP : BBISHOP; for (int y = 0; y &lt; 8; y++) { for (int x = 0; x &lt; 8; x++) { if (board[y][x] == piece.value()) { LONGRANGEPIECEMOVES::generateMoves&lt;1, 1&gt;(moves, board, y, x); LONGRANGEPIECEMOVES::generateMoves&lt;1, -1&gt;(moves, board, y, x); LONGRANGEPIECEMOVES::generateMoves&lt;-1, -1&gt;(moves, board, y, x); LONGRANGEPIECEMOVES::generateMoves&lt;-1, 1&gt;(moves, board, y, x); } } } } void LONGRANGEPIECEMOVES::generateAllRookMoves(std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt;&amp; moves, const Board&amp; board) { auto piece = board.to_move_ == Color::WHITE ? WROOK : BROOK; for (int y = 0; y &lt; 8; y++) { for (int x = 0; x &lt; 8; x++) { if (board[y][x] == piece.value()) { LONGRANGEPIECEMOVES::generateMoves&lt;1, 0&gt;(moves, board, y, x); LONGRANGEPIECEMOVES::generateMoves&lt;0, -1&gt;(moves, board, y, x); LONGRANGEPIECEMOVES::generateMoves&lt;-1, 0&gt;(moves, board, y, x); LONGRANGEPIECEMOVES::generateMoves&lt;0, 1&gt;(moves, board, y, x); } } } } void LONGRANGEPIECEMOVES::generateAllQueenMoves(std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt;&amp; moves, const Board&amp; board) { auto piece = board.to_move_ == Color::WHITE ? WQUEEN : BQUEEN; for (int y = 0; y &lt; 8; y++) { for (int x = 0; x &lt; 8; x++) { if (board[y][x] == piece.value()) { LONGRANGEPIECEMOVES::generateMoves&lt;1, 1&gt;(moves, board, y, x); LONGRANGEPIECEMOVES::generateMoves&lt;1, -1&gt;(moves, board, y, x); LONGRANGEPIECEMOVES::generateMoves&lt;-1, -1&gt;(moves, board, y, x); LONGRANGEPIECEMOVES::generateMoves&lt;-1, 1&gt;(moves, board, y, x); LONGRANGEPIECEMOVES::generateMoves&lt;1, 0&gt;(moves, board, y, x); LONGRANGEPIECEMOVES::generateMoves&lt;0, -1&gt;(moves, board, y, x); LONGRANGEPIECEMOVES::generateMoves&lt;-1, 0&gt;(moves, board, y, x); LONGRANGEPIECEMOVES::generateMoves&lt;0, 1&gt;(moves, board, y, x); } } } } </code></pre> <p>Kinglogic.cc</p> <pre><code>#include &quot;Odin.h&quot; /* * Generates all castling moves. If the king is in check after the castling, the move will be generated and can be filtered out later. * However, if the king would be in check while crossing, the move would not be added. */ void KINGMOVES::generateAllCastling(int j, int i, std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt; &amp;moves, const Board &amp;board) { //check if King is at original position. if (!((board.to_move_ == Color::BLACK &amp;&amp; i == 7 &amp;&amp; j == 4) || (board.to_move_ == Color::WHITE &amp;&amp; i == 0 &amp;&amp; j == 4))) { return; } switch (board.to_move_) { /* * If the side still has castling sides, the space between king and rook is free, the rook still is at original position * and the king could not be captured while moving to its desired position. */ //case WHITE case Color::WHITE: if (board.long_castle_white_ &amp;&amp; !checkIfMoveIsIllegalDueCheck(board, std::make_tuple(4, 3, EMPTY)) &amp;&amp; board[0][1] == EMPTY.value() &amp;&amp; board[0][2] == EMPTY.value() &amp;&amp; board[0][3] == EMPTY.value() &amp;&amp; board[0][0] == WROOK.value()) { moves.push_back(std::make_tuple(4, 2, EMPTY)); } if (board.short_castle_white_ &amp;&amp; !checkIfMoveIsIllegalDueCheck(board, std::make_tuple(4, 5, EMPTY)) &amp;&amp; board[0][5] == EMPTY.value() &amp;&amp; board[0][6] == EMPTY.value() &amp;&amp; board[0][7] == WROOK.value()) { moves.push_back(std::make_tuple(4, 6, EMPTY)); } break; //case BLACK default: if (board.long_castle_black_ &amp;&amp; !checkIfMoveIsIllegalDueCheck(board, std::make_tuple(60, 59, EMPTY)) &amp;&amp; board[7][1] == EMPTY.value() &amp;&amp; board[7][2] == EMPTY.value() &amp;&amp; board[7][3] == EMPTY.value() &amp;&amp; board[7][0] == BROOK.value()) { moves.push_back(std::make_tuple(60, 58, EMPTY)); } if (board.short_castle_black_ &amp;&amp; !checkIfMoveIsIllegalDueCheck(board, std::make_tuple(60, 61, EMPTY)) &amp;&amp; board[7][5] == EMPTY.value() &amp;&amp; board[7][6] == EMPTY.value() &amp;&amp; board[7][7] == BROOK.value()) { moves.push_back(std::make_tuple(60, 62, EMPTY)); } } } void KINGMOVES::generateAllKingMoves(std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt; &amp;moves, const Board &amp;board) { auto piece = board.to_move_ == Color::WHITE ? WKING : BKING; for (int i = 0; i &lt; 8; i++) { for (int j = 0; j &lt; 8; j++) { if (board[i][j] == piece.value()) { KINGMOVES::generateOneSteps&lt;1, 0&gt;(j, i, moves, board); KINGMOVES::generateOneSteps&lt;1, 1&gt;(j, i, moves, board); KINGMOVES::generateOneSteps&lt;1, -1&gt;(j, i, moves, board); KINGMOVES::generateOneSteps&lt;-1, 0&gt;(j, i, moves, board); KINGMOVES::generateOneSteps&lt;-1, -1&gt;(j, i, moves, board); KINGMOVES::generateOneSteps&lt;-1, 1&gt;(j, i, moves, board); KINGMOVES::generateOneSteps&lt;0, -1&gt;(j, i, moves, board); KINGMOVES::generateOneSteps&lt;0, 1&gt;(j, i, moves, board); KINGMOVES::generateAllCastling(j, i, moves, board); return; } } } } </code></pre> <p>Knightlogic.cc</p> <pre><code>#include &lt;vector&gt; #include &lt;tuple&gt; #include &quot;Odin.h&quot; //adds Knight move if moveable inline void KNIGHTMOVES::addIfMoveable(std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt;&amp; moves, const int fromi, const int fromj, const int toi, const int toj, const Board&amp; b) { int opposite = b.to_move_ == Color::WHITE ? -1 : 1; if (!inBounds(toi, toj)) { return; } if (opposite * b[toi][toj] &gt;= 0) { int old_field = fromi * 8 + fromj; int new_field = toi * 8 + toj; moves.push_back(std::make_tuple(old_field, new_field, EMPTY)); } return; } void KNIGHTMOVES::generateAllKnightMoves(std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt;&amp; moves, const Board&amp; board) { auto piece = board.to_move_ == Color::WHITE ? WKNIGHT : BKNIGHT; for (int i = 0; i &lt; 8; i++) { for (int j = 0; j &lt; 8; j++) { if (board[i][j] == piece.value()) { KNIGHTMOVES::addIfMoveable(moves, i, j, i - 2, j + 1, board); KNIGHTMOVES::addIfMoveable(moves, i, j, i - 2, j - 1, board); KNIGHTMOVES::addIfMoveable(moves, i, j, i + 2, j + 1, board); KNIGHTMOVES::addIfMoveable(moves, i, j, i + 2, j - 1, board); KNIGHTMOVES::addIfMoveable(moves, i, j, i - 1, j + 2, board); KNIGHTMOVES::addIfMoveable(moves, i, j, i - 1, j - 2, board); KNIGHTMOVES::addIfMoveable(moves, i, j, i + 1, j + 2, board); KNIGHTMOVES::addIfMoveable(moves, i, j, i + 1, j - 2, board); } } } } </code></pre> <p>I have some general questions:</p> <ol> <li><p>As you see in the Odin.h file, namespaces are declared. However, for some weird reasons, I had to include the <code>KINGMOVES::generateOneStep</code> into the header file and could not define it in the kinglogic.cc, while this was possible with the similar <code>generatesMoves</code> from the longrangepiecelogic.cc. How to fix that?</p> </li> <li><p>How could a better structure of this move generation look like?</p> </li> <li><p>There are some functions, where White and Black do different things (Pawnlogic.cc) This make it really clumsy. Any idea on how to fix that?</p> </li> <li><p>What else would you improve?</p> </li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T15:22:59.837", "Id": "521625", "Score": "0", "body": "Where is `EMPTY` defined?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T22:14:00.867", "Id": "521656", "Score": "0", "body": "In an additional file, I left it out. EMPTY is an Piece with color white and value 0.\nSo you can check if the board is clear with Empty.value()" } ]
[ { "body": "<blockquote>\n<p>For some weird reason, I do not fully understand: <code>generateOneSteps</code> needs to be header defined.</p>\n</blockquote>\n<pre><code>template&lt;int dX, int dY&gt;\nvoid generateOneSteps(const int j, const int i,\n std::vector&lt;std::tuple&lt;int, int, Figure&gt;&gt; &amp;moves,\n const Board &amp;board) {\n</code></pre>\n<p>Because it's a template! If you declared it only, without any body, then when you call it the compiler can't specialize it since the body is in a different source file from the call. So it codes the call but doesn't generate the specialization's code. Meanwhile, in the file that does have the body, nothing causes any specialization. So in the end you get a linker error because the function is never generated anywhere.</p>\n<p>You would have to add a line to the file where the body is defined, for each form that you want to be generated. See <a href=\"https://en.cppreference.com/w/cpp/language/class_template#Explicit_instantiation\" rel=\"nofollow noreferrer\">explicit instantiation</a> in Cppreference. But, we normally just put templates in the header.</p>\n<hr />\n<p>I don't see why <code>generateOneSteps</code> needs to have <code>dX</code> and <code>dY</code> given as template arguments. It looks like it's just used in arithmetic, and would work just fine as normal parameters.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T22:16:30.337", "Id": "521657", "Score": "0", "body": "But why is LONGRANGEPIECEMOVES::generateMoves working ?\nYou see it above the KINGMOVES" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T23:32:11.293", "Id": "521660", "Score": "0", "body": "In other words, a template is just a safer macro than `#define`. In newer C++ convention, a project has many \".hpp\" files and a few \".cpp\" files instead of the pairs of \".h/.hpp\" files and \".cpp\" files." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T14:04:07.760", "Id": "521793", "Score": "0", "body": "@Niclas because it is defined in Longrangepiecelogic.cc _before_ it is called. Do you understand that .h files are simply text spliced in at that point, and the compiler sees everything put together in a _translation unit_ ? The overriding principle is that the template definition must be seen before the call is made. Putting them in _different_ translation units, that is not going to happen. Putting the definition before the use in the same cpp file, or in a .h file that's included before the use, accomplishes that." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T15:11:17.007", "Id": "264118", "ParentId": "264092", "Score": "1" } }, { "body": "<blockquote>\n<ol start=\"3\">\n<li>There are some functions, where White and Black do different things (Pawnlogic.cc) This make it really clumsy. Any idea on how to fix that?</li>\n</ol>\n</blockquote>\n<p>I prefer functional programming, and I usually write closures. But C++ has a more statical solution. You can reduce codes by template and alias. Here is an example:</p>\n<pre><code>template &lt;int x&gt;\nint add_x(int y) {\n return y + x;\n}\n\nconstexpr auto add_2 = add_x&lt;2&gt;;\nconstexpr auto add_5 = add_x&lt;5&gt;;\n</code></pre>\n<p>I referred to the following source:\n<a href=\"https://stackoverflow.com/questions/3053561/how-do-i-assign-an-alias-to-a-function-name-in-c\">How do I assign an alias to a function name in C++?\n</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T23:03:10.627", "Id": "264133", "ParentId": "264092", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T10:51:54.740", "Id": "264092", "Score": "1", "Tags": [ "c++", "c++17", "chess" ], "Title": "Chess engine generates moves" }
264092
<p>basically i am new to python lookin for any bad practices done down there in my script, any ways to shrink the code and increase efficiency</p> <pre><code>import json, os, win32crypt, shutil, sqlite3 from Crypto.Cipher import AES tmp = os.getenv('TEMP') usa = os.environ['USERPROFILE'] triple = False both = False edb = usa + os.sep + r'AppData\Local\Microsoft\Edge\User Data\Default\Login Data' cdb = usa + os.sep + r'AppData\Local\Google\Chrome\User Data\Default\Login Data' bdb = usa + os.sep + r'AppData\Local\BraveSoftware\Brave-Browser\User Data\Default\Login Data' if os.path.exists(edb) and os.path.exists(bdb): both = True if both and os.path.exists(bdb): triple = True ckey = usa + os.sep + r'AppData\Local\Google\Chrome\User Data\Local State' ekey = usa + os.sep + r'AppData\Local\Microsoft\Edge\User Data\Local State' bkey = usa + os.sep + r'AppData\Local\BraveSoftware\Brave-Browser\User Data\Local State' def dec(pwd, key): initv = pwd[3:15] block = pwd[15:] cphr = AES.new(key, AES.MODE_GCM, initv) realAssPass = cphr.decrypt(block) realAssPass = realAssPass[:-16].decode() return realAssPass l = [&quot;LOGIN.db&quot;, &quot;LOGIN.txt&quot;, &quot;LOGINe.db&quot;, &quot;LOGINe.txt&quot;, &quot;LOGINb.db&quot;, &quot;LOGINb.txt&quot;] def main(db=cdb, keylocation=ckey, dbName=l[0], fName=l[1]): cp = shutil.copy2(db, tmp + os.sep + fr&quot;{dbName}&quot;) f = open(keylocation, &quot;r&quot;, encoding=&quot;utf-8&quot;) local_state = f.read() local_state = json.loads(local_state) maKey = b64decode(local_state['os_crypt']['encrypted_key']) maKey = maKey[5:] maKey = win32crypt.CryptUnprotectData(maKey)[1] # gotTheKeyHoe, TimeToDeCode conn = sqlite3.connect(tmp + os.sep + fr&quot;{dbName}&quot;) cursor = conn.cursor() cursor.execute(&quot;SELECT action_url, username_value, password_value FROM logins&quot;) f2 = open(tmp + os.sep + fr&quot;{fName}&quot;, &quot;w&quot;) for i in cursor.fetchall(): site = i[0] user = i[1] pas = i[2] final = dec(pas, maKey) x = f&quot;[...] User: {user}, Pass: {final}, URl: {site}&quot; f2.write('\n' + x) f2.close() if triple: main() main(bdb, bkey, l[4], l[5]) main(edb, ekey, l[2], l[3]) elif both: main() main(edb, ekey, l[2], l[3]) else: try: main() except: main(db=edb, keylocation=ekey) </code></pre> <p>FYI i am studyin cybersec and came across a script to recover browser passwords, decided to write one myself</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T13:42:23.197", "Id": "521534", "Score": "1", "body": "This seems very hardcoded, especially your paths. How would this run on another persons system with a different file structure or even worse Linux? Disregarding the serverstuff I would look into [pathlib](https://docs.python.org/3/library/pathlib.html) and particular `Path`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T15:39:25.570", "Id": "521550", "Score": "0", "body": "@N3buchadnezzar it can never work on linux. thats one reason i posted it for a solution" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T20:36:35.147", "Id": "521583", "Score": "0", "body": "I [changed the title](https://codereview.stackexchange.com/posts/264094/revisions#rev-body-51d43f6f-0f30-460a-8233-4cf991a04ee8) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate." } ]
[ { "body": "<p>There are two things that can greatly improve your code's readability.</p>\n<p>First one is, using better names. Making a variable name short makes it easier to write it. However, code is more often read than written. Hence, its better to give variables a more meaningful name. For example:</p>\n<pre class=\"lang-py prettyprint-override\"><code>chrome_db_path\nedge_db_path\nbreave_db_path\nchrome_key_path\n...\n</code></pre>\n<p>And also, as @N3buchadnezzar suggested, you could use <code>pathlib</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import os\nfrom pathlib import Path\n\ntmp_dir = Path(os.getenv('TEMP'))\nuser_profile_dir = Path(os.environ['USERPROFILE'])\n\napp_data_local_dir = user_profile_dir / 'AppData/Local'\n\nLOGIN_DATA_PATH = 'User Data/Default/Login Data'\nLOCAL_STATE_PATH = 'User Data/Local State'\n\nchrome_dir = app_data_local_dir / 'Google/Chrome'\nedge_dir = app_data_local_dir / 'Microsoft/Edge'\nbrave_dir = app_data_local_dir / 'BraveSoftware/Brave-Browser'\n\nchrome_db_path = chrome_dir / LOGIN_DATA_PATH\nedge_db_path = edge_dir / LOGIN_DATA_PATH\nbrave_db_path = brave_dir / LOGIN_DATA_PATH\n\nchrome_key_path = chrome_dir / LOCAL_STATE_PATH\n...\n\nchrome_and_edge_exist = chrome_db_path.exists() and edge_db_path.exists()\nchrome_edge_and_brave_exist = chrome_and_edge_exist and brave_db_path.exists()\n...\n</code></pre>\n<p>Also, I would recommend you to use the <code>with</code> statement, to ensure files are always closed:</p>\n<pre class=\"lang-py prettyprint-override\"><code>try:\n my_file = open(my_file_path)\n ...\nfinally:\n my_file.close()\n</code></pre>\n<p>Would be equivalent to:</p>\n<pre class=\"lang-py prettyprint-override\"><code>with open(my_file_path) as my_file:\n ...\n</code></pre>\n<p>Using <code>pathlib</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>my_file_path = Path('some/path')\nwith my_file_path.open() as my_file:\n ...\n</code></pre>\n<p>Edit:</p>\n<p>After re-reading your code, it seems like a list is not the best data structure for the files used by the different browsers. A dict will be more suitable and readable:</p>\n<pre class=\"lang-py prettyprint-override\"><code>browser_files = {\n 'chrome': {\n 'db_file': 'LOGIN.db',\n 'output_file': 'LOGIN.txt'\n },\n 'edge': {\n 'db_file': 'LOGINe.db',\n 'output_file': 'LOGINe.txt'\n },\n ...\n}\n\nchrome_files = browser_files['chrome']\nmain(chrome_db_path, chrome_key_path, chrome_files['db_file'], chrome_files['db_file'])\n...\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T16:16:23.587", "Id": "264096", "ParentId": "264094", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T13:09:10.873", "Id": "264094", "Score": "0", "Tags": [ "python", "beginner", "python-3.x", "security" ], "Title": "script to recover browser passwords" }
264094
<p>I am experimenting with asio web sockets and tried to write a simple serializer / deserializer.</p> <p>I am also thinking about an approach on how to serialize some type information alongside the actual data. This way a dont have to worry about that i might choose the wrong type when deserializing.</p> <pre><code>// serialize.hpp template&lt;typename T&gt; struct serialize { static_assert(std::is_fundamental_v&lt;T&gt; || std::is_standard_layout_v&lt;T&gt;, &quot;Only primitives and PODs can be serialized&quot;); std::array&lt;std::byte, sizeof(T)&gt; operator()(const T&amp; object) { auto buffer = std::array&lt;std::byte, sizeof(T)&gt;{}; const auto begin = static_cast&lt;const std::byte*&gt;(static_cast&lt;const void*&gt;(std::addressof(object))); std::copy_n(begin, sizeof(T), buffer.begin()); return buffer; } }; // deserialize.hpp template&lt;typename T&gt; struct deserialize { static_assert(std::is_fundamental_v&lt;T&gt; || std::is_standard_layout_v&lt;T&gt;, &quot;Only primitives and PODs can be serialized&quot;); T operator()(const std::array&lt;std::byte, sizeof(T)&gt;&amp; buffer) { T object; const auto begin = static_cast&lt;std::byte*&gt;(static_cast&lt;void*&gt;(std::addressof(object))); std::copy_n(buffer.begin(), sizeof(T), begin); return object; } }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T00:05:31.103", "Id": "521586", "Score": "1", "body": "I have a library that does this if it helps: https://github.com/Loki-Astari/ThorsSerializer Serializes into JSON/YAML/BSON with no extra code from you installed via brew." } ]
[ { "body": "<h2 id=\"stdis_standard_layout-z89z\">std::is_standard_layout</h2>\n<p><code>std::is_standard_layout_v&lt;T&gt; == true</code> does not imply that an object is a POD-type. An object is a POD-type if it is both <code>std::is_standard_layout_v&lt;T&gt; &amp;&amp; std::is_trivial_v&lt;T&gt;</code>. Here's an excellent <a href=\"https://docs.microsoft.com/en-us/cpp/cpp/trivial-standard-layout-and-pod-types?view=msvc-160\" rel=\"nofollow noreferrer\">summary</a>.</p>\n<hr />\n<h2 id=\"stdis_pod_v-lglj\">std::is_pod_v</h2>\n<p>If you're using C++17, or an older standard, you can use <code>std::is_pod_v&lt;T&gt;</code> to determine if a type is a POD-type.</p>\n<hr />\n<h2 id=\"no-need-for-stdis_fundamental_v-f290\">No need for <code>std::is_fundamental_v</code></h2>\n<p>A fundamental type is guaranteed to be a POD-type.</p>\n<hr />\n<h2 id=\"use-stdis_trivially_copyable_v-opvv\">Use <code>std::is_trivially_copyable_v</code></h2>\n<p>There are types which are memcpy-able but not POD-types. For example,</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>struct NonPODButMemcpyableType\n{\n int x = 42;\n}\n</code></pre>\n<p>The existence of the default value disqualifies it from being a POD-type. It will raise a compile error, but it should still be (de)serializable. You should <code>std::is_trivially_copyable_v&lt;T&gt;</code> instead.</p>\n<hr />\n<p>The cast to <code>const void*</code> can be avoided if you use <code>reinterpret_cast&lt;std::byte*&gt;</code>. It is legal in this case, since you're casting to a char type.</p>\n<hr />\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T19:50:27.653", "Id": "264101", "ParentId": "264100", "Score": "2" } } ]
{ "AcceptedAnswerId": "264101", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T18:26:14.593", "Id": "264100", "Score": "2", "Tags": [ "c++", "io", "stream" ], "Title": "C++ simple type serialization for streaming primitive- / pod types over a web socket (e.g. asio)" }
264100
<p>I'm currently learning Python for a masters and am trying to improve the best I can, as I'll need to know how to code in my future career.</p> <p>I currently have a function that builds a table from a dictionary, no matter how long the characters of either the keys or values are.</p> <p>However, I'm trying to get better and I'm sure there's a more &quot;Pythonic&quot; way to write this (i.e. a more simple way). This is just what I was able to come to with my limited knowledge.</p> <pre><code>def salaryTable(itemsDict): lengthRight=max( [ len(k) for k,v in itemsDict.items() ] ) lengthLeft=max( [ len(str(v)) for k,v in itemsDict.items() ] ) print( &quot;Major&quot;.ljust(lengthRight+7) + &quot;Salary&quot;.rjust(lengthLeft+7) ) print( '-' * (lengthRight+lengthLeft+14) ) for k,v in itemsDict.items(): print( k.ljust(lengthRight+7,'.') + str(v).rjust(lengthLeft+7) ) </code></pre> <p>And here's the two dictionaries I used to test both left and right:</p> <pre><code># what it produces when keys or values in the dictionary are longer than the parameter's # leftWidth and rightWidth majors={'English Composition':45000, 'Mechanical Engineering with a concentration in Maritime Mechanics':75000, 'Applied Math with a concentration in Computer Science':80000} # testing on a dictionary with a long value majors2={'English Composition':45000, 'Mechanical Engineering':75000, 'Applied Math':&quot;$100,000 thousand dollars per year USD&quot;} <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<h3 id=\"identifiers-ou1y\">Identifiers</h3>\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> recommends using snake_case for variables and functions, not camelCase.</p>\n<p>It should be <code>salary_table</code>, <code>length_right</code> and <code>items_dict</code>. Besides, do you really need <code>_dict</code> in <code>items_dict</code>?</p>\n<h3 id=\"are-you-sure-lengthleft-and-lengthright-are-proper-names-haez\">Are you sure lengthLeft and lengthRight are proper names?</h3>\n<p>It looks strange that lengthRight is the width of the left column; maybe it has something with the content of the column, but width_left looks better to me.</p>\n<h3 id=\"max-works-with-any-iterator-not-only-list-qw85\">Max works with any iterator, not only list</h3>\n<pre><code>width_left = max( len(k) for k,v in items_dict.items() )\n</code></pre>\n<p>works as well, and doesn't create a list.</p>\n<h3 id=\"you-can-iterate-over-keys-of-dict-without-items-1695\">You can iterate over keys of dict without items()</h3>\n<p>width_left = max( len(k) for k in items_dict )</p>\n<p>You can go further and use <code>max(map(len, itemsDict))</code>, but this is pythonic enough for me.</p>\n<h3 id=\"if-the-variable-is-not-used-point-this-out-with-5qlg\">If the variable is not used, point this out with _</h3>\n<pre><code>width_right = max( len(str(v)) for _, v in items_dict.items() )\n</code></pre>\n<p>But it is better to</p>\n<h3 id=\"use.values-if-you-dont-need-keys-5thz\">Use .values(), if you don't need keys</h3>\n<pre><code>width_right = max( len(str(v)) for v in items_dict.values() )\n</code></pre>\n<h3 id=\"avoid-magic-numbers-constants-without-explanation-wpz6\">Avoid &quot;magic numbers&quot; (constants without explanation)</h3>\n<p>Both lengths are added with 7; maybe it is better to add it at once and name it?</p>\n<pre><code>MINIMAL_WIDTH = 7\nwidth_left = max( len(k) for k in items_dict ) + MINIMAL_WIDTH\nwidth_right = max( len(str(v)) for v in items_dict.values() ) + MINIMAL_WIDTH\n</code></pre>\n<h3 id=\"f-strings-are-usually-more-readable-o98w\">F-strings are usually more readable</h3>\n<pre><code>print(f&quot;{k:.&lt;{length_right}}{v:&gt;{length_right}}&quot;)\n</code></pre>\n<h3 id=\"all-together-hke3\">All together</h3>\n<pre><code>def salary_table(items):\n MINIMAL_WIDTH = 7\n width_left = MINIMAL_WIDTH + max( len(k) for k in items )\n width_right = MINIMAL_WIDTH + max( len(str(v)) for v in items.values() )\n\n print( f&quot;{'Major':&lt;{width_left}}{'Salary':&gt;{width_right}}&quot; )\n print( '-' * (width_left + width_right) )\n\n for k, v in items.items():\n print( f&quot;{k:.&lt;{width_left}}{v:&gt;{width_right}}&quot; )\n</code></pre>\n<p>I don't know anything about the nature of keys and values; according to values given it can be better to rename <code>k</code> and <code>v</code> into <code>name</code> and <code>price</code>, and <code>items</code> into <code>books</code>.</p>\n<h3 id=\"alternatives-wpj0\">Alternatives</h3>\n<p>Pay attention to <a href=\"https://github.com/astanin/python-tabulate\" rel=\"nofollow noreferrer\">tabulate</a>. Maybe you better use it instead of inventing the wheel? There are also <a href=\"https://github.com/jazzband/prettytable\" rel=\"nofollow noreferrer\">PrettyTable</a> and <a href=\"https://github.com/foutaise/texttable/\" rel=\"nofollow noreferrer\">texttable</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T14:28:42.220", "Id": "521624", "Score": "1", "body": "You could make `MINIMAL_WIDTH` a defaulted kwarg of `salary_table()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T16:11:47.537", "Id": "521629", "Score": "0", "body": "Yes. Also the dot - it could be optionated, right? And the max width. And justification. I've thought about it - and the best choice would be to take one of the libraries in the Alternatives section." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T19:25:48.097", "Id": "521645", "Score": "0", "body": "Thank you so much! Especially for taking the time to explain each step and directing me to those useful cites. I'm assuming there are pretty useful codes/mods (whatever you call them) there and that's why I can just search there and not have to \"inventing the wheel\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T19:27:41.917", "Id": "521646", "Score": "0", "body": "This was so helpful because I learned how these little improvements can help in a big, besides I'm trying to become a good programmer myself so knowing these things are important." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T05:28:11.697", "Id": "521665", "Score": "0", "body": "Steve McConnel's \"Code Complete\" is still the best. Also Robert Martin's \"Clean Code\"." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T08:49:51.017", "Id": "264111", "ParentId": "264102", "Score": "4" } } ]
{ "AcceptedAnswerId": "264111", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-15T20:33:29.183", "Id": "264102", "Score": "6", "Tags": [ "python", "hash-map", "formatting" ], "Title": "Python function to print a two-column table from a dictionary" }
264102
<p>I learnt a little about genetic algorithm. And I made a program from typescript that tries to evolve and match word/sentence using genetic algorithm. But if I give a little longer sentence it takes 2000+ generation to evolve and match the sentence.</p> <p>I have two classes, one class called <code>nature</code> that generates population, natural selection, calculate fitness etc. another class called <code>Member</code> that has genes and do crossover and mutation.</p> <p>Here is Nature.ts:</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 { Member } from "./genes"; import { AudioContext } from "web-audio-api" function arraysEqual(a1: Array&lt;any&gt;,a2: Array&lt;any&gt;) { return JSON.stringify(a1)==JSON.stringify(a2); } const context = new AudioContext() class Nature { private population: Array&lt;Member&gt; private n: number private matingPool: Array&lt;Member&gt; private selected: Array&lt;Member&gt; private newPopulation: Array&lt;Member&gt; private generation_count: number constructor(private target: string, private n_population: number, private mutation_rate: number){ this.population = []; this.n = target.length; this.matingPool = []; this.selected = []; this.newPopulation = []; this.generation_count = 0; } public init(){ this.calcFitness() this.naturalSelection() this.print() this.mate() } public generatePopulation(){ for(let i = 1; i&lt;=this.n_population; i++){ this.population.push(new Member(this.n)) } } private calcFitness(){ for(let member of this.population){ const gene = member.gene; for(let i = 0; i&lt;this.n; i++){ if(gene[i] === this.target[i]){ member.score += 1 } } } } private naturalSelection(){ for(let member of this.population){ for(let i = 1; i&lt;member.score; i++){ this.matingPool.push(member) } } for(let i = 1; i&lt;=2; i++){ const rand = Math.floor(Math.random()*this.matingPool.length) this.selected.push(this.matingPool[rand]) } } private mate(){ this.newPopulation = [] for(let i = 0; i&lt;this.n_population; i++){ const parent1 = this.selected[0] const parent2 = this.selected[1] const child = parent1.crossover(parent2) // console.log(child.gene.toString().replace(",", "").replace(", ", " ")) if(arraysEqual(child.gene, this.target.split(""))){ console.log(child.gene) return } this.newPopulation.push(child) } this.updateGeneration() } private updateGeneration(){ this.population = this.newPopulation this.matingPool = [] this.selected = [] this.newPopulation = [] this.generation_count++ console.log('\x1b[36m%s\x1b[0m', `generation ${this.generation_count}`); this.init() } public print(){ } } const nature = new Nature("to be or ", 200, 0.1) nature.generatePopulation() nature.init()</code></pre> </div> </div> </p> <p>Here is Member.ts:</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>export class Member { public gene: Array&lt;string&gt; public score: number constructor(private n: number){ const strings = "abcdefghijklmnopqrstuvwxyz " this.gene = [] this.score = 0; for(let i = 0; i&lt;n; i++){ const random = Math.floor(Math.random()*strings.length) this.gene.push(strings.charAt(random)) } } private getRandomChar(){ const strings = "abcdefghijklmnopqrstuvwxyz " const random = Math.floor(Math.random()*strings.length) return strings.charAt(random) } public addGene(data: string){ this.gene.push(data) } public crossover(partner: Member){ const partner_gene = partner.gene; const gene = this.gene; const rand = Math.floor(Math.random()*(gene.length+1))-1 const child = new Member(this.n) child.gene = [] for(let i = 0; i&lt;gene.length; i++){ if(i&lt;rand){ child.addGene(gene[i]) }else{ child.addGene(partner_gene[i]) } } child.mutate(25) return child } public mutate(rate: number){ const mutation_rate = Math.random() * 100 if(mutation_rate &lt;= rate ){ const mutate_pos = Math.floor(Math.random()*this.gene.length) this.gene[mutate_pos] = this.getRandomChar() } } }</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T09:46:58.653", "Id": "521608", "Score": "0", "body": "Please remove the very last paragraph because we do not recommend projects here, we just review the code if it works." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T05:31:02.810", "Id": "264108", "Score": "1", "Tags": [ "javascript", "algorithm", "node.js", "typescript", "genetic-algorithm" ], "Title": "Genetic Algorithm Typescript" }
264108
<p>I am a junior web developer currently doing my first internship and I had a lot of freedom to solve small problems the way I thought was best. (There aren't really any developers here so I am completely on my own). My solution worked and is no longer needed, but I really want to improve and become a better programmer, so I wonder if anyone could tell me what I did wrong and how I should improve my code, or any advice in general.</p> <p>Part of my mission was to transfer images associated to products (each product has an unique identifier) from one PIM (Product Information Manager) to another, and the only way to do so was through API calls. The products had already been copied from one PIM to another, so all that was left to do was copy the images. I had only learnt C, C++ and Java up to this point, so I decided I'd learn PHP to make these kinds of scripts, so apologies in advance for the beginner's work.</p> <p>What the script does is :</p> <ul> <li><p>Get authentication tokens from the ancient and new PIM.</p> </li> <li><p>Start a loop from <code>i</code> to 3600 (amount of products)</p> </li> <li><p>Do an HTTP GET call to extract the ith product from the ancient PIM, decode the JSON file obtained containing all the product information (identifier, values, etc.) into a PHP multidimensional array.</p> </li> <li><p>Extract the identifier from the array and store it in a string variable.</p> </li> <li><p>Store every key associated to an image in the product values in an array</p> </li> <li><p>Check if this identifier exists in the new PIM, if so start a loop that iterates through every key value associated with an image, and checks if this key exists in the JSON file (some products have less images so the key doesn't even exist in the JSON).</p> </li> <li><p>If the key exists, do a GET call to download it then store it in a temp file.</p> </li> <li><p>Inject this temp file into the value of the key of the product of the new PIM.</p> </li> <li><p>Check for errors, unlink the temp image</p> </li> <li><p>Once every key image value of the product has been looped through, start the next product loop</p> </li> <li><p>There is also a time check mechanism I set in place because I need to refresh the tokens every hour.</p> <pre><code>&lt;?php /* Fonctionnement du script : - Extraction des produits du PIM enexo 1 par 1, puis extraction des images des produits pour les injecter dans les produits identiques du nouveau PIM. */ $enexoTokenCurl = curl_init(); $v2TokenCurl = curl_init(); $enexoProductCurl = curl_init(); $v2ProductCurl = curl_init(); $enexoImageDL = curl_init(); $v2ImageInject = curl_init(); curl_setopt_array($enexoTokenCurl, array( CURLOPT_URL =&gt; 'https://ancient.api.address/', CURLOPT_RETURNTRANSFER =&gt; true, CURLOPT_ENCODING =&gt; '', CURLOPT_MAXREDIRS =&gt; 10, CURLOPT_TIMEOUT =&gt; 0, CURLOPT_FOLLOWLOCATION =&gt; true, CURLOPT_HTTP_VERSION =&gt; CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST =&gt; 'POST', CURLOPT_POSTFIELDS =&gt; '{ &quot;username&quot; : &quot;redacted&quot;, &quot;password&quot; : &quot;redacted&quot;, &quot;grant_type&quot;: &quot;redacted&quot; }', CURLOPT_HTTPHEADER =&gt; array( 'Content-Type: application/json', 'Authorization: Basic redacted', 'Cookie: BAPID=redacted' ), )); curl_setopt_array($v2TokenCurl, array( CURLOPT_URL =&gt; 'http://new.api.website/', CURLOPT_RETURNTRANSFER =&gt; true, CURLOPT_ENCODING =&gt; '', CURLOPT_MAXREDIRS =&gt; 10, CURLOPT_TIMEOUT =&gt; 0, CURLOPT_FOLLOWLOCATION =&gt; true, CURLOPT_HTTP_VERSION =&gt; CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST =&gt; 'POST', CURLOPT_POSTFIELDS =&gt; '{ &quot;username&quot; : &quot;redactoo&quot;, &quot;password&quot; : &quot;redactoo&quot;, &quot;grant_type&quot;: &quot;redactoo&quot; }', CURLOPT_HTTPHEADER =&gt; array( 'Content-Type: application/json', 'Authorization: Basic redactoo', 'Cookie: BAPID=redactoo' ), )); $multiHandle = curl_multi_init(); curl_multi_add_handle($multiHandle, $enexoTokenCurl); curl_multi_add_handle($multiHandle, $v2TokenCurl); $running = null; do { curl_multi_exec($multiHandle, $running); } while ($running); curl_multi_remove_handle($multiHandle, $enexoTokenCurl); curl_multi_remove_handle($multiHandle, $v2TokenCurl); curl_multi_close($multiHandle); $enexoResponse = curl_multi_getcontent($enexoTokenCurl); $enexoToken = (json_decode($enexoResponse))-&gt;access_token; $v2Response = curl_multi_getcontent($v2TokenCurl); $v2Token = (json_decode($v2Response))-&gt;access_token; // On store dans un tableau tous les attributs d'images existant dans le pim $imageTypeAttributes = ['PV1', 'PV2', 'PV3', 'PV4', 'PV5', 'PV6', 'PV7', 'PC1', 'MS1', 'MS2', 'MS3']; $last_time = microtime(true); // On va boucler les 3599 produits de l'ancien PIM et transferer les images de produit a produit vers le nouveau for ($page_num = 1611; $page_num &lt; 3600; $page_num++) { // Recuperation du produit de la page actuelle (page_num) de l'ancien pim curl_setopt_array($enexoProductCurl, array( CURLOPT_URL =&gt; 'https://redaci.api' . $page_num . '&amp;limit=1', CURLOPT_RETURNTRANSFER =&gt; true, CURLOPT_ENCODING =&gt; '', CURLOPT_MAXREDIRS =&gt; 10, CURLOPT_TIMEOUT =&gt; 0, CURLOPT_FOLLOWLOCATION =&gt; true, CURLOPT_HTTP_VERSION =&gt; CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST =&gt; 'GET', CURLOPT_HTTPHEADER =&gt; array( 'Authorization: Bearer ' . $enexoToken, 'Cookie: BAPID=uc8igrpidb8dfcgqlf39uv2snn' ), )); // On decode le fichier JSON contenant les informations du produit $productJson = curl_exec($enexoProductCurl); $productAttributes = json_decode($productJson, true); // On recupere l'identifiant du produit importe et le tableau des valeurs d'attributs $identifier = $productAttributes['_embedded']['items'][0]['identifier']; // On remplace le caractere # contenu dans certains identifiants par %23 (solution d'echappement qui représente #) pour eviter que l'url API ne detecte le &quot;#&quot; comme fragment $hashtagID = str_replace('#', '%23', $identifier); // On rajoute les deux leading 0 qui sont supprimes par json_encode pour seulement ces deux nombres la. Bug etrange. if ($identifier === 1670 || $identifier === 1767) { $identifier = '00' . $identifier; } $values = $productAttributes['_embedded']['items'][0]['values']; $url = 'http://redacto.apo' . $hashtagID; curl_setopt_array($v2ProductCurl, array( CURLOPT_URL =&gt; $url, CURLOPT_RETURNTRANSFER =&gt; true, CURLOPT_ENCODING =&gt; '', CURLOPT_MAXREDIRS =&gt; 10, CURLOPT_TIMEOUT =&gt; 0, CURLOPT_FOLLOWLOCATION =&gt; true, CURLOPT_HTTP_VERSION =&gt; CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST =&gt; 'GET', CURLOPT_HTTPHEADER =&gt; array( 'Authorization: Bearer ' . $v2Token, 'Cookie: BAPID=kq94lmha20s2ntlb181eau6nnr' ), )); $existsError = curl_exec($v2ProductCurl); if (str_contains($existsError, 'does not exist')) { echo 'Le produit ' . $identifier . ' n\'existe pas sur le nouveau PIM : ' . $existsError . &quot;\n&quot;; } else { foreach ($imageTypeAttributes as $imageAttribute) { // On verifie si l'attribut d'image dans la boucle actuelle existe pour le produit en cours de traitement if (array_key_exists($imageAttribute, $values) &amp;&amp; array_key_exists(&quot;_links&quot;, $values[$imageAttribute][0])) { // On envoie un call API GET pour telecharger l'image stockee dans l'ancien pim correspondant a l'attribut dans la boucle actuelle curl_setopt_array($enexoImageDL, array( CURLOPT_URL =&gt; $values[$imageAttribute][0]['_links'][&quot;download&quot;]['href'], CURLOPT_RETURNTRANSFER =&gt; true, CURLOPT_ENCODING =&gt; '', CURLOPT_MAXREDIRS =&gt; 10, CURLOPT_TIMEOUT =&gt; 0, CURLOPT_FOLLOWLOCATION =&gt; true, CURLOPT_HTTP_VERSION =&gt; CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST =&gt; 'GET', CURLOPT_HTTPHEADER =&gt; array( 'Authorization: Bearer ' . $enexoToken, 'Cookie: BAPID=hv6sup4d5uc1fokhhb2orj1tj4' ), )); // On stocke l'image temporairement dans un fichier qu'on va creer avec un nom de type &quot;EAN du produit&quot; + &quot;nom de l'attribut&quot; .jpg $imgUrl = &quot;tempImage/&quot; . $values[&quot;EAN&quot;][0][&quot;data&quot;] . $imageAttribute . '.jpg'; $fp = fopen($imgUrl, 'x'); fwrite($fp, curl_exec($enexoImageDL)); fclose($fp); // On injecte l'image vers l'attribut du produit sur le nouveau pim curl_setopt_array($v2ImageInject, array( CURLOPT_URL =&gt; 'http://redictucho.del.apioucho', CURLOPT_RETURNTRANSFER =&gt; true, CURLOPT_ENCODING =&gt; '', CURLOPT_MAXREDIRS =&gt; 10, CURLOPT_TIMEOUT =&gt; 0, CURLOPT_FOLLOWLOCATION =&gt; true, CURLOPT_HTTP_VERSION =&gt; CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST =&gt; 'POST', // On renseigne l'identifiant et l'attribut du produit qui sont identiques sur l'ancien et le nouveau pim, ce qui permet de transferer l'image au bon produit. CURLOPT_POSTFIELDS =&gt; array('product' =&gt; '{&quot;identifier&quot;:&quot;' . $identifier . '&quot;, &quot;attribute&quot;:&quot;' . $imageAttribute . '&quot;, &quot;scope&quot;: null,&quot;locale&quot;:null}', 'file' =&gt; new CURLFILE($imgUrl)), CURLOPT_HTTPHEADER =&gt; array( 'Authorization: Bearer ' . $v2Token, 'Content-Type: multipart/form-data', 'Cookie: BAPID=vb820vi7ec4umcmhu9n5p18p60' ), )); $error = curl_exec($v2ImageInject); if ($error) { echo '!!! ERROR !!! ' . $error . &quot; !!! ERROR !!!\n&quot;; } else { echo 'Product n°' . $identifier . ' - Image upload worked for ' . $imageAttribute . &quot;\n&quot;; } // On supprime le fichier d'image temporaire dont on n'a plus besoin unlink($imgUrl); } } } echo $page_num . ' - ' . $identifier . &quot; DONE\n\n&quot;; $check_time = microtime(true)-$last_time; if ($check_time &gt; 3500) { $enexoResponse = curl_multi_getcontent($enexoTokenCurl); $enexoToken = (json_decode($enexoResponse))-&gt;access_token; $v2Response = curl_multi_getcontent($v2TokenCurl); $v2Token = (json_decode($v2Response))-&gt;access_token; $last_time = microtime(true); } } curl_close($enexoTokenCurl); curl_close($v2TokenCurl); curl_close($enexoProductCurl); curl_close($v2ProductCurl); curl_close($enexoImageDL); curl_close($v2ImageInject); </code></pre> </li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T13:44:35.423", "Id": "521615", "Score": "0", "body": "Thanks for the advice and the improved title !" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T07:32:01.497", "Id": "264110", "Score": "2", "Tags": [ "performance", "php", "api", "rest" ], "Title": "Copy images using curl to make API calls" }
264110
<p>My goal is to look for nearest neighbours in a Boolean-assigned mapping (a Python dictionary). For this purpose I'm looping through the candidates, starting from those with the closest distance. The code will exit the loop once it finds a neighbour that meets additional criteria. My question here is for best practices to efficiently loop through the candidates.</p> <h3>Details</h3> <p>The data structure is an assignment from variables to two truth values <code>True</code> and <code>False</code>. On these data structures, one can perform a &quot;switch&quot; operation by switching an assigned truth value, and a &quot;deletion&quot; operation by which one deletes a variable from the assignment. Each operation increases the distance to the assignment by 1. In the example below, integers are used as variables for reasons of simplicity.</p> <p>I'm currently building the list of candidates by using the product of the powerset of an assignment's keys. For an assignment, the powerset of keys will contain subsets of the assignment keys, and the product of the powerset will consist of tuples of elements from the powerset. For example, for the assignment <code>a = {0: True, 1: False}</code>, one tuple in the product of the powerset will be <code>(0, 1)</code>. In this tuple, I take the keys in the first element to be those for which we perform the &quot;deletion&quot; operation. The keys in the second element are those on which the &quot;switch&quot; operation is performed. So in this example, the element <code>0</code> should be deleted, and <code>1</code> switched. Other examples for tuples would be <code>(0, {})</code> or <code>({0,1}, {})</code>.</p> <h3>The problem</h3> While the code runs well in assignment sizes of up to 10, it quickly reaches very long computation times after that. In particular, with an assignment of 20 variables, the search takes several hours, e.g.: <pre class="lang-py prettyprint-override"><code>a20 = {i: choice([True, False]) for i in range(20)} </code></pre> <h3>Example neighbours for an assignment with size = 2</h3> <p>For example, the assignment <code>a = {0: True, 1: False}</code> has the following neighbours:</p> <h4>With distance 1:</h4> <pre class="lang-py prettyprint-override"><code>{0: False, 1: False} # Assignment for 0 switched {0: True, 1: True} # Assignment for 1 switched {1: False} # Assignment for 0 deleted {0: True} # Assignment for 1 deleted </code></pre> <h4>With distance 2:</h4> <pre class="lang-py prettyprint-override"><code>{0: False, 1: True} # Assignments for 0 and 1 switched {1: True} # Assignment for 0 deleted, for 1 switched {0: False} # Assignment for 1 deleted, for 0 switched {} # Assignments for 0 and 1 deleted </code></pre> <h3>My current implementation</h3> <pre class="lang-py prettyprint-override"><code>from itertools import chain, combinations, product from random import choice def switch_deletion_neighbourhood(assignment, distance): # powerset definition from more-itertools powerset = chain.from_iterable(combinations(assignment, r) for r in range(len(assignment)+1)) # all items from P(assignment) x P(assignment) are potential neighbours, # but only if their intersection is empty and their union is equal to a distance. candidates = ([set(j) for j in list(i)] for i in product(list(powerset), repeat=2)) for c in candidates: if (not (c[0] &amp; c[1])) and (len(c[0] | c[1]) == distance): yield c # Let a be a simple toy assignment a = {i: choice([True, False]) for i in range(2)} # The loop to find near neighbours for d in range(1, len(a)+1): print(f&quot;These are the dictionaries with distance {d}&quot;) for c in switch_deletion_neighbourhood(a, d) : candidate = {**{k: a[k] for k in a if k not in c[0]}, **{k: not a[k] for k in c[1]}} # print() here serves as a dummy operation on the candidate print(candidate) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T12:21:25.060", "Id": "264115", "Score": "2", "Tags": [ "performance", "python-3.x", "combinatorics", "edit-distance" ], "Title": "Loop through the nearest switch and deletion neighbours of a Boolean assignment" }
264115
<p>I'm doing some research on Nearest Neighbor Search of quantization, where running speed is very important. As I've just started using Python, I wonder if the following code for multi-processes can be further optimized to obtain faster running speed.</p> <pre><code>import numpy as np from joblib import Parallel, delayed def search_neighbors(self, C, queries, S_ind): &quot;&quot;&quot; It will return the top k neighbors about queries, which will be saved by a matrix. C is codebook in the quantization algorithm, in this case, it's set to 1 dimension ndarray The algorithm has compressed each data into M integers. S_ind is the compressed representation of used dataset. Its shape is (num, M), where num is the numbers of used dataset. &quot;&quot;&quot; n = queries.shape[0] topk = 512 Neighbor_Matrix = np.zeros((n,topk),dtype=int) result = Parallel(n_jobs = 5)(delayed(self.search_neightbor)(C,S_ind,q,top_k=topk) for q in queries) for i in range(n): Neighbor_Matrix[i] = result[i] return Neighbor_Matrix def search_neightbor(self, C, S_ind, query, top_k=64): ''' It will return the top k neighbors about a query. ''' # M,Ks are the parameters of the quantization algorithm,which are some integers M = self.M Ks = self.Ks # Ds = (the dimension of the used data) / M. Ds = self.Ds Table = np.zeros((M, Ks)) for i in range(M): query_sub = query[i * Ds:(i + 1) * Ds] C_i = C[i * Ks * Ds:(i + 1) * Ks * Ds] codebook_i = C_i.reshape(Ds, Ks, order=&quot;F&quot;) Table[i] = query_sub.T @ codebook_i i1 = np.arange(M) quantization_inner = np.sum(Table[i1, S_ind[..., i1]], axis=1) ind = np.argpartition(quantization_inner, -top_k)[-top_k:] return ind[np.argsort(quantization_inner[ind])] </code></pre> <p>Thanks in advance for any help/suggestion.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T16:48:59.460", "Id": "521681", "Score": "0", "body": "Maybe using a slice instead of the loop `for i in range(n):\n Neighbor_Matrix[i] = result[i]` could be faster" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T16:12:28.563", "Id": "264120", "Score": "3", "Tags": [ "python", "numpy", "multiprocessing" ], "Title": "Nearest neighbor search algorithm of quantization" }
264120
<p>I recently started programming and ran into a problem in the battle algorithm. This piece of code checks if there is someone in the position of the main character. If there is, then the battle begins (action() function). If several enemies are in the same position, then the battle will go on until all the enemies in this position die.</p> <p>What I wrote works, but I don't understand how to make the code shorter, more productive and smarter. In general, point out all the shortcomings of the code. I started just recently, I don't want to continue with mistakes.</p> <pre><code>import random from random import randint ######################################HERO_CLASS############################################################## class Hero(): def __init__(self, name, level, race, position): self.name = name self.level = level self.race = race self.position = position self.maxhealth = 300 self.health = 300 self.attack = 20 self.money = 2000 self.bag = [] self.weapon = [] print(f&quot;Player {self.name} created&quot;) def walk(self): self.position += 1 print(f&quot;{self.name} go for a walk straight....your position is {self.position}&quot;) def reverse_walk(self): self.position -= 1 if self.position &lt; 0: self.position = 0 print(f&quot;{self.name} go for a walk back....your position is {self.position}&quot;) ######################################ENEMY_CLASS############################################################## class Enemy(): def __init__(self, health, attack, race): self.health = health self.attack = attack self.race = race self.position = randint(1, 5) print(f&quot;{race} create, enemy position is {self.position}&quot;) ######################################VARIABLES############################################################## Pers = Hero(&quot;JohnnyBravo&quot;, 1, &quot;Human&quot;, 0) Orc = Enemy(200, 50, &quot;Orc&quot;) Human = Enemy(200, 50, &quot;Human&quot;) Goblin = Enemy(200, 50, &quot;Goblin&quot;) enemys = [Orc, Human, Goblin] ######################################FUNCTIONS############################################################## def attack(point): damage = enemy.attack point = point - damage print(f&quot;{enemy.race} damage is {enemy.attack}&quot;) return point def attack_enemy(Enemy): damage = Pers.attack Enemy = Enemy - damage return Enemy def main_attack(): print(f&quot;You attack {enemy.race} he have {enemy.health} health point!&quot;) enemy.health = attack_enemy(enemy.health) if enemy.health &lt;= 0: enemy.health = 0 print(f&quot;After your attack {enemy.race} have {enemy.health} health point&quot;) print(f&quot;You killed {enemy.race}\n\n&quot;) return enemy.health else: print(f&quot;After your attack {enemy.race} have {enemy.health} health point&quot;) def enemy_attack(): Pers.health = attack(Pers.health) if Pers.health &lt;= 0: Pers.health = 0 print(f&quot;{Pers.name} you die:(&quot;) else: print(f&quot;{Pers.health} health left&quot;) def action(): if enemy.position == Pers.position and Pers.health &gt; 0: print(f&quot;{enemy.race} attack you! Watch out!\n\n&quot;) while True: answer = input(f&quot;&quot;&quot; _______________________________________ Press '1' to ATTACK!!!\n Press '2' walk straight\n Press '3' walk back\n _______________________________________ \n Your answer?\t\t&quot;&quot;&quot;) if answer == &quot;1&quot;: if Pers.health &gt; 0: enemy_attack() if Pers.health &lt;= 0: print(&quot;text for testing2&quot;) break if enemy.health &gt; 0 and Pers.health &gt; 0: main_attack() if enemy.health &lt;= 0: enemys.remove(enemy) break elif answer == &quot;2&quot;: Pers.walk() break elif answer == &quot;3&quot;: Pers.reverse_walk() break if len(enemys) == 0: print(&quot;There are no enemies left&quot;) print(f&quot;{Pers.name} you WIN!!!&quot;) ######################################START_GAME############################################################## while len(enemys) &gt; 0 and Pers.health &gt; 0: for enemy in enemys: if len(enemys) &gt; 0 and Pers.health &gt; 0: action() if len(enemys) &lt;= 0 or Pers.health &lt;= 0: print(&quot;text for testing1&quot;) break answer = input(&quot;&quot;&quot; Press D walk to the right\n Press A walk to the left\n Your answer?\t&quot;&quot;&quot;).upper() if answer == &quot;D&quot;: Pers.walk() for enemy in enemys: if len(enemys) &gt; 0 and Pers.health &gt; 0: action() elif answer == &quot;A&quot;: Pers.reverse_walk() for enemy in enemys: if len(enemys) &gt; 0 and Pers.health &gt; 0: action() </code></pre>
[]
[ { "body": "<h3 id=\"you-will-do-many-mistakes-pp7c\">You will do many mistakes</h3>\n<p>And this is totally normal. I don't know anyone who didn't do any mistake in his life. Everyone learns on mistakes. So don't be afraid to make mistakes - be afraid of not fixing them or not learning on them.</p>\n<h3 id=\"extra-import-mly0\">Extra import</h3>\n<pre><code>import random\n</code></pre>\n<p>is unneeded.</p>\n<pre><code>from random import randint\n</code></pre>\n<p>does the thing. Of course, if you need several functions and/or classes from the module, or have some other concerns (like if you use tens of modules and want to track every function source), you should use the first form.</p>\n<h3 id=\"think-in-oop-way-xj0y\">Think in OOP way</h3>\n<p>You have two objects interacting? Create a method (or several). Like</p>\n<pre><code>class Hero:\n ...\n def attack(self, enemy):\n enemy.health -= self.attack\n</code></pre>\n<p>or even</p>\n<pre><code> def attack(self, enemy):\n enemy.get_damage(self.attack)\n</code></pre>\n<p>The second code allows enemy to control what happens when damage is done. Don't manipulate objects with external functions - make objects do something themselves.</p>\n<h3 id=\"create-a-class-for-battlefield-5i6k\">Create a class for battlefield</h3>\n<p>Scene, Battlefield, Arena - name it as you wish; but your game probably will be bigger at some point, including menus, levels etc., and you've some useful global code stuck to current game configuration. Move all global functions and variables there.</p>\n<h3 id=\"have-only-one-main-loop-24oz\">Have only one main loop</h3>\n<p>Now you have two loops: one at the end of file, and it calls action(), which also has a loop. This is bad for many reasons - like if you want enemies to walk or heal or something every step of an outer loop, they will freeze while the inner loop is executing; you should rethink all the actions that happen in a game loop and break the code into several functions, like</p>\n<p>class Arena:\n...\ndef main_loop(self):\nwhile True:\nself.draw()\nself.get_user_action()\nself.player_action() #according to get_user_action\nself.enemies_action()</p>\n<p>Be ready to transform it into a single-step function (no loop) if you move to something like <a href=\"https://www.pygame.org/wiki/GettingStarted\" rel=\"nofollow noreferrer\">PyGame</a>.</p>\n<h3 id=\"read-pep8-7lya\">Read <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a></h3>\n<p>It's a good habit to stick to style guides</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T20:18:11.113", "Id": "521650", "Score": "0", "body": "thank you very much for the advice! about the method, yes, I thought about it, but the thought of the battle algorithm does not allow me to think about anything. I do not understand how to double-check the presence of an enemy in a position, even if there are several enemies. and be able to leave the position and go back, in general, with any movement, check for the presence of an enemy, and if you kill him, then do not leave the loop if someone is still there." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T19:05:50.717", "Id": "264127", "ParentId": "264123", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T17:40:46.177", "Id": "264123", "Score": "5", "Tags": [ "python", "beginner", "game" ], "Title": "Python text game. combat system with enemies in the same position" }
264123
<p>I made a Tkinter MP3 Player with Pygame and am looking for tips to improve. Explanation offered in comments in code, but it generally works by getting all the files in a folder. (Have censored filepaths for privacy.)</p> <pre><code>import os import glob import shutil import pygame import tkinter as tk from pytube import YouTube import tkinter.messagebox from tkinter import filedialog as fd from tkinter import simpledialog from mutagen.mp3 import MP3 from klaxon import klaxon import re import applescript from youtube_search import YoutubeSearch def sorted_alphanumeric(data): #for sorting out the music in the tkinter listbox convert = lambda text: int(text) if text.isdigit() else text.lower() alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] return sorted(data, key=alphanum_key) def listdir_nohidden(path): #for getting all files in a folder without return sorted_alphanumeric(glob.glob(os.path.join(path, '*'))) def move_file(file): #for moving a music file to the folder try: name_and_ext = os.path.basename(file) target = name_and_ext shutil.copyfile(file, target) except TypeError: pass def mp4_mp3(filepath): #for converting the downloaded mp4 file from pytube into mp3 format klaxon(title = 'MP3 Player', subtitle = 'Downloading YouTube...', message = 'This will take some time.') from moviepy.editor import VideoFileClip try: clip = VideoFileClip(filepath) clip.write_videofile(filepath.replace('.mp4', '.mp3'), logger = None) clip.close() except: pass os.remove(filepath) name, ext = os.path.splitext(filepath) os.remove(name + 'TEMP_MPY_wvf_snd.mp3') def download(link): #for downloading the youtube video yt = YouTube(link) video = yt.streams.first() filepath = video.download('/Users/****/Desktop/****/****/****/****/Files') mp4_mp3(filepath) update_music() def get_results(search): #for getting the youtube video names results = YoutubeSearch(search, max_results = 10).to_dict() res = [] for x in range(10): video = results[x] info = [] info.append(video['title']) info.append('youtube.com' + video['url_suffix']) res.append(info) return res def open_window(): #for displaying the youtube video names for downloading ans = simpledialog.askstring(title = 'YouTube Video Downloader', prompt = 'What would you like to seach for on YouTube?') if ans is not None: window2 = tk.Tk() window2.title(f'YouTube Search Results For {ans}') res = get_results(ans) tk.Button(window2, text = res[0][0], command = lambda : download(res[0][1])).grid(row = 0, column = 0, padx = 5, pady = 5) tk.Button(window2, text = res[1][0], command = lambda : download(res[1][1])).grid(row = 0, column = 1, padx = 5, pady = 5) tk.Button(window2, text = res[2][0], command = lambda : download(res[2][1])).grid(row = 1, column = 0, padx = 5, pady = 5) tk.Button(window2, text = res[3][0], command = lambda : download(res[3][1])).grid(row = 1, column = 1, padx = 5, pady = 5) tk.Button(window2, text = res[4][0], command = lambda : download(res[4][1])).grid(row = 2, column = 0, padx = 5, pady = 5) tk.Button(window2, text = res[5][0], command = lambda : download(res[5][1])).grid(row = 2, column = 1, padx = 5, pady = 5) tk.Button(window2, text = res[6][0], command = lambda : download(res[6][1])).grid(row = 3, column = 0, padx = 5, pady = 5) tk.Button(window2, text = res[7][0], command = lambda : download(res[7][1])).grid(row = 3, column = 1, padx = 5, pady = 5) tk.Button(window2, text = res[8][0], command = lambda : download(res[8][1])).grid(row = 4, column = 0, padx = 5, pady = 5) tk.Button(window2, text = res[9][0], command = lambda : download(res[9][1])).grid(row = 4, column = 1, padx = 5, pady = 5) def convert_mils(mils): #for converting the time from pygame.mixer.music.get_pos() into correct format seconds = int((mils/1000) % 60) minutes = int((mils/(1000 * 60)) % 60) return f'{minutes:02d}:{seconds:02d}' def convert_secs(seconds): #for converting the seconds from mutagen.mp3.MP3(song).info.length into correct format m = int(seconds % 3600 // 60) s = int(seconds % 3600 % 60) return f'{m:02d}:{s:02d}' def add_music(): #adding music as the user wishes try: res = applescript.AppleScript('display dialog &quot;How would you like to add music?&quot; buttons {&quot;Cancel&quot;, &quot;YouTube Search&quot;, &quot;File Upload&quot;} default button &quot;File Upload&quot;').run() for item in res: new_res = res[item] if new_res == 'File Upload': play_pause() file = get_music() if file != 'improper format': move_file(file) window.after(100, update_music) else: open_window() window.after(100, update_music) except applescript.ScriptError: pass def delete_music(): selected_file = play_list.get(tk.ACTIVE) confirm = tkinter.messagebox.askquestion('MP3 Player', 'Are you sure you want to delete ' + selected_file + '?') if confirm == 'yes': if selected_file == title.get(): pygame.mixer.music.stop() title.set('') os.remove(selected_file + '.mp3') window.after(100, update_music) def rename_music(): #renameing the song selected_song = play_list.get(tk.ACTIVE) ans = simpledialog.askstring(title = 'Music Renaming', prompt = f'What would you like to rename {selected_song} to?') if ans is not None: os.rename(selected_song + '.mp3', ans + '.mp3') title.set(ans) update_music() def edit_music(): #displaying options for editing selected_file = play_list.get(tk.ACTIVE) try: response = applescript.AppleScript('set res to display dialog &quot;Actions For Song ' + selected_file + '&quot; buttons {&quot;Cancel&quot;, &quot;Rename&quot;, &quot;Delete&quot;} default button &quot;Delete&quot;').run() for item in response: res = response[item] if res == &quot;Delete&quot;: delete_music() else: rename_music() except: pass def update_music(): #for updating the files in tkinter Listbox play_list.delete(0, tk.END) song_list = listdir_nohidden('/Users/****/Desktop/****/****/****/****/Files') for x in range(len(song_list)): orig = song_list[x] name = os.path.basename(orig) song_list[x] = name pos = 0 for item in song_list: play_list.insert(pos, item.replace('.mp3', '')) pos += 1 if play_list.size() &gt; 10: scroll.pack(side = 'right', fill = 'y') else: scroll.pack_forget() def unconvert(mins_and_secs): #for changing the '{mins:02d}:{secs:02d}' format into seconds mins, secs = mins_and_secs.split(':') if mins[0] == '0': mins = mins[1:] if secs[0] == '0': secs = secs[1:] more_secs = int(mins) * 60 total_secs = more_secs + int(secs) return total_secs def update_time(): #for updating music time tracker global already_run if pygame.mixer.music.get_pos() != -1: current_time = pygame.mixer.music.get_pos() song = MP3(title.get() + '.mp3') seconds_total = int(song.info.length) mins_and_secs = convert_mils(current_time) current_sec = unconvert(mins_and_secs) remaining_secs = seconds_total - current_sec remaining_secs = convert_secs(remaining_secs) music_time.set(f'{mins_and_secs}\t-{remaining_secs}') else: if already_run is True: music_time.set('') next_song() already_run = True window.after(99, update_time) def get_music(): #getting a file to add to songs f = fd.askopenfile(filetypes = (('MP3 Files', '*.mp3'), ('All Files', '*.*'))) if f is not None: file = f.name root, ext = os.path.splitext(file) if ext in ['.mp3']: return file else: tkinter.messagebox.showinfo('MP3 Player', 'Must be MP3 file format!') return 'improper format' def play(): #playing the music if already_run is not True: update_time() pygame.mixer.music.stop() pygame.mixer.music.load(play_list.get(tk.ACTIVE) + '.mp3') title.set(play_list.get(tk.ACTIVE)) pygame.mixer.music.play() status.set('Pause') def pause(): #pausing music pygame.mixer.music.pause() def unpause(): #resuming music pygame.mixer.music.unpause() def change_volume(volume): #chaning volume with tk.Scale pygame.mixer.music.set_volume(int(volume)/100) def on_closing(): #what to do when window is closed pygame.mixer.music.stop() pygame.mixer.quit() window.destroy() def next_selection(): #to select the next song song_name = title.get() index = play_list.get(0, &quot;end&quot;).index(song_name) selection_indices = play_list.curselection() play_list.selection_clear(selection_indices) play_list.activate(index) play_list.selection_set(index) selection_indices = play_list.curselection() next_selection = 0 if len(selection_indices) &gt; 0: last_selection = int(selection_indices[-1]) play_list.selection_clear(selection_indices) if last_selection &lt; play_list.size() - 1: next_selection = last_selection + 1 play_list.activate(next_selection) play_list.selection_set(next_selection) def next_song(): #to select next song and play it next_selection() window.after(99, play) def pause_play(): #to change the button from pause to resume stat = status.get() if stat == 'Pause': pause() status.set('Resume') else: unpause() status.set('Pause') def main(): #main function global window, title, play_list, music_time, scroll, already_run, status already_run = False window = tk.Tk() window.title('MP3 Player') window.configure(bg = 'blue') window.resizable(False, False) window.protocol('WM_DELETE_WINDOW', on_closing) controls = tk.Frame() controls.grid(column = 1, row = 1, sticky = 'nsew', padx = 10, pady = 10) controls.configure(bg = 'blue') buttons = tk.Frame() buttons.grid(column = 0, row = 0, sticky = 'nsew', padx = 10, pady = 10) buttons.configure(bg = 'blue') songs = tk.Frame() songs.grid(column = 0, row = 1, sticky = 'nsew', padx = 10, pady = 10) songs.configure(bg = 'blue') song = tk.Frame() song.grid(column = 1, row = 0, sticky = 'nsew', padx = 10, pady = 10) song.configure(bg = 'blue') song_list = listdir_nohidden('/Users/****/Desktop/****/****/****/****/Files') for x in range(len(song_list)): orig = song_list[x] name = os.path.basename(orig) song_list[x] = name play_list = tk.Listbox(songs, bg='yellow', selectmode=tk.SINGLE) scroll = tk.Scrollbar(songs) play_list.config(yscrollcommand = scroll.set) scroll.config(command = play_list.yview) pos = 0 for item in song_list: play_list.insert(pos, item.replace('.mp3', '')) pos += 1 pygame.init() pygame.mixer.init() title = tk.StringVar() music_time = tk.StringVar() status = tk.StringVar() status.set('Pause') pause_button = tk.Button(controls, textvariable = status, command = lambda : pause_play()) play_button = tk.Button(controls, text = 'Play', command = lambda : play()) add_music_button = tk.Button(buttons, text = 'Add Music', command = lambda : add_music()) delete_music_button = tk.Button(buttons, text = 'Edit Music', command = lambda : edit_music()) song_title = tk.Label(song, textvariable = title, fg = 'yellow', bg = 'blue') song_time = tk.Label(song, textvariable = music_time, fg = 'yellow', bg = 'blue') volume_scale = tk.Scale(controls, from_ = 0, to = 100, tickinterval = 0.00001, showvalue = 0, label = ' Volume', command = change_volume, orient = tk.HORIZONTAL) volume_scale.set(50) add_music_button.pack(side='top', fill = 'x') volume_scale.grid(column = 0, row = 4, sticky = 'nsew', padx = 4, pady = 4) delete_music_button.pack(side='bottom', fill = 'x') play_list.pack(side = 'left', fill = 'both') song_title.pack(side = 'top', fill = 'x') song_time.pack(side = 'bottom', fill = 'x') play_button.grid(column = 0, row = 1, sticky = 'nsew', padx = 4, pady = 4) pause_button.grid(column = 0, row = 2, sticky = 'nsew', padx = 4, pady = 4) os.chdir('/Users/****/Desktop/****/****/****/****/Files') window.after(10, update_music()) window.mainloop() if __name__ == '__main__': main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T15:41:54.463", "Id": "521679", "Score": "0", "body": "There seems to be some code missing. `play_pause` is undefined." } ]
[ { "body": "<p>In this section:</p>\n<pre><code>convert = lambda text: int(text) if text.isdigit() else text.lower()\nalphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]\n</code></pre>\n<p><code>convert</code> can be moved to a regular function. In fact you can rephrase your alphanumeric sort key as an iterator:</p>\n<pre><code>split_alpha = re.compile(r'([0-9]+)').split\n\n\ndef alphanumeric_parts(key: str) -&gt; Iterable[Union[int, str]]:\n for c in split_alpha(key):\n if c.isdigit():\n yield int(c)\n else:\n yield c.lower()\n\n\ndef alphanumeric_key(key: str) -&gt; Tuple[Union[int, str], ...]:\n return tuple(alphanumeric_parts(key))\n\n\ndef sorted_alphanumeric(data: Iterable[str]) -&gt; List[str]: # for sorting out the music in the tkinter listbox\n return sorted(data, key=alphanumeric_key)\n</code></pre>\n<p>This avoids lambdas and comprehensions in favour of generator functions, pre-compiles and pre-binds your regular expression, and replaces your inner lists with inner tuples which are a better representation of immutable data. When looking at the disassembled bytecode of your original code, there would have been three inner subroutines defined - one for each of your lambdas and one for the comprehension; the shown alternative uses two. Also note the PEP8-standard spacing between function definitions and PEP484 type hints.</p>\n<p>Otherwise:</p>\n<ul>\n<li>Consider replacing <code>os.path</code>, several <code>os.*</code>, and <code>shutil</code> calls with <code>pathlib</code> calls</li>\n<li>Move your <code>moviepy</code> import to the top of the file</li>\n<li><code>clip</code> having a <code>close()</code>, that explicit call should be removed and replaced with a context manager, as the <a href=\"https://zulko.github.io/moviepy/_modules/moviepy/Clip.html#Clip\" rel=\"nofollow noreferrer\">source shows is possible</a> due to the implementation of <code>__exit__</code></li>\n<li>Never <code>try/except/pass</code>; if you're going to swallow a specific exception, show it</li>\n<li>Don't hard-code the path for <code>download()</code>; allow the user to choose, or default to somewhere like <code>~/Downloads</code></li>\n<li>Your calls to <code>tk.Button</code> should be converted into a loop</li>\n<li>The use of AppleScript for <code>display dialog</code> is unjustified. A more portable solution is right at your fingertips - use tkinter instead.</li>\n<li>Your call to <code>play_pause</code> is incorrect and you probably meant <code>pause_play</code></li>\n<li>Your rampant use of globals <code>window, title, play_list, music_time, scroll, already_run, status</code> needs to be cleaned up - easy wins include classes, <code>partial</code>s or closures</li>\n<li>You have a bunch of UI code mixed right in with business logic, including in <code>main</code>. Try to separate these out.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T20:18:27.063", "Id": "521694", "Score": "0", "body": "Importing moviepy at the beginning makes Python quit unexpectedly." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T16:58:17.940", "Id": "264149", "ParentId": "264126", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T18:52:26.667", "Id": "264126", "Score": "1", "Tags": [ "python-3.x", "tkinter", "pygame", "music" ], "Title": "Python MP3 player with pygame.mixer and tkinter for MacOS" }
264126
<p>This function is about the fact that a std::<strong>w</strong>string was used in another cpp file in order to be able to read strings with German umlauts from the console. Since it is difficult to get wstrings into a text file when a std::ofstream is already accessing the text file, this wstring was converted into a normal std::string using utf8.h. The 16-bit characters that represented umlauts are now 2 cryptic characters (which is logical, I know). A ß becomes ß, an ü becomes ü, as you often see it in everyday life. This is corrected with this .h and .cpp files.</p> <p>By utf8.h, I mean this: <a href="https://i.stack.imgur.com/3DMdD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3DMdD.png" alt="utf8 package which I downloaded in NuGet Packet Manager" /></a></p> <p>My question is: Could you please review this function and say what you think of the code? I'm asking because the code is copying one vector to a second one a lot, and, as you see in the last lines, I need to get rid of ‘left-over’ null characters. I want to include the header and cpp file more often, so I want the two to be good.</p> <p><strong>handle_German_umlauts.cpp</strong></p> <pre><code>#include &quot;handle_German_umlauts.h&quot; Umlaute_korrigieren::Umlaute_korrigieren() { } Umlaute_korrigieren::~Umlaute_korrigieren() { } std::vector&lt;char&gt; Umlaute_korrigieren::_std__String_to_std__vectorChar_for_ANSI(std::string stdstring) { std::vector&lt;char&gt; CString(stdstring.c_str(), stdstring.c_str() + stdstring.size() + 1); std::vector&lt;char&gt; copy(stdstring.c_str(), stdstring.c_str() + stdstring.size() + 1); for (size_t i = (size_t)0; i &lt; CString.size() - (size_t)1; i++) { if (CString[i] == -61 &amp;&amp; CString[i + 1] == -97) // Pseudo-ß gefunden { copy[i] = '\xDF'; //ß ist DF(hex) in ANSI for (size_t j = copy.size() - (size_t)1; j &gt; (i+(size_t)1); j--) // umkopieren { copy[j - 1] = CString[j]; } CString = copy; } if (CString[i] == -61 &amp;&amp; CString[i + 1] == -68) // Pseudo-ü gefunden { copy[i] = '\xFC'; //ü ist FC(hex) in ANSI for (size_t j = copy.size() - (size_t)1; j &gt; (i + (size_t)1); j--) // umkopieren { copy[j - 1] = CString[j]; } CString = copy; } if (CString[i] == -61 &amp;&amp; CString[i + 1] == -92) // Pseudo-ä gefunden { copy[i] = '\xE4'; //ä ist E4(hex) in ANSI for (size_t j = copy.size() - (size_t)1; j &gt; (i + (size_t)1); j--) // umkopieren { copy[j - 1] = CString[j]; } CString = copy; } if (CString[i] == -61 &amp;&amp; CString[i + 1] == -74) // Pseudo-ö gefunden { copy[i] = '\xF6'; //ö ist F6(hex) in ANSI for (size_t j = copy.size() - (size_t)1; j &gt; (i + (size_t)1); j--) // umkopieren { copy[j - 1] = CString[j]; } CString = copy; } if (CString[i] == -61 &amp;&amp; CString[i + 1] == -124) // Pseudo-Ä gefunden { copy[i] = '\xC4'; //Ä ist C4(hex) in ANSI for (size_t j = copy.size() - (size_t)1; j &gt; (i + (size_t)1); j--) // umkopieren { copy[j - 1] = CString[j]; } CString = copy; } if (CString[i] == -61 &amp;&amp; CString[i + 1] == -106) // Pseudo-Ö gefunden { copy[i] = '\xD6'; //Ö ist D6(hex) in ANSI for (size_t j = copy.size() - (size_t)1; j &gt; (i + (size_t)1); j--) // umkopieren { copy[j - 1] = CString[j]; } CString = copy; } if (CString[i] == -61 &amp;&amp; CString[i + 1] == -100) // Pseudo-Ü gefunden { copy[i] = '\xDC'; //Ü ist DC(hex) in ANSI for (size_t j = copy.size() - (size_t)1; j &gt; (i + (size_t)1); j--) // umkopieren { copy[j - 1] = CString[j]; } CString = copy; } } // crop unnecessary ‘\0’s size_t _0Counter = 0; for (size_t i = (size_t)0; i &lt; CString.size(); i++) { if (CString[i] == '\0') { _0Counter += (size_t)1; } } size_t original = CString.size() - (size_t)1; // because the vector gets smaller due to the deletion and the for loop is always reevaluating size_t wie_weit = CString.size() - _0Counter; for (size_t i = original; i &gt; wie_weit; i--) { CString.erase(CString.begin() + i - 1); } return CString; } </code></pre> <p>The <strong>handle_German_umlauts.h</strong></p> <pre><code>#ifndef HANDLE_GERMAN_UMLAUTS_H_ #define HANDLE_GERMAN_UMLAUTS_H_ #include &lt;vector&gt; #include &lt;string&gt; class Umlaute_korrigieren { public: Umlaute_korrigieren(); ~Umlaute_korrigieren(); std::vector&lt;char&gt; _std__String_to_std__vectorChar_for_ANSI(std::string); private: }; #endif // !HANDLE_GERMAN_UMLAUTS_H_ </code></pre> <p><strong>The function is called as follows:</strong></p> <pre><code>std::string Strasse_als_stdstring; utf8::utf16to8(physical_address.street.begin(), physical_address.street.end(), back_inserter(Strasse_als_stdstring)); std::vector&lt;char&gt; korrigierte_Strasse = Uk._std__String_to_std__vectorChar_for_ANSI(Strasse_als_stdstring); for (size_t h = (size_t)0; h &lt; korrigierte_Strasse.size() - (size_t)3; h++) // write to txt. -3, so that \r\n\0 aren't printed. { fs8 &lt;&lt; korrigierte_Strasse[h]; } fs8 &lt;&lt; &quot; &quot; &lt;&lt; physical_address.house_number &lt;&lt; std::endl; </code></pre> <p>where <code>physical_address.street</code> is the std::<strong>w</strong>string (mentioned above), and the for loop serves to write the chars in the textfile (<code>std::ofstream fs8</code>).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T20:08:03.557", "Id": "521648", "Score": "0", "body": "I'm confused because this converts a wstring to utf8, but then changes some utf8 things to CP-1252, so the result is kind of a mix between CP-1252 and utf8. It's odd. It indicates that whatever is reading the data, is really using CP-1252 after all, otherwise there would be no need to do this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T20:12:28.483", "Id": "521649", "Score": "0", "body": "@harold The utf8 library converts the wstring not correctly if umlauts are in it. The result will be wrong. So today I started writing my own header file." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T21:53:11.370", "Id": "521654", "Score": "0", "body": "If the utf8 library converts the incorrectly you shouldn't be using it. However it's very unlikely that is the case. Generally modern software nowadays support umlauts (and other special characters) very well, so that the things you are doing here shouldn't be necessary and just will make the situation worse. It is more likely that you are doing something wrong (that is, you are using the library or something else incorrectly)." } ]
[ { "body": "<p>I see a few problems.</p>\n<h2 id=\"comparisons-and-counting-1bts\">Comparisons and counting</h2>\n<p>At the lowest level, you are being repetitive and inefficient with your comparisons. And you are &quot;rediscovering&quot; information you already know -- specifically, the amount of shrinkage in the string.</p>\n<p>I suggest you code your tests for characters in a cascading style, since they all depend on the same prefix character.</p>\n<p>And keep a count of the amount of shrinkage so you don't have to recount it. If you're turning two characters into one, then <code>shrinkage += 2 - 1;</code> etc.</p>\n<h2 id=\"multiple-copies-r4no\">Multiple copies</h2>\n<p>At a higher level, you are being very inefficient with your handling of <code>Cstring</code> and <code>copy</code>. Instead of &quot;moving down&quot; the characters for each special character you find, you should only copy them once, into their exactly right target location.</p>\n<p>You are doing this:</p>\n<pre><code>for i in ...\n if special character at position i\n fix special character\n move all subsequent characters down by 1\n</code></pre>\n<p>That means if your string starts with 2 special characters, you will process the first one, move all the following characters down by 1, then process the second one, and move all the following characters down by 1 <em>AGAIN.</em></p>\n<p>Instead, I think you could simple make a duplicate and copy characters into it one by one:</p>\n<pre><code>j = 0\nfor i in 0 ...\n if special character at position i:\n copy[j] = translated character\n shrinkage += ...\n j += 1\n else\n copy[j] = original[i]\n j += 1\n</code></pre>\n<p>This way you keep two separate <em>indexes</em> but you only ever copy the characters one time, into their final position.</p>\n<h2 id=\"magic-numbers-56xl\">Magic Numbers</h2>\n<p>There are few better ways to piss off the poor idiot that has to maintain your code than by throwing in a bunch of <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">magic numbers</a>! Magic numbers are one of those things that <em>every single programming language</em> provides a way to fix (usually several ways), and you always learn them early because it's soooo easy to do. Why do you have all these magic numbers in your code?</p>\n<p>What do <code>-61</code>, <code>-97</code>, <code>'\\xDF'</code>, and <code>(size_t)1</code> mean?</p>\n<h2 id=\"integer-promotions-pvbm\">Integer promotions</h2>\n<p>As an aside, <code>(size_t)1</code> is unnecessary. If you have warnings at some ridiculous level, consider using <code>1U</code>, but if there's a warning level that nags at you when you subtract a literal <code>1</code> from a variable that is already declared <code>size_t</code>, you should just turn it off -- it's making you pollute your code even worse than C++ usually does.</p>\n<h2 id=\"get-rid-of-comments-y3us\">Get rid of comments</h2>\n<p>I've already suggested that you restructure your code to get rid of all the copying and moving. And I've suggested that you restructure your <code>if</code> statements into a 2-level hierarchy of first-character, second-character.</p>\n<p>But I'll point out that having a comment explaining something is a good indicator that you can replace whatever it is with either a named object or a function call.</p>\n<p>Consider this:</p>\n<pre><code>if (CString[i] == -61 &amp;&amp; CString[i + 1] == -97) // Pseudo-ß gefunden\n</code></pre>\n<p>Now consider this:</p>\n<pre><code>#define SHARP_S -61, -97\n#define IS_SPECIAL_CHAR(c1, c2) (CString[i]==(c1) &amp;&amp; CString[i+1]==(c2))\n\nif (IS_SPECIAL_CHAR(SHARP_S))\n</code></pre>\n<p>Notice that I don't need a comment?</p>\n<p>If you've got a stupid coding standard, or a quasi-religious belief about getting rid of the C preprocessor, you can recode that macro as 200 lines of template class or something, or just rewrite it as an inline function (constexpr, even!).</p>\n<h2 id=\"names-hpfg\">Names</h2>\n<p>Be consistent. You have <code>CString</code> and <code>copy</code> and they are both locals with the same scope? How about <code>cstring</code> and <code>copy</code>? Or <code>CString</code> and <code>CString2</code>?</p>\n<p>Who thinks <code>_std__String_to_std__vectorChar_for_ANSI</code> is a good idea? Underscores, double underscores, <em>and</em> capitalization? <a href=\"https://www.youtube.com/watch?v=wpecBkdpiK4\" rel=\"nofollow noreferrer\">No, man.</a> How about <code>fix_wstring_umlaut_conversions</code> instead?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T18:29:32.697", "Id": "521688", "Score": "0", "body": "Hello @aghast, thank you for your detailed and understandable answer. I implemented everything last night. The code looks much clearer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T00:30:03.960", "Id": "521824", "Score": "0", "body": "having double-underscores in a name is Undefined Behavior." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T21:08:54.163", "Id": "264131", "ParentId": "264128", "Score": "2" } } ]
{ "AcceptedAnswerId": "264131", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T19:26:59.580", "Id": "264128", "Score": "-1", "Tags": [ "c++", "encoding" ], "Title": "I wrote a header file to write German umlauts in a textfile properly" }
264128
<p>I'm trying to learn how to write code well in Python. I've been tinkering with a function that will return a list of all prime numbers between the two parameters. This is the best I could come up with considering my limited experience.</p> <p>Do you have any ideas of how this code can be improved to become more Pythonic? (Which I think means more efficient?) If you do, would you be so kind as to not explain what you would do differently?</p> <p>This would be such a help! Here's what I have so far:</p> <pre><code>def get_primes(start,end): return [num for num in range(start,end+1) if num&gt;1 and all(num%i!=0 for i in range(2,num))] get_primes(-41,41) </code></pre>
[]
[ { "body": "<p>If you are already into programming/STEM, you will already know finding prime numbers is a tough problem. Hence, I will not comment on the efficiency of checking whether a number is primer by checking all possible divisors (which is a terrible idea if you are trying to actually find prime numbers, but it is good enough if you are simply trying to learn).</p>\n<p>Now, regarding what pythonic means, it does not refer to efficiency at all. It is about readability and the way the language features are used (it is explained in a bit more depth in <a href=\"https://stackoverflow.com/a/25011492/13688761\">this</a> answer).</p>\n<p>Furthermore, if you are new to python, and want to learn about best practises, I would recommend you giving a read to <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP-8</a>. It is a style guide for python code widely followed by the community.</p>\n<p>Edit:</p>\n<p>Still, as a comment on your code, I feel the logic to check whether a number is primer or not is complex enough to be encapsulated in a function:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from typing import Iterable\n\ndef is_prime(num: int) -&gt; bool:\n return num&gt;1 and all(num%i!=0 for i in range(2,num))\n\ndef get_primes(start: int, end:int) -&gt; Iterable[int]:\n return [num for num in range(start,end+1) if is_prime(num)]\n\nget_primes(-41,41)\n</code></pre>\n<p>If you are not yet familiar with it, the syntax used above is called type annotations. You can read more about it <a href=\"https://www.python.org/dev/peps/pep-0484/\" rel=\"noreferrer\">here</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T21:26:55.837", "Id": "264132", "ParentId": "264130", "Score": "6" } }, { "body": "<p>I too am new to this forum as well as to python.</p>\n<p>Here's my version of your solution, its a fully functional interface and not just a code snippet, that will be useful</p>\n<p>Also I followed most PEP-8 conventions, do point out any deviations, I shall correct myself.</p>\n<pre><code>def get_primes(start,end):\n l = []\n for i in range(start,end + 1):\n flag = True\n for j in range(2,i):\n if i % j == 0:\n flag = False\n if flag == True:\n l.append(i)\n return l\n\n#__main__\nans = &quot;y&quot;\nwhile ans == &quot;y&quot;:\n st = int(input(&quot;Enter starting number: &quot;))\n nd = int(input(&quot;Enter ending number: &quot;))\n print(f&quot;The list containing all prime (inclusive) between {st} and {nd} is: \\n&quot;,get_primes(st,nd))\n ans = input(&quot;Once again? (y / n): &quot;)\n</code></pre>\n<p>That should work. Do tell if any additional issues.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-18T09:32:11.010", "Id": "521705", "Score": "1", "body": "The aim of this website is to review the existing code, not to provide an alternative solution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-18T08:06:48.973", "Id": "525732", "Score": "0", "body": "All right! Thanks for the clarification" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-18T07:11:34.093", "Id": "264157", "ParentId": "264130", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-16T21:08:13.383", "Id": "264130", "Score": "3", "Tags": [ "python", "functional-programming", "primes", "iteration" ], "Title": "Python – return list (or not?) of prime numbers between two numbers" }
264130
<p>I'm attempting to import an external script into an HTML file. The name of the js file that I want to import is hosted in a SQL database. Therefore, I am using a XMLHttpRequest to access the SQL database so that I can fetch the appropriate name of the script. I then create a script element where I set src equal to 'this.responseText' which should import the name taken from the SQL database. However, the script isn't being executed and I believe it's because it's run within a function. Therefore, I would like to append the js.src to the top of the header next to 'script1' and 'script2' which I assume would then allow the script to be imported successfully. Any ideas as to how this can be done?</p> <pre><code>&lt;head&gt; &lt;title&gt;Columbia University HIT&lt;/title&gt; &lt;script src = &quot;script1.js&quot;&gt;&lt;/script&gt; &lt;script src = &quot;script2.js&quot;&gt;&lt;/script&gt; &lt;script&gt; function reqListener () { console.log(this.responseText); } var oReq = new XMLHttpRequest(); // New request object oReq.onload = function() { const js = document.createElement(&quot;script&quot;); var noQuotes = this.responseText.split('&quot;').join(''); //removes double quotes js.src = noQuotes; // script that I want to move to top of header next to 'script1' and 'script2' }; console.log(oReq.onload.); oReq.open(&quot;get&quot;, &quot;index.php&quot;, true); oReq.send(); &lt;/script&gt; </code></pre>
[]
[ { "body": "<p>I think the way you have created the element is correct but it needs to to be added to DOM.\nAdd the script element to the DOM using</p>\n<pre><code>document.body.appendChild(js):\n</code></pre>\n<p>If you want it to be added at top try doing something like this</p>\n<pre><code>let myScript = document.createElement(&quot;script&quot;);\nmyScript.setAttribute(&quot;src&quot;, &quot;https://www.example.com/foo.js&quot;);\nmyScript.setAttribute(&quot;async&quot;, &quot;false&quot;);\nlet head = document.head;\nhead.insertBefore(myScript, head.firstElementChild);\n</code></pre>\n<p>Reference :<a href=\"https://www.kirupa.com/html5/loading_script_files_dynamically.htm\" rel=\"nofollow noreferrer\">https://www.kirupa.com/html5/loading_script_files_dynamically.htm</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T02:10:13.750", "Id": "521663", "Score": "0", "body": "Thanks, this worked!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T14:36:21.857", "Id": "521675", "Score": "0", "body": "`src` and `async` are defined by the DOM and as such you should not use `setAttribute` which should only be used for undefined attributes. To read or write defined attributes use dot or bracket notation, eg via dot notation `myScript.async = false` or bracket notation `myScript[\"async\"] = false` (same for `src`)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T01:07:20.300", "Id": "264135", "ParentId": "264134", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T00:41:20.780", "Id": "264134", "Score": "0", "Tags": [ "javascript", "html", "sql" ], "Title": "Appending script from within function to header" }
264134
<p>I have invented the fastest string search algorithm. Can someone prove that it is not fastest?</p> <p>I am not considering worst case scenarios.</p> <p>The algorithm can be found here: <a href="https://sourceforge.net/projects/fastest-string-search-algo/files/" rel="nofollow noreferrer">https://sourceforge.net/projects/fastest-string-search-algo/files/</a></p> <pre><code> /* * Choudhary algorithm */ public static int choudharyStringSearchAlgorithm(char[] text, char[] pattern) { int i = 0; int index = 0; int end_index = 0; boolean not_found = false; int text_len = text.length; int pattern_len = pattern.length; int pi_44 = pattern_len - 1; int pi_34 = (3 * pattern_len) / 4; int pi_24 = pattern_len / 2; int pi_14 = pattern_len / 4; int[] skip_table = new int[ASIZE]; // preprocess pattern and fill skip_table for (i = 0; i &lt; pattern_len; i++) { skip_table[pattern[i]] = pattern_len - 1 - i; } // now search for (i = 0; i &lt; text_len; i++) { if ((text_len - i) &lt; pattern_len) { return -1; } if (pattern[pi_44] != text[i + pi_44]) { if (skip_table[(int) (text[i + pi_44])] &gt; 0) { i = i + skip_table[(int) (text[i + pi_44])] - 1; } continue; } if (pattern[0] != text[i]) { continue; } if (pattern[pi_24] != text[i + pi_24]) { continue; } if (pattern[pi_34] != text[i + pi_34]) { continue; } if (pattern[pi_14] != text[i + pi_14]) { continue; } end_index = i + pi_44; not_found = false; for (index = i; index &lt;= end_index; index++) { if (text[index] != pattern[index - i]) { not_found = true; break; } } // end of inner for loop if (not_found == false) { // match is found return i; } } // end of outer for loop return -1; } // end of choudharyStringSearchAlgorithm </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T07:30:48.243", "Id": "521669", "Score": "3", "body": "Looks like you've re-invented Boyer-Moore-Horspool string searching. At least in theory, Boyer-Moore string searching is a bit faster (but honestly, the difference is quite small). Even though it's been invented before, independently re-inventing BMH is no mean feat." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T09:23:01.810", "Id": "521692", "Score": "0", "body": "This algorithm is not Boyer-Moore-Horspool. Please see the algorithm carefully. It compares characters at indices pattern_len - 1, 0, (3 * pattern_len) / 4, pattern_len / 2, and pattern_len / 4 before going for full pattern search." } ]
[ { "body": "<p>If you are searching for long patterns, your algorithm wins most of the time (long strings as far to the end of the text as possible are favored), but if you compare the algorithms on patterns up to 100 characters long (human search), Boyer-Moore smokes everyone and it is not even close.</p>\n<p>Edit: After some testing I have found out that your algorithm is worse on long patterns than if you just implemented the skip table.</p>\n<p>Edit 2: Actually here is the implementation that is consistently faster than every other algorithm in your collection more than 95% of the time:</p>\n<pre><code>public class MyTextSearch implements TextSearch\n{\n @Override\n public int search(\n char[] text,\n char[] pattern\n )\n {\n int[] skip_table = new int[256];\n int patternLength = pattern.length - 1;\n char lastPatternChar = pattern[patternLength];\n\n Arrays.fill(skip_table, patternLength);\n\n for (int i = 0; i &lt; pattern.length; i++)\n {\n skip_table[pattern[i]] = patternLength - i - 1;\n }\n\n for (int i = 0; i &lt; text.length; i++)\n {\n if (i + patternLength &gt;= text.length)\n {\n return -1;\n }\n\n char lastTextChar = text[i + patternLength];\n if (lastPatternChar != lastTextChar)\n {\n i += skip_table[lastTextChar];\n continue;\n }\n\n if (isEqual(text, i, pattern))\n {\n return i;\n }\n }\n\n return -1;\n }\n\n private boolean isEqual(\n char[] text,\n int at,\n char[] pattern\n )\n {\n for (int j = 0; j &lt; pattern.length; j++)\n {\n if (text[at + j] != pattern[j])\n {\n return false;\n }\n }\n\n return true;\n }\n\n @Override\n public String name()\n {\n return &quot;My Text Search&quot;;\n }\n}\n</code></pre>\n<p>I have refactored your code a bit and it is on <a href=\"https://github.com/blazmrak/fastest-string-search\" rel=\"nofollow noreferrer\">https://github.com/blazmrak/fastest-string-search</a> if you are interested.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T19:50:57.243", "Id": "264151", "ParentId": "264137", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T05:59:08.620", "Id": "264137", "Score": "1", "Tags": [ "java", "strings", "search" ], "Title": "Fastest string search algorithm" }
264137
<p>How can I improve efficiency/readability of the following code?</p> <blockquote> <p>It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order. Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.</p> </blockquote> <p><a href="https://projecteuler.net/problem=52" rel="nofollow noreferrer">https://projecteuler.net/problem=52</a></p> <pre class="lang-py prettyprint-override"><code>#! /usr/bin/env python def sameDigits(a, b): return sorted(str(a)) == sorted(str(b)) def main(): found = False i = 2 while not found: x2 = i * 2 x3 = i * 3 x4 = i * 4 x5 = i * 5 x6 = i * 6 if ( sameDigits(i, x2) and sameDigits(i, x3) and sameDigits(i, x4) and sameDigits(i, x5) and sameDigits(i, x6) ): found = True print(i) i += 1 if __name__ == &quot;__main__&quot;: main() </code></pre>
[]
[ { "body": "<h2 id=\"readablilitypythonization-n2fr\">Readablility/pythonization</h2>\n<h3 id=\"pep8-is-your-friend-2zpr\"><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> is your friend</h3>\n<p>Use recommended practices, like using snake_case instead of camelCase for functions and variables.</p>\n<h3 id=\"short-circuit-evaluation-1rzf\">Short-circuit evaluation</h3>\n<p><code>and</code> and <code>or</code> operators evaluate the second argument only if the first can't tell the value - like <code>False</code> for <code>and</code> and <code>True</code> for <code>or</code>. So, if you move all multiplications in a condition, some of them will not be calculated.</p>\n<pre><code>if same_digits(i, x*2) and same_digits(i,x*3) and ...\n</code></pre>\n<h3 id=\"move-repeating-expressions-into-loops-ai3e\">Move repeating expressions into loops</h3>\n<p>Luckily, Python has functions to check several expressions for <code>True</code> at once: <code>any</code> for at least one <code>True</code> and <code>all</code> for all. They work with a short-circuit and can work with any iterable - like generator expression:</p>\n<pre><code>if all(same_digits(i, x*j) for j in range(1,7)):\n</code></pre>\n<h3 id=\"generating-an-infinite-loop-with-itertools.count-s1xc\">Generating an infinite loop with itertools.count()</h3>\n<p>There's a more pythonic way to have something like unlimited range: itertools.count()</p>\n<pre><code>from itertools import count\nfor i in count(2):\n #no need to increment i\n</code></pre>\n<h3 id=\"using-break-instead-of-found-variable-lkii\">Using <code>break</code> instead of <code>found</code> variable</h3>\n<p>Though not a structured feature, it can be useful</p>\n<pre><code>for ...:\n if ...:\n break\n</code></pre>\n<h3 id=\"separate-algorithm-and-input-output-7fev\">Separate algorithm and input-output</h3>\n<p>Return the value from the function, not output it. <code>return</code> statement works just like break, so we can omit it.</p>\n<h3 id=\"all-together-3bgy\">All together</h3>\n<pre><code>from itertools import count\n\ndef same_digits(a, b):\n return sorted(str(a))==sorted(str(b))\n\ndef main():\n for i in count(2):\n if all(same_digits(i, x*j) for j in range(1,7)):\n return i\n\nif __name__ == &quot;__main__&quot;:\n print(main())\n</code></pre>\n<h2 id=\"optimizations-7ftq\">Optimizations</h2>\n<p>I don't think you can change the complexity of an algorithm, but you can avoid unnecessary actions. Profile the code for everything below - Python is a very high-level programming language, and built-in functions can prove faster then better algorithms for small optimizations .</p>\n<h3 id=\"same_digits-y3y9\">same_digits</h3>\n<p>Instead of using str, divide (with divmod) both numbers and count digits in a list - adding for a and subtracting for b. If at some point you reach negative value or lengths are different - return <code>False</code>. Counting digits is slightly faster than sorting, and you avoid dividing after problem is found.</p>\n<h3 id=\"multiples-of-9-z9i2\">Multiples of 9</h3>\n<p>The number with this property should be a very specific. The sum of its digits remains the same after multiplication (because digits are the same). If the number is a multiple of 3, the sum of its digits also will be the multiple of 3, the same for 9. But <span class=\"math-container\">\\$3i\\$</span> is a multiple of 3 and has the same digits, so <span class=\"math-container\">\\$i\\$</span> will be the multiple of 3, <span class=\"math-container\">\\$i=3k\\$</span>. Once again, <span class=\"math-container\">\\$3i=9k\\$</span> will be the multiple of 9, so i will be the multiple of 9. No sense to check not multiples of 9:</p>\n<pre><code>for i in count(9,9):\n</code></pre>\n<h3 id=\"i-should-have-the-same-number-of-digits-yon3\"><code>6*i</code> should have the same number of digits</h3>\n<p>The second idea is that <code>6*i</code> should have the same number of digits with i. You can refactor the loop into nested loops: outer for the number of digits (name it <code>d</code>) and inner for numbers from 100...08 (<code>d</code> digits) to 100..00 (<code>d+1</code> digits)/6, everything bigger will make <code>6*i</code> have <code>d+1</code> digit.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T08:26:23.870", "Id": "264139", "ParentId": "264138", "Score": "3" } }, { "body": "<p><a href=\"https://codereview.stackexchange.com/a/264139/200133\">Pavlo Slavynskyy's answer</a> is excellent!</p>\n<p>Depending how concerned you are with performance, the built-in <a href=\"https://docs.python.org/3/library/collections.html#collections.Counter\" rel=\"nofollow noreferrer\">Counter</a> class might work for counting digits (or it might be really slow; IDK).</p>\n<p>Another small point: The way the <code>same_digits</code> function is being used, the digits of <code>i</code> are being checked six (or seven) times. That should be avoidable...</p>\n<p>You don't strictly need a loop for the task at hand; <a href=\"https://docs.python.org/3/library/functions.html#next\" rel=\"nofollow noreferrer\">next</a> has some gotchas, but should work well here. Taking &quot;no explicit loops&quot; all the way gives us something like</p>\n<pre class=\"lang-py prettyprint-override\"><code>from collections import Counter\nfrom itertools import chain, count\nfrom functools import reduce\nfrom more_itertools import pairwise # or copypast from https://docs.python.org/3/library/itertools.html#itertools-recipes\n\ndef f():\n return next(\n i\n for i\n in chain.from_iterable(range(low, high, 9)\n for (low, high)\n in zip((10**d + 8 for d in count(1)),\n (10**d // 6 for d in count(2))))\n if all(m1 == m2\n for (m1, m2)\n in pairwise(frozenset(Counter(str(i * m)).items())\n for m\n in range(1, 7)))\n )\n</code></pre>\n<p>Frankly that could use some more documentation :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-18T03:39:28.570", "Id": "264155", "ParentId": "264138", "Score": "0" } } ]
{ "AcceptedAnswerId": "264139", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T06:28:46.657", "Id": "264138", "Score": "1", "Tags": [ "python", "python-3.x", "programming-challenge" ], "Title": "Permuted multiples in python" }
264138
<p>Here is some php code which i think is optimized but still want to optimize it more but not sure how to do it.</p> <pre><code>&lt;?php $result = curl_exec($ch); // here i get a json response from a curl. $result = json_decode($result, TRUE); $result = arrangeData($result, $app, $currentSite); $app-&gt;exit($result); function arrangeData($result, $app, $currentSite){ $total = $result['hits']['total']['value']; $final_result = array ( 'data' =&gt; array ( 'customer' =&gt; array ( 'wishlist' =&gt; array ( 'id' =&gt; '', 'items_count' =&gt; $total, 'items' =&gt; getProducts($result,$app,$currentSite), ), ), ), ); return $final_result; } function getProducts($result,$app,$currentSite){ $product_set = array(); $all_products = $result['hits']['hits']; foreach ($all_products as $productdata) { $product_set[] = getArrangedProduct($productdata,$app,$currentSite); } return $product_set; } function getArrangedProduct($productdata,$app,$currentSite){ $productId = $productdata['_id']; $data = $productdata['_source']; $config = getConfigValue($app,$currentSite); $image_label = $data['image'] ? getImageLabel($data['image'],$app,$currentSite) : null; $product = array ( 'id' =&gt; '', 'website' =&gt; '', 'product' =&gt; array( 'id' =&gt; $productId, 'name' =&gt; $data['name'], 'sku' =&gt; $data['sku'], 'url_key' =&gt;$data['url_key']['0'], 'url_suffix' =&gt; '.html', 'display_brand' =&gt; $data['display_brand'], 'manufacturer' =&gt; $data['manufacturer'], 'manufacturer_label' =&gt; $data['manufacturer_value'], 'quantity_in_stock' =&gt; 0, 'trend' =&gt; $data['trend_value'], 'microcategory' =&gt; $data['microcategory'], 'size_label' =&gt; $data['size_value'], 'over_image' =&gt; $data['over_image'], '__typename' =&gt; 'ConfigurableProduct', 'image' =&gt; array ( 'url' =&gt; $config['media_url'].$data['image'], 'label' =&gt; $image_label, 'position' =&gt; '', ), 'gc_image' =&gt; $data['gc_image'], 'whole_preorder' =&gt; $data['whole_preorder_value']=='Yes' ? 1 : 0, 'preorder_shipping_date' =&gt; $data['preorder_shipping_date'], 'variants' =&gt; getVariants($productId,$app,$currentSite) ) ); return $product; } function getImageLabel($image_path, $app, $currentSite){ $result = $app-&gt;getReadDb()-&gt;query(&quot;SELECT `label` FROM `catalog_product_entity_media_gallery_value` WHERE `value_id` = (SELECT `value_id` FROM `catalog_product_entity_media_gallery` WHERE `value` = '&quot;.$image_path.&quot;' LIMIT 1) AND `store_id`= '&quot;.$currentSite.&quot;' LIMIT 1&quot;); $image_data = $result-&gt;fetchAll(); $image_label = $image_data ? $image_data[0]['label'] : false; return $image_label; } function getVariants($productId,$app,$currentSite){ $config = getConfigValue($app,$currentSite); $productInfo = getProductInfo($productId,$app,$currentSite); if(!$productInfo['sku']){ return null; } $special_price = getProductSpecialPrice($productInfo['simple_id'],$app,$currentSite); $rule_price = $productInfo['rule_price'] ? $productInfo['rule_price'] : null; $price = $productInfo['price'] ? $productInfo['price'] : null; $improvised_price = $rule_price ? $rule_price : $special_price; $final_price = $improvised_price ? $improvised_price : $price; $amount_off = $price ? $price - $final_price : null; $percent_off = $price ? (($price - $final_price)*100) / $price : null; $variants = array ( 0 =&gt; array ( 'product' =&gt; array ( 'id' =&gt; $productInfo['simple_id'], 'name' =&gt; $productInfo['name'], 'sku' =&gt; $productInfo['sku'], 'price_range' =&gt; array ( 'minimum_price' =&gt; array ( 'regular_price' =&gt; array ( 'value' =&gt; $price, 'currency' =&gt; $config['currency'], ), 'final_price' =&gt; array ( 'value' =&gt; $final_price, 'currency' =&gt; $config['currency'], ), 'discount' =&gt; array ( 'amount_off' =&gt; $amount_off, 'percent_off' =&gt; round($percent_off), ), ), ), 'special_price' =&gt; $special_price, 'special_to_date' =&gt; NULL, 'special_from_date' =&gt; NULL, ), ), ); return $variants; } function getProductSpecialPrice($productId, $app, $currentSite) { $result = $app-&gt;getReadDb()-&gt;query(&quot;SELECT value FROM `catalog_product_entity_decimal` WHERE `store_id`= '&quot;.$currentSite.&quot;' AND `row_id` = '&quot;.$productId.&quot;' AND `attribute_id` IN (SELECT `attribute_id` FROM `eav_attribute` WHERE `attribute_code` = 'special_price')&quot;); $prices = $result-&gt;fetchAll(); $special_price = $prices ? $prices[0]['value'] : null; return $special_price; } function getConfigValue($app, $currentSite) { $result = $app-&gt;getReadDb()-&gt;query(&quot;SELECT `value` FROM `core_config_data` WHERE `scope` = 'stores' AND `path` = 'currency/options/default' AND `scope_id` = '&quot;.$currentSite.&quot;' union SELECT `value` from `core_config_data` WHERE `path` = 'dollskill_catalog/product/base_media_url' AND `scope` = 'stores' AND `scope_id` = '&quot;.$currentSite.&quot;'&quot;); $getConfigValue = $result-&gt;fetchAll(); $currency = $getConfigValue ? $getConfigValue[0]['value'] : null; $media_url = $getConfigValue ? $getConfigValue[1]['value'] : null; $config_values = array('currency' =&gt; $currency,'media_url' =&gt; $media_url); return $config_values; } function getProductInfo($productId, $app,$currentSite){ $result = $app-&gt;getReadDb()-&gt;query(&quot;SELECT parent.entity_id AS parent_id, simple.entity_id AS simple_id, simple.sku AS simple_sku, cpp.rule_price AS rule_price, cped.value AS price, cpev.value AS simple_name FROM catalog_product_entity AS parent JOIN catalog_product_super_link AS link ON parent.row_id = link.parent_id JOIN catalog_product_entity AS simple ON link.product_id = simple.entity_id LEFT JOIN catalogrule_product_price AS cpp ON cpp.product_id = simple.entity_id AND cpp.website_id = (SELECT `website_id` FROM `store` WHERE `store_id` = '&quot;.$currentSite.&quot;') LEFT JOIN catalog_product_entity_decimal AS cped ON cped.row_id = simple.entity_id AND `attribute_id` IN (SELECT `attribute_id` FROM `eav_attribute` WHERE `attribute_code` IN ('price')) AND cped.store_id= '&quot;.$currentSite.&quot;' LEFT JOIN catalog_product_entity_varchar AS cpev ON cpev.row_id = simple.entity_id AND cpev.store_id = '&quot;.$currentSite.&quot;' WHERE parent.entity_id = '&quot;.$productId.&quot;' LIMIT 1&quot;); $product_info = $result-&gt;fetchAll(); $product_info = array('sku' =&gt; $product_info[0]['simple_sku'],'name' =&gt; $product_info[0]['simple_name'],'rule_price' =&gt; $product_info[0]['rule_price'],'price' =&gt; $product_info[0]['price'],'simple_id' =&gt; $product_info[0]['simple_id']); return $product_info; } </code></pre> <p>Any thoughts it how it can be more optimized ?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T18:15:30.970", "Id": "521686", "Score": "2", "body": "Welcome to CR! What do you mean by \"optimization\" exactly? Is there a performance problem? Do you mean optimizing for readability? Easier to maintain? What does the code do at a high level, anyway? Sample input and output might help. Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T21:44:48.250", "Id": "521697", "Score": "1", "body": "Your question title must not describe the review that you are seeking. Your title should try to uniquely describe what your script does." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T21:51:41.123", "Id": "521698", "Score": "0", "body": "The `exit()` method is not defined in your posted code. The rest of the functional definitions are \"functions\", not \"methods\" because they do not belong to a \"class\". I don't see any prepared statements implemented here -- so even if it is not directly insecure/unstable (and it very well may be), it is certainly not upto the modern standard. There is plenty to critique here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-02T20:30:15.307", "Id": "524697", "Score": "0", "body": "Where do `$currentSite`, `$ch` come from?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T10:19:28.130", "Id": "264143", "Score": "1", "Tags": [ "performance", "php", "memory-optimization" ], "Title": "PHP SCRIPT OPTIMIZATION OF METHODS" }
264143
<p>Below is my attempt at the challenge found <a href="https://github.com/donnemartin/interactive-coding-challenges/blob/master/graphs_trees/graph_build_order/build_order_challenge.ipynb" rel="nofollow noreferrer">here</a>. The challenge is &quot;Find a build order given a list of projects and dependencies.&quot; Already given are the classes Node and Graph (which I can add if anyone needs them to help review my code), and also</p> <pre><code>class Dependency(object): def __init__(self, node_key_before, node_key_after): self.node_key_before = node_key_before self.node_key_after = node_key_after </code></pre> <p>I came up with the below:</p> <pre><code>class BuildOrder(object): def __init__(self, dependencies): self.dependencies = dependencies self.graph = Graph() self._build_graph() def _build_graph(self): for dependency in self.dependencies: self.graph.add_edge(dependency.node_key_before, dependency.node_key_after) def find_build_order(self): processed_nodes = [n for n in self.graph.nodes.values() if n.incoming_edges == 0] if not processed_nodes: return None num_processed = len(processed_nodes) num_nodes = len(self.graph.nodes) while num_processed &lt; num_nodes: for node in [n for n in processed_nodes if n.visit_state == State.unvisited]: node.visit_state = State.visited for neighbor in list(node.adj_nodes.values()): node.remove_neighbor(neighbor) processed_nodes += [n for n in self.graph.nodes.values() if n.incoming_edges == 0 and n.visit_state == State.unvisited] if len(processed_nodes) == num_processed: return None else: num_processed = len(processed_nodes) return processed_nodes </code></pre> <p>When I timed it against the solution given <a href="https://github.com/donnemartin/interactive-coding-challenges/blob/master/graphs_trees/graph_build_order/build_order_solution.ipynb" rel="nofollow noreferrer">here</a>, mine was ~4.5x faster. This was surprising, as throughout completing the challenges in the repo, I usually have approx same runtime as the given solution, or worse.</p> <p>I'd like to know if the above is pythonic, is it readable and how would you improve it? Also, I have deliberately left out comments - which lines in this should probably have a comment to help others understand it? Thanks!</p>
[]
[ { "body": "<p><strong>&quot;Pythonicness&quot;</strong></p>\n<p>The code is easy to read and understandable - a good start.</p>\n<ol>\n<li>Remove <code>(object)</code> when declaring classes, it is not needed :)</li>\n<li>Use type annotations!</li>\n</ol>\n<pre><code>from typing import List\n\ndef __init__(self, node_key_before: Node, node_key_after: Node):\ndef __init__(self, dependencies: List[Dependency]):\ndef find_build_order(self) -&gt; List[Node]:\n</code></pre>\n<ol start=\"3\">\n<li>The statement:</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>if len(processed_nodes) == num_processed:\n return None\nelse:\n num_processed = len(processed_nodes)\n</code></pre>\n<p>Can be rewritten as:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if len(processed_nodes) == num_processed:\n return None\nnum_processed = len(processed_nodes)\n</code></pre>\n<p>That is it for this section (for now - I might edit later).</p>\n<p><strong>Algorithm and runtime</strong></p>\n<p>Let's talk complexity. This algorithm runs in <code>O(V * V + E)</code>, it can be seen from the example of the following graph:</p>\n<pre><code>a -&gt; b -&gt; c -&gt; d -&gt; ... (V times) \n</code></pre>\n<p>You will iterate over the <code>V</code> nodes and for each of them you will search (twice in fact) over all the <code>V</code> nodes. The reason we add <code>+ E</code> is since you will also delete all edges of the graph.</p>\n<p>Now the correct algorithm can do this in <code>O(V + E)</code>, the analysis a just a little bit more complex but you can do it yourself.</p>\n<p>Why is my algorithm faster in tests than?<br />\nI cannot answer for sure but 2 explanations are possible:</p>\n<ol>\n<li><p>The graph in the test has many many edges and <code>E</code> is close to <code>V * V</code>, therefore the fact that the time complexity is worst is not relevant in practice.</p>\n</li>\n<li><p>After a quick look at the code in the answer you can see it has more functions and more dictionaries, this is probably the reason your code is faster in with smaller graphs, also cache probably plays a factor here.</p>\n</li>\n</ol>\n<hr />\n<p>I might add some more stuff. This is it for now.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T17:49:59.220", "Id": "521684", "Score": "0", "body": "Am I right in thinking that I can remove the 'else' since the 'if' results in a return statement? I have seen a lot of code that just does 'if' several times, without returns in the bodies of the 'if's. I guess I am asking, is 'else' (and even 'elif') actually necessary ever?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T17:56:48.170", "Id": "521685", "Score": "0", "body": "Would you be able to give an example of how to do the type annotations please?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T18:49:31.390", "Id": "521693", "Score": "0", "body": "Yes you are right, this is also point 3 in the first section. I will edit to add a type annotation, no problem." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T16:54:46.850", "Id": "264148", "ParentId": "264145", "Score": "1" } }, { "body": "<p>I decided to implement it following Kahn's algorithm found <a href=\"https://en.wikipedia.org/wiki/Topological_sorting#Algorithms\" rel=\"nofollow noreferrer\">here</a>, which is\n0(V + E). Below is my direct translation into python, except for the final if statement, where I just compare length of L and the number of nodes in the graph rather than iterating thru the nodes and counting incoming edges.</p>\n<pre><code>def find_build_order(self):\n L = []\n S = {n for n in self.graph.nodes.values() if n.incoming_edges == 0}\n\n while S:\n n = S.pop()\n L.append(n)\n for m in list(n.adj_nodes.values()):\n n.remove_neighbor(m)\n if m.incoming_edges == 0:\n S.add(m)\n \n if len(L) != len(self.graph.nodes):\n return None\n return L\n</code></pre>\n<p>This works, but again I am puzzled on the runtime. The times are laid out below.</p>\n<p>Kahn's algo: 3.69 µs ± 42 ns per loop</p>\n<p><a href=\"https://github.com/donnemartin/interactive-coding-challenges/blob/master/graphs_trees/graph_build_order/build_order_solution.ipynb\" rel=\"nofollow noreferrer\">Given solution</a>: 4.36 µs ± 78.5 ns per loop</p>\n<p>Algo in my OP (with the minor changes suggested): 986 ns ± 11.2 ns per loop</p>\n<p>Kahn's algo seems a lot more efficient than my first attempt, and it is compact unlike the given solution. Maybe I have not implemented it correctly.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T18:40:23.337", "Id": "264150", "ParentId": "264145", "Score": "0" } } ]
{ "AcceptedAnswerId": "264148", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T11:03:54.547", "Id": "264145", "Score": "0", "Tags": [ "python-3.x", "graph" ], "Title": "Build order from a dependency graph (Python)" }
264145
<p>A simple implementation of the Observer pattern in rust. The Observable constructor (<code>::new</code>) is called with a subscription function which will be called every time an observer subscribes.</p> <p>The subscription function must return a cleanup function which is defined by the using code.</p> <p>An observer subscribed to the Observable either by:</p> <ul> <li>passing a simple <code>next</code> function</li> <li>providing an <code>Observer</code> which provide a <code>next</code>, <code>complete</code> and <code>error</code> function</li> <li>providing a <code>FullObserver</code> which, in addition to the aforementioned function, provide also a start function which allows the Observer to be called before the processing start.</li> </ul> <pre class="lang-rust prettyprint-override"><code>use std::error::Error; use std::rc::Rc; struct Observer&lt;T, E&gt; { next: Box&lt;dyn Fn(T)&gt;, complete: Box&lt;dyn Fn()&gt;, error: Box&lt;dyn Fn(E)&gt;, } struct FullObserver&lt;T, E&gt; { start: Box&lt;dyn Fn(&amp;mut Subscription)&gt;, next: Box&lt;dyn Fn(T)&gt;, complete: Box&lt;dyn Fn()&gt;, error: Box&lt;dyn Fn(E)&gt;, } struct Observable&lt;T, E&gt; { subscription_fn: Rc&lt;dyn Fn(&amp;FullObserver&lt;T, E&gt;) -&gt; Box&lt;dyn Fn()&gt;&gt;, } struct Subscription { cleanup: Option&lt;Box&lt;dyn Fn()&gt;&gt;, closed: bool, } impl Subscription { fn new&lt;T, E, F: Fn() + 'static&gt;( observer: FullObserver&lt;T, E&gt;, subscription_fn: Rc&lt;dyn Fn(&amp;FullObserver&lt;T, E&gt;) -&gt; F&gt;, ) -&gt; Subscription { let mut subscription = Subscription { cleanup: None, closed: false, }; (observer.start)(&amp;mut subscription); if !subscription.closed { let cleanup = Box::new((subscription_fn)(&amp;observer)); subscription.cleanup = Some(cleanup); } return subscription; } fn unsubscribe(&amp;mut self) { if let Some(cleanup) = &amp;self.cleanup { (cleanup)(); } self.closed = true; } } impl&lt;T, E&gt; Observable&lt;T, E&gt; { fn new&lt;F: Fn() + 'static&gt;( subscription_fn: impl (Fn(&amp;FullObserver&lt;T, E&gt;) -&gt; F) + 'static, ) -&gt; Self { Observable { subscription_fn: Rc::new(move |observer| Box::new(subscription_fn(observer))), } } fn subscribe(&amp;self, next: impl Fn(T) + 'static) -&gt; Subscription { Subscription::new( FullObserver { start: Box::new(|_s| {}), next: Box::new(next), complete: Box::new(|| {}), error: Box::new(|_err| {}), }, self.subscription_fn.clone(), ) } fn subscribe_observer(&amp;self, observer: Observer&lt;T, E&gt;) -&gt; Subscription { Subscription::new( FullObserver { start: Box::new(|_s| {}), next: observer.next, complete: observer.complete, error: observer.error, }, self.subscription_fn.clone(), ) } fn subscribe_full_observer(&amp;self, observer: FullObserver&lt;T, E&gt;) -&gt; Subscription { Subscription::new(observer, self.subscription_fn.clone()) } } fn main() { let observable = Observable::&lt;i32, Box&lt;dyn Error&gt;&gt;::new(|observer| { (observer.next)(42); (observer.next)(666); (observer.complete)(); return || { println!(&quot;cleanup&quot;); }; }); let mut subscription = observable.subscribe(|value| { println!(&quot;next {}&quot;, value); }); subscription.unsubscribe(); let some_closure = &quot;yo!&quot;; observable.subscribe_full_observer(FullObserver { start: Box::new(|_subscription| println!(&quot;start&quot;)), next: Box::new(|value| println!(&quot;next {}&quot;, value)), complete: Box::new(move || println!(&quot;complete {}&quot;, some_closure)), error: Box::new(|error| eprintln!(&quot;error {:?}&quot;, error)), }); } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>Firstly, this doesn't appear to follow the Observer pattern. Allow me to quote Wikipedia:</p>\n<blockquote>\n<p>The observer pattern is a software design pattern in which an object,\nnamed the subject, maintains a list of its dependents, called\nobservers, and notifies them automatically of any state changes,\nusually by calling one of their methods.</p>\n</blockquote>\n<p>Your code lacks a list of dependents or observers which are notified in tandem whenever there is a state change. Instead, every call to subscribe invokes the &quot;subscription function&quot; which produces an independent stream of events.</p>\n<p>Secondly, patterns involving invoking callbacks are a poor fit for Rust. They don't interact well with lifetimes. To see this, consider the basic callback function that you have:</p>\n<pre><code>let mut subscription = observable.subscribe(|value| {\n println!(&quot;next {}&quot;, value);\n});\n</code></pre>\n<p>Here, you print something. But you can't actually do anything useful. The callback type is <code>Fn(T) + 'static</code> So this closure cannot contain any references to anything and cannot mutate any state. The only way to interact with the rest of the system would be to give the closure a <code>Rc&lt;RefCell&lt;_&gt;&gt;</code> (or equivalent) that it could use to get a mutable reference to the rest of the system.</p>\n<p>We can also see it in your subscription function:</p>\n<pre><code>let observable = Observable::&lt;i32, Box&lt;dyn Error&gt;&gt;::new(|observer| {\n (observer.next)(42);\n (observer.next)(666);\n (observer.complete)();\n return || {\n println!(&quot;cleanup&quot;);\n };\n});\n</code></pre>\n<p>Here, you generate a bunch of values and finish immediately. And that's pretty much the only thing you can do. Because the observer is borrowed, you can't keep it around to call later in response to any sort of event.</p>\n<p>What should you do instead? That depends on the situation. But you should pretty much always be able to better a rust friendly pattern which is a better fit.</p>\n<p>In general, I find that using <code>Rc</code>, <code>Box</code>, and <code>dyn</code> are signs that are trying to write code in a OO style which doesn't fit Rust well. Of course, you can do that if you really want, but Rust will give you a lot of friction. Furthermore, you won't notice this friction just printing out some test outputs. Try actually solving real problems and you'll see what I mean.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-22T05:22:08.003", "Id": "521899", "Score": "0", "body": "Thanks a lot for your review! You say the callback can't do anything useful but (1) it's a lambda that can still access its environment through closures right? and (2) the value provided can be mutable. You say the observer is borrowed, but I though that it would depend on T (wether a reference, ref mut or a value). Finally, my understanding of Box and Rc are that they precisely allow you to do thing like that, it's even describe in the [rust book](https://doc.rust-lang.org/book/ch19-05-advanced-functions-and-closures.html#returning-closures). Thanks again!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-22T07:05:39.957", "Id": "521907", "Score": "0", "body": "And you are right, this does not fully implement the Observer pattern. My intention is to implement a Subject based on the Observable. The subscription function is used to append the observer to a list and the cleanup function to remove it from the list. So this is just a building block of the Observer pattern." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-24T22:12:26.747", "Id": "522103", "Score": "1", "body": "@LukeSkywalker, (1) no, it can't access the environment directly because that would involve holding a reference to the environment, which is disallowed because the type is `'static`. It will only be able to access things either moved into the closure or things through a `Rc` or similiar. 2) True. 3) Yes, Box and Rc let you do such things. But needing to do such things means you are running afoul of the borrow checker and thus probably not writing very Rusty code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-24T22:23:07.147", "Id": "522104", "Score": "1", "body": "The observer is borrowed because the type is `&FullObserver<T, E>`, the & makes it borrowed regardless of the type of T. I believe you'll find it impossible to implement a full observer pattern on this building block, because the lifetimes you have going won't allow it. Probably, the best way to really understand that is to try anyways." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T18:23:41.937", "Id": "264252", "ParentId": "264147", "Score": "2" } }, { "body": "<p>@Winston Ewert already points out several problems with your code, I however, would like to give you a naive implementation that works with asynchronous rust:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>use std::ops::Deref;\nuse std::pin::Pin;\nuse std::future::Future;\nuse std::task::{Waker, Context, Poll};\nuse std::sync::{Arc, RwLock, RwLockReadGuard};\nuse std::marker::PhantomData;\nuse std::num::Wrapping;\n\n/// Thread-safe observable, intended to be implemented on `&amp;self`\ntrait Observable&lt;'a&gt; {\n type Item;\n /// (item, epoch)\n type Ref: Deref&lt;Target = (Self::Item, usize)&gt; + 'a;\n\n /// subscriber has to be renewed after the value is updated\n fn subscribe(self, waker: Waker);\n fn update(self, item: Self::Item);\n fn get_observed(self) -&gt; Self::Ref;\n fn get_epoch(self) -&gt; usize;\n}\n\nstruct ObservableFuture&lt;'a, T: Observable&lt;'a&gt;&gt; {\n observable: T,\n epoch: usize,\n phantom: PhantomData&lt;&amp;'a ()&gt;,\n}\nimpl&lt;'a, T: Copy + Observable&lt;'a&gt;&gt; ObservableFuture&lt;'a, T&gt; {\n fn new(observable: T) -&gt; Self {\n Self {\n observable,\n epoch: observable.get_epoch(),\n phantom: PhantomData,\n }\n }\n}\nimpl&lt;'a, T: Copy + Observable&lt;'a&gt;&gt; Future for ObservableFuture&lt;'a, T&gt; {\n type Output = T::Ref;\n \n fn poll(self: Pin&lt;&amp;mut Self&gt;, cx: &amp;mut Context&lt;'_&gt;) -&gt; Poll&lt;Self::Output&gt; {\n let observable = &amp;self.observable;\n \n if self.epoch != observable.get_epoch() {\n Poll::Ready(observable.get_observed())\n } else {\n observable.subscribe(cx.waker().clone());\n Poll::Pending\n }\n }\n}\nfn wait_for_update&lt;'a, T: Copy + Observable&lt;'a&gt;&gt;(observable: T) -&gt; ObservableFuture&lt;'a, T&gt; {\n ObservableFuture::new(observable)\n}\n\nstruct Observed&lt;T&gt; {\n // If T is a primitive, then you can replace RwLock\n // with Atomic.\n // Or if T is `Sync`, then you may remove `RwLock`.\n // However, you still have to think of a way where\n // epoch can be updated atomically with T.\n item: RwLock&lt;(T, usize)&gt;,\n // You can consider replacing Vec with other\n // container with built-in concurrency support.\n // such as crossbeam::queue::SegQueue\n observers: RwLock&lt;Vec&lt;Waker&gt;&gt;,\n}\nimpl&lt;T&gt; Observed&lt;T&gt; {\n fn new(item: T) -&gt; Self {\n Self {\n item: RwLock::new((item, 0)),\n observers: RwLock::new(Vec::new()),\n }\n }\n}\nimpl&lt;'a, T: 'a&gt; Observable&lt;'a&gt; for &amp;'a Observed&lt;T&gt; {\n type Item = T;\n type Ref = RwLockReadGuard&lt;'a, (T, usize)&gt;;\n\n fn subscribe(self, waker: Waker) {\n self.observers.write().unwrap().push(waker);\n }\n\n fn update(self, item: Self::Item) {\n let epoch = Wrapping(self.get_epoch());\n let one = Wrapping(1);\n *self.item.write().unwrap() = (item, (epoch + one).0);\n let observers = std::mem::replace(&amp;mut *self.observers.write().unwrap(), Vec::new());\n for observer in observers {\n observer.wake_by_ref();\n }\n }\n\n fn get_observed(self) -&gt; Self::Ref {\n self.item.read().unwrap()\n }\n \n fn get_epoch(self) -&gt; usize {\n self.item.read().unwrap().1\n }\n}\n\n#[tokio::main]\nasync fn main() {\n use tokio::time::{sleep, Duration};\n \n let observed = Arc::new(Observed::new(Vec::&lt;i32&gt;::new()));\n \n let observed_cloned = observed.clone();\n let handle = tokio::spawn(async move {\n let observed = observed_cloned;\n \n println!(&quot;{:#?}&quot;, *wait_for_update(&amp; *observed).await);\n });\n\n let observed_cloned = observed.clone();\n let handle2 = tokio::spawn(async move {\n let observed = observed_cloned;\n \n println!(&quot;{:#?}&quot;, *wait_for_update(&amp; *observed).await);\n });\n\n // sleep for 1s to make sure wait_for_update is executed\n sleep(Duration::from_millis(1000)).await;\n observed.update(vec![1, 2, 3, 4]);\n \n handle.await.unwrap();\n handle2.await.unwrap();\n}\n</code></pre>\n<p>The <code>Observable</code> trait is designed to be thread-safe and work with <code>async</code>, requiring to be implemented on copyable reference (immutable reference).</p>\n<p>The <code>Observed</code> struct provides a naive sample implementation which stores the list of observers in a <code>Rwlock&lt;Vec&gt;</code>, while a better implementation could use <code>crossbeam::queue::SegQueue</code>.</p>\n<p>It also uses <code>RwLock</code> for safely updating the data, but for primitive you can use <code>Atomic</code> and for <code>T</code> that is already thread safe, you can remove <code>RwLock</code> completely, but you still need to account for updating <code>ecpoch</code> atomically with the data.</p>\n<p>I have tested my code on <a href=\"https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=df31851609c2808ba741c5ba403438a7\" rel=\"nofollow noreferrer\">rust playground</a> and it worked as expected for two observers, though I haven’t tested it for more observers.</p>\n<p>Edit:</p>\n<p>If you are running in single-thread only, then you can simply remove the <code>RwLock</code> and there will be no synchronization overhead.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-22T07:03:07.887", "Id": "521906", "Score": "0", "body": "Thanks for your review! It's an interesting implementation. However my use case is not multi-threaded but associated to an event loop and the additional complexity and, probably, execution cost are not worth it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-22T10:14:52.000", "Id": "521917", "Score": "0", "body": "@LukeSkywalker If you are using an event loop, then you can definitly use my implementation, as it supports `async` wakeup upon update to the value." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-22T10:15:58.797", "Id": "521918", "Score": "0", "body": "@LukeSkywalker The `RwLock` I used in `Observed` can be easily removed if it is used inside a single-thread program." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-22T05:33:13.483", "Id": "264266", "ParentId": "264147", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T15:34:43.197", "Id": "264147", "Score": "1", "Tags": [ "reinventing-the-wheel", "rust", "observer-pattern" ], "Title": "Observer pattern in Rust" }
264147
<p>So I decided to implement a basic event system in JavaScript.</p> <p>My goal was to support the following functions:</p> <p><code>on</code> - allows the user to register a handler on the event system that fires until it's removed.</p> <p><code>once</code> - same as above, but only fires the first time, then removes itself.</p> <p><code>emit</code> - creates an event and fires all relevant handlers.</p> <p><code>delete</code> - deletes the specified handler from from the system.</p> <pre class="lang-js prettyprint-override"><code>class HandlerSet extends Map { set(handler, once = false) { if (typeof handler !== 'function') return super.set(handler, !once ? handler : (...args) =&gt; { handler(...args) this.delete(handler) }) } forEach(...args) { [...this.values()].forEach(...args) } } class EventSystem extends Map { set(type) { return super.set(type, new HandlerSet()) } on(type, handler, once = false) { (this.get(type) ?? this.set(type).get(type)).set(handler, once) } once(type, handler) { this.on(type, handler, true) } emit(type, ...args) { this.get(type)?.forEach(handler =&gt; handler(...args)) } delete(type, handler) { let set = this.get(type) if (set?.delete(handler) &amp;&amp; set?.size === 0) { super.delete(type) } } } </code></pre> <p>I'm curious to see what peoples thoughts are on this implementation.</p> <p>As far as I'm aware, it should be quite robust from a type safety standpoint, as well as quite predictable from a lifecycle standpoint.</p> <p>If anyone can find any bugs in this, or suggest improvements, I'd like to hear from you!</p>
[]
[ { "body": "<p>I couldn't find any obvious bugs, so that's good!</p>\n<p>For improvements, I have a few comments. It's mostly about readability, and of course it's just my subjective experience when I read the code:</p>\n<ul>\n<li>If handler is not a function, you should throw an error. It's obviously a mistake.</li>\n<li>When extending base classes you should not rewrite the extended method signatures. This would be obvious in typescript, where you would get an error message. The reason is that it would be legal to assign EventSystem to a Map, but that would not work since EventSystem is not a Map (due to the rewrite).</li>\n<li>The way EventSystem is implemented it exposes many more methods than it needs to. Why expose set? Also, it will expose all the other methods on Map, which you may or may not want.</li>\n<li>In HandlerSet, you seem to want a data structure that mimics a Set. The Map is an implementation detail, and it works quite well. However, when you add an item to a regular set the method is called &quot;add&quot;. It's just a minor point, but it's small things like this that happens when you extend a base class that doesn't <em>quite</em> fit.</li>\n<li>In the method &quot;on&quot; you have something that reads a bit like &quot;get set get set&quot; with some parens that needs to be mentally arranged. It's harder to read than it needs to be, at least in my opinion. I would split it onto two lines to make it completely obvious.</li>\n<li>HandlerSet.forEach seems a bit strange to me. You've extended Map, so why not use the Map methods directly from EventSystem? Or if not, why not make a function that actually calls the handlers? Extending Map in HandlerSet is completely pointless since you don't use a single method from Map (except delete). The Map should be an implementation detail imo.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-18T22:16:59.990", "Id": "521720", "Score": "0", "body": "Good point on passing a non function to the set, and the fact it should throw an error. HandlerSet originally extended a set, however I needed a way to find the handler function within the set even if it was wrapped by a cleanup function as seen when the bool \"once\" is passed to the set function. When it is wrapped, it can no longer be found using the original function. As far as overriding functions and changing the parameters, as far as I'm aware, this isn't an error in JavaScript, rather I'm just embracing a language feature." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-18T22:23:19.410", "Id": "521721", "Score": "0", "body": "I also agree the 'on' function implementation should be adjusted to be a bit more readable. And I also do agree with changing the override of forEach to instead call the functions directly, thanks for the comprehensive review!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T06:29:01.547", "Id": "521726", "Score": "0", "body": "Using a map for handlerset is completely fine, it was just the extending I didn't like. You can call it embracing a language feature if you want, but just because javascript allows you to do all sorts of crazy things doesn't mean it's a good idea. I've outlined some problems, but it's up to you to decide if they're important or not. See also \"liskov substitution\" principle if you want to know more" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-18T20:05:49.607", "Id": "264163", "ParentId": "264152", "Score": "2" } }, { "body": "<h2 id=\"events-or-messages-mt1f\">Events or messages?</h2>\n<p>Is this a messaging system or an event system. As I see it, it is a messaging system.</p>\n<p>Assuming this is for the browser you may prefer the provided <a href=\"https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/events/Event\" rel=\"nofollow noreferrer\" title=\"MDN Web API's events Event\">events.Event</a> API which will use the event stack. <strong>NOTE</strong> check comparability before using.</p>\n<h2 id=\"review-9evd\">Review</h2>\n<p>A general style code review. Code style is subjective and thus these points are just suggestions</p>\n<ul>\n<li><p>When possible use <code>instanceof</code> rather than <code>typeof</code> as the former has considerably less overhead</p>\n<p>For example</p>\n<pre><code>if (typeof handler === 'function') {\n</code></pre>\n<p>can be</p>\n<pre><code>if (handler instanceof Function) {\n</code></pre>\n</li>\n<li><p>Do not silence errors (oh I mean... <em>&quot;NEVER!! silence errors&quot;</em>). The above point (vetting the callback) will silence code that is passing the wrong type of object. Silencing means that an error can go unnoticed during development.</p>\n<p>Either throw when vetting or let JS throw naturally.</p>\n</li>\n<li><p>Always delimit code blocks with <code>{}</code> Eg <code>if (foo) return</code> should be <code>if (foo) { return }</code></p>\n</li>\n<li><p>Use semicolons!</p>\n</li>\n<li><p>Use constants whenever possible. You have <code>let set = this.get(type)</code> should be <code>const set = ...</code></p>\n</li>\n<li><p>Avoid redundant clauses</p>\n<p>You have the statement</p>\n<blockquote>\n<pre><code>if (set?.delete(handler) &amp;&amp; set?.size === 0) {\n</code></pre>\n</blockquote>\n<p>The second <code>?.</code> is redundant. If the first clause is true then <code>set</code> must not be <code>undefined</code>.</p>\n<p>Also use logical not <code>!</code> rather than <code>=== 0</code>. <code>Map.size</code> will only ever be a <code>Number</code> thus <code>!set.size</code> will always be <code>true</code> for <code>0</code></p>\n<pre><code>if (set?.delete(handler) &amp;&amp; !set.size) {\n</code></pre>\n</li>\n<li><p>Avoid intermediate calls, especially when using rest parameters as this forces array creation overhead just to pass arguments between functions.</p>\n<p>You have</p>\n<blockquote>\n<pre><code>class HandlerSet extends Map {\n forEach(...args) {\n [...this.values()].forEach(...args);\n }\n\nclass EventSystem extends Map {\n emit(type, ...args) {\n this.get(type)?.forEach(handler =&gt; handler(...args));\n }\n</code></pre>\n</blockquote>\n<p>Can be...</p>\n<pre><code>emit(type, ...args) {\n const handlers = this.get(type);\n if (handlers) {\n for (const handler of handlers.values()) { handler(...args) }\n }\n}\n</code></pre>\n<p>...reducing memory and iteration overheads. Also removes the need for <code>HandlerSet.forEach</code></p>\n</li>\n<li><p>Be careful with naming.</p>\n<p>Avoid naming variables for their type. Name variables for what they represent, not what they are.</p>\n<p>I find your name selection is obfuscating the functionality of your code. The main problem is that the concepts of a listener and an event have been blurred. An event has a name eg a load event would be called <code>&quot;load&quot;</code>. Each named event has a set of listeners / callbacks (functions)</p>\n<p>Notes on some of the names you used</p>\n<ul>\n<li><p><code>handler</code> Conventional JS uses listeners rather than handlers, however in this case they are much more like callbacks, <code>listener</code> or <code>callback</code> would be more appropreate (NOTE <code>callback</code> as one word not <code>callBack</code>).</p>\n</li>\n<li><p><code>HandlerSet</code> is extending a <code>Map</code>. Names should avoid including type descriptions. Adding a name of a similar type is just confusing.</p>\n</li>\n<li><p><code>EventSystem</code> is it really a system? Don't add superfluous content to names. Maybe <code>GlobalEvents</code> would be better?</p>\n</li>\n<li><p><code>EventSystem.on</code> ambiguous name, maybe <code>addListener</code>, <code>addCallback</code>, or even just <code>addCall</code>?</p>\n</li>\n<li><p><code>EventSystem.once</code> Similar to <code>on</code>. Personally the <code>once</code> functionality is inappropriate or can be handled using options when adding a listener.</p>\n</li>\n<li><p><code>EventSystem.emit</code> JS convention is that events are fired not emitted thus maybe <code>fire</code> would be better</p>\n</li>\n<li><p><code>EventSystem.delete</code> Delete what, an event or a listener? Names should never be ambiguous.</p>\n</li>\n</ul>\n</li>\n</ul>\n<h2 id=\"rewrite.no-upge\">Rewrite?... No.</h2>\n<p>I did rewrite your code but I could not reconcile its usefulness due to ambiguity of (guessed) usage cases.</p>\n<p>Thus what follows is an Example and is just a modification of code I use to add a messaging.</p>\n<h2 id=\"example-zvvo\">Example</h2>\n<p><strong>Note</strong> the example code has been parsed but is untested.</p>\n<p><strong>Note</strong> the <code>Map</code> named <code>events</code> is closed over and thus protected from miss use.</p>\n<p><strong>Note</strong> This does not check if the listener is a function. Doing so can hide/silence bad code. If the cb is not a function it will throw in <code>fireEvent</code></p>\n<pre><code>// Naming: cb and cbs short for &quot;callback&quot; (a function) and &quot;callbacks&quot; (array of callback objects)\nfunction Events(owner = {}) {\n const events = new Map(); // named arrays of listener objects\n return Object.assign(owner, {\n addListener(name, cb, options = {}) {\n var cbs;\n ((events.get(name) ?? (events.set(name, cbs = []), cbs)).push({cb, options}));\n },\n removeEvent(name) { events.delete(name) },\n removeListener(name, cb) {\n const cbs = events.get(name);\n if (cbs?.length) {\n const idx = cbs.findIdx(listener =&gt; listener.cb === cb);\n idx &gt; -1 &amp;&amp; cbs.splice(idx, 1);\n }\n },\n fireEvent(name, data = {}) {\n var i = 0;\n const cbs = events.get(name);\n if (cbs?.length) { \n for (const {cb, options} of cbs) { \n options.once &amp;&amp; cbs.splice(i--, 1);\n cb.bind(owner)({type: name, target: owner, ...data});\n i++;\n } \n }\n },\n });\n}\nexport {Events};\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T17:54:45.627", "Id": "264188", "ParentId": "264152", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-17T23:11:00.220", "Id": "264152", "Score": "3", "Tags": [ "javascript", "event-handling" ], "Title": "Javascript (ES11) Event System implementation" }
264152
<p>I have a comparison function for comparing two points in 2 (or more) dimensions based on the angle of each point in standard polar coordinates. In other words, a point <code>a</code> should compare less than a point <code>b</code> if the angle through the origin from the +x axis to <code>a</code> is less than the corresponding angle for <code>b</code>. For the origin, the normalized angle is <code>0</code> BUT for sanity it compares equal with any point.</p> <p>This can be done pretty trivially using the <code>atan2</code> function, which has built in handling for different quadrants and simply returns a normalized angle (between 0 inclusive and 2 pi exclusive) for any given point besides the origin. Unfortunately, trig is slow so it is better to compare <code>b.x*a.y &lt;=&gt; a.x*b.y</code>. This is also nice since it plays nicer with integers than trig does. This comparison can be derived from the fact that tan is strictly increasing on the interval 0 to pi/2. However, it only works if the points <code>a</code> and <code>b</code> are in the same quadrant, so we need to do some preprocessing before we can apply it.</p> <p>This is where my dilemma with my current code comes in. I originally had a fairly long and hard to read forest of <code>if</code> statements that handled all cases where <code>a</code> and <code>b</code> were not in the same quadrant, but I replaced it with the code you see here. I first get the &quot;region number&quot; for each point <code>a</code> and <code>b</code>, and then use the <code>b.x*a.y &lt;=&gt; a.x*b.y</code> comparison if necessary. I define the region number as <code>0</code> for the origin and <code>1-8</code> for the +x axis through quadrant IV in counterclockwise order. Namely, <code>2</code> is quadrant I, <code>3</code> is the +y axis, <code>4</code> is quadrant II, <code>5</code> is the -x axis, <code>6</code> is quadrant III, and <code>7</code> is the -y axis.</p> <p>Thus I can compare two points by</p> <ul> <li>getting the region number for each</li> <li>if either is <code>0</code>, return <code>0</code> since one of the points is the origin so they should compare equal since</li> <li>otherwise, if their region numbers are not the same, return <code>-1</code> if the region number for <code>a</code> is smaller and <code>1</code> if the region number for <code>b</code> is smaller</li> <li>otherwise, the region numbers for <code>a</code> and <code>b</code> are the same. If the region number for <code>a</code> is odd, return <code>0</code> because the points are on the same axis in the same direction (+x, +y, -x, or -y)</li> <li>otherwise, <code>a</code> and <code>b</code> are both in the interior of the same quadrant, so we can use the <code>b.x*a.y &lt;=&gt; a.x*b.y</code> comparison</li> </ul> <p>Finding the region number for each point does a bit of redundant work in some cases, but this is probably something the compiler can optimize away. I'm not at the point where I need to profile and optimize this, though I do want to avoid floating point computations.</p> <p>Here is the code for the comparison function:</p> <pre><code>/// Return an identifier for the region of the xy plane containing a point /// /// Returns 0 for origin or 1 to 8 for the +/- axis and quadrants in /// counterclockwise order starting from the +x axis (ie 1 for +x axis, /// 2 for quadrant I, etc, and 8 for quadrant IV) static inline int find_x_y_region(const int64_t *a){ if(a[0] == 0){// a is on the y axis if(a[1] == 0){// a is the origin return 0; } return a[1] &gt; 0 ? 3 : 7;// +y axis and -y axis respectively }else if(a[1] == 0){// a is on the x axis (but not the origin) return a[0] &gt; 0 ? 1 : 5;// +x axis and -x axis respectively }else if(a[1] &gt; 0){// a is in the upper half plane return a[0] &gt; 0 ? 2 : 4;// quadrant I and quadrant II respectively }// otherwise a is in the lower half plane return a[0] &gt; 0 ? 8 : 6;// quadrant IV and quadrant III respectively } static inline int cmp_x_y(const void *_a, const void *_b){ const int64_t *a = _a, *b = _b; // consider the points a and b projected into the xy plane (ie ignore their z components) // we want to find which point, a or b, has a smaller angle in its standard polar representation // return -1 if a has a smaller angle, 1 if b does, 0 if they have the same angle // we do not need to do trig for this, but there are a lot of cases // for a fixed z, all xy points have a fixed radius, so comparison of points at the same z // can be done instantly with one coordinate. However, when a and b have different z coordinates we // need to work harder. int a_region = find_x_y_region(a), b_region = find_x_y_region(b); if(a_region == 0 || b_region == 0){ return 0; }else if(a_region &lt; b_region){ return -1; }else if(a_region &gt; b_region){ return 1; }else if(a_region &amp; 1){// both regions are the same, if they are odd both points are on the same axis (+/- x/y) return 0; }// otherwise both points are in the same quadrant int64_t ord = b[0]*a[1] - a[0]*b[1]; if(ord &lt; 0){ return -1; }else if(ord == 0){ return 0; } return 1; } </code></pre> <p>Factoring out <code>find_x_y_region</code> helped a lot, but can I simplify this comparison function even further? Also, should I worry about dealing with overflow in the computation of <code>ord</code>? As hinted at in the comments, I'm going to use this to make a KD tree out of points on the surface of a sphere, so I'm already requiring the square of any coordinate be representable as an <code>int64_t</code> and for such points overflow is not a concern. I could coalesce a couple of branches in the comparison function to ternary operators which would shorten it by 4 lines, but that wouldn't really increase readability.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-18T03:46:33.157", "Id": "521699", "Score": "3", "body": "I'm not sharp enough with C to give a proper response, but a lot of comparison consumers wouldn't require you to return strictly {-1 | 0 | 1}; you could save yourself some `if` statements by just returning signed-integer differences in many of these cases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-18T18:32:19.083", "Id": "521715", "Score": "0", "body": "\\$\\tan\\$ is strictly increasing in \\$(-\\dfrac{\\pi}{2}, \\dfrac{\\pi}{2})\\$. You are surely do at least twice much work as necessary. Comparing half-planes seems to be good enough." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T01:37:33.037", "Id": "521723", "Score": "0", "body": "@vnp you are right, tan is continuous and strictly increasing in the right and left half planes. But I still need to split up the right half plane into quadrants since I want to have the branch point at 0 radians and not -pi/2 or something else. On the top/bottom half planes tan is discontinuous and jumps from +inf to -inf unfortunately. I could combine quadrant II, the -x axis, and quadrant III into one region though" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T05:34:35.973", "Id": "521725", "Score": "2", "body": "I think you've misread me (or I was not clear). If both vectors are in the upper half plane, the cross-product works. If they are both in the lower half plane, it also works (backwards). If they are in the different half planes, the one in the upper is less." } ]
[ { "body": "<h2 id=\"early-returns\">Early returns</h2>\n<p>You have a bunch of them. I'm all for them (not everyone is), but you're inconsistent in your <code>else</code> style after an early return. Sometimes you do this:</p>\n<pre><code> if(a[1] == 0){\n return a[0] &gt; 0 ? 1 : 5;\n }else // ...\n</code></pre>\n<p>and sometimes you dispense with the <code>else</code>:</p>\n<pre><code> if(a[1] &gt; 0){\n return a[0] &gt; 0 ? 2 : 4;\n }\n return a[0] &gt; 0 ? 8 : 6;\n</code></pre>\n<p>My preferred style is the latter, since <code>else</code> is redundant.</p>\n<h2 id=\"inline\">Inline</h2>\n<p>Even if a compiler were to respect your explicit <code>inline</code> (which it typically doesn't), you wouldn't want it to. Compilers are better than humans at deciding what should be auto-inlined and what shouldn't. Just drop the <code>inline</code>.</p>\n<p>Further reading e.g.: <a href=\"https://www.greenend.org.uk/rjk/tech/inline.html\" rel=\"nofollow noreferrer\">https://www.greenend.org.uk/rjk/tech/inline.html</a>, particularly</p>\n<blockquote>\n<p>Sometimes it is necessary for the compiler to emit a stand-alone copy of the object code for a function even though it is an inline function</p>\n<p>[...]</p>\n<p>You can have a separate (not inline) definition in another translation unit, and the compiler might choose either that or the inline definition.</p>\n</blockquote>\n<p>and <a href=\"https://stackoverflow.com/questions/2082551/what-does-inline-mean\">https://stackoverflow.com/questions/2082551/what-does-inline-mean</a>, including</p>\n<blockquote>\n<p>nowadays most compilers don't even acknowledge it as a hint to inline the function.</p>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-18T14:32:21.123", "Id": "264159", "ParentId": "264154", "Score": "2" } }, { "body": "<p><strong>should I worry about dealing with overflow in the computation of ord?</strong></p>\n<p>Yes. The difference may overflow.</p>\n<p>Instead compare:</p>\n<pre><code>// Compute cross product sign (see next bullet)\nint64_t ba = b[0]*a[1];\nint64_t ab = a[0]*b[1];\nif(ba &lt; ab) return -1;\nif(ba == ab) return 0;\nreturn 1;\n</code></pre>\n<p><strong>can I simplify this comparison function even further?</strong></p>\n<p>Excessive comparing is done.</p>\n<p>To expand on <a href=\"https://codereview.stackexchange.com/questions/264154/simplify-2d-point-angle-comparator#comment521715_264154\">@vnp</a> idea:</p>\n<blockquote>\n<p>...If both vectors are in the upper half plane, the cross-product works. If they are both in the lower half plane, it also works (backwards). If they are in the different half planes, the one in the upper is less.</p>\n</blockquote>\n<pre><code>int cmp_x_y(const int64_t a[2], const int64_t b[2]) {\n if (a[1] &lt; 0 == b[1] &lt; 0) { // same upper/lower plane? \n int cps = cross_product_sign(a,b);\n if (a[1] &lt; 0) cps = -cps;\n return cps;\n }\n return a[1] &lt; 0 ? -1 : 1;\n}\n</code></pre>\n<p>Above may need some edge-case review, but does present the idea to use the cross-product as the general solution path.</p>\n<p><strong><code>void *</code> vs. <code>int64_t *</code></strong></p>\n<p><code>*a = _a</code> leads to <em>undefined behavior</em> (UB) should <code>*_a</code> not meet the alignment requirements of <code>int64_t</code>. <code>void *</code> also loses some type checking.</p>\n<p>Suggest simple using <code>int64_t *</code> or <code>int64_t a[2]</code>.</p>\n<pre><code>//static inline int cmp_x_y(const void *_a, const void *_b){\n// const int64_t *a = _a, *b = _b;\n\nstatic inline int cmp_x_y(const int64_t *a, const int64_t *b) {\n// or\nstatic inline int cmp_x_y(const int64_t a[2], const int64_t b[2]) {\n</code></pre>\n<p><strong>Minor: discussion error</strong></p>\n<blockquote>\n<p>This can be done pretty trivially using the atan2 function, which has built in handling for different quadrants and simply returns a normalized angle (between 0 inclusive and 2 pi exclusive)</p>\n</blockquote>\n<p>Above is amiss: <code>atan2(y, x)</code> returns &quot;arctan y=x in the interval [-π π] radians.&quot;</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T02:34:23.470", "Id": "521781", "Score": "0", "body": "Oh right! I've used the cross product approach a lot in the past but I got stuck on a tan based approach. I have to stick with `void*` since this is a generic callback. (I have strict aliasing disabled which works around casting flexible length char arrays in generic data structs and alignment on platforms allowing unaligned access. I think the drawbacks of `void*` with no strict aliasing are more benign than of macro based or intrusive structs.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T02:39:58.150", "Id": "521782", "Score": "0", "body": "@hacatu It is not the aliasing issue, but the alignment that can break code here. If stuck with `void* _a`, could use `int64_t a; memcpy(&a, _a, sizeof a):` as that fixes alignment issues and a good compiler will talk advantage as it can to emit efficient code without a function call." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T14:32:08.567", "Id": "264186", "ParentId": "264154", "Score": "3" } } ]
{ "AcceptedAnswerId": "264186", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-18T01:26:38.217", "Id": "264154", "Score": "3", "Tags": [ "c", "coordinate-system", "callback", "cyclomatic-complexity" ], "Title": "Simplify 2D point angle comparator" }
264154
<p>So, I wrote this function to sort three numbers in Julia. Any feedback on readability, performance, and Julian-ness would be appreciated.</p> <pre class="lang-julia prettyprint-override"><code>function sort_asc(a, b, c) # defined in function so as not to overwrite Base.minmax minmax(x, y) = ifelse(x &lt; y, (x, y), (y, x)) l1, h1 = minmax(a, b) lo, h2 = minmax(l1, c) md, hi = minmax(h1, h2) return lo, md, hi end </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T13:37:10.167", "Id": "521756", "Score": "0", "body": "There's no need to swap `x` and `y` if they're equal, so I'd prefer less-or-equal instead of less-than." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T09:23:48.253", "Id": "532690", "Score": "0", "body": "Have a look at the code in [SortingNetworks.jl](https://github.com/JeffreySarnoff/SortingNetworks.jl). They seem to be using your approach, but with a branching `minmax`. Probably for good reason." } ]
[ { "body": "<p>As it turns out</p>\n<pre class=\"lang-julia prettyprint-override\"><code>function sort_asc(a, b, c)\n l1, h1 = minmax(a, b)\n lo, h2 = minmax(l1, c)\n md, hi = minmax(h1, h2)\n return lo, md, hi\nend\n</code></pre>\n<p>results in the exact same native assembly instructions on my machine (compared to the branchless version). So, given its greater simplicity, I think this is the best version so far.</p>\n<p>Here are comparisons to other implementations</p>\n<pre class=\"lang-julia prettyprint-override\"><code>function sort3(a, b, c)\n l1, h1 = minmax(a, b)\n lo, h2 = minmax(l1, c)\n md, hi = minmax(h1, h2)\n return lo, md, hi\nend\n\n@inline minmax_nb(x, y) = ifelse(isless(x, y), (x, y), (y, x))\n\nfunction sort3_nb(a, b, c)\n l1, h1 = minmax_nb(a, b)\n lo, h2 = minmax_nb(l1, c)\n md, hi = minmax_nb(h1, h2)\n return lo, md, hi\nend\n\nfunction sort3_koen(a, b, c)\n lo, md = minmax(a, b)\n if md &gt; c\n hi = md\n lo, md = minmax(lo, c)\n else\n hi = c\n end\n\n return lo, md, hi\nend\n</code></pre>\n<p>Here is the benchmark code</p>\n<pre class=\"lang-julia prettyprint-override\"><code>using BenchmarkTools\n\nfunction map_sort3!(f::F, out, data) where F\n @inbounds for i in eachindex(out, data)\n a, b, c = data[i]\n out[i] = f(a, b, c)\n end\nend\n\nfor f in [sort3, sort3_nb, sort3_koen]\n print(rpad(f, 12), &quot;:&quot;)\n @btime map_sort3!($f, out, data) setup=begin\n data = [ntuple(i -&gt; rand(Int), 3) for _ in 1:10_000]\n out = similar(data)\n end evals=1\nend\n</code></pre>\n<p>And here are the results on my machine:</p>\n<pre><code>sort3 : 17.286 μs (0 allocations: 0 bytes)\nsort3_nb : 17.624 μs (0 allocations: 0 bytes)\nsort3_koen : 21.776 μs (0 allocations: 0 bytes)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T10:26:41.357", "Id": "264173", "ParentId": "264158", "Score": "1" } }, { "body": "<p>I'd expect this to be marginally faster:</p>\n<pre><code>(lo,md) = minmax(a,b)\nif md &gt; c\n hi = md\n (lo,md) = minmax(lo,c)\nelse\n hi = c\n</code></pre>\n<p>I don't know where this sits in the scale of Julianesquinness since I'm not familiar with Julia (not even sure if my &quot;if-else&quot; adheres to its syntax, but the intention should be clear).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-23T12:41:07.747", "Id": "264321", "ParentId": "264158", "Score": "0" } } ]
{ "AcceptedAnswerId": "264173", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-18T11:30:10.017", "Id": "264158", "Score": "2", "Tags": [ "algorithm", "sorting", "julia" ], "Title": "Sort three numbers" }
264158
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/263729/231235">Tests for the operators of image template class in C++</a> and <a href="https://codereview.stackexchange.com/q/263956/231235">A recursive_transform template function for the multiple parameters cases in C++</a>. I appreciated <a href="https://codereview.stackexchange.com/a/263988/231235">G. Sliepen's answer</a>. I am attempting to extend the mentioned element-wise operations in <code>TinyDIP::Image</code> image class. In other words, not only <code>+</code>, <code>-</code>, <code>*</code> and <code>/</code> but also other customized calculations can be specified easily with the implemented <code>pixelwiseOperation</code> template function here. For example:</p> <p>There are four images and each pixel value in these images are set to 4, 3, 2 and 1, respectively.</p> <pre><code>auto img1 = TinyDIP::Image&lt;GrayScale&gt;(10, 10, 4); auto img2 = TinyDIP::Image&lt;GrayScale&gt;(10, 10, 3); auto img3 = TinyDIP::Image&lt;GrayScale&gt;(10, 10, 2); auto img4 = TinyDIP::Image&lt;GrayScale&gt;(10, 10, 1); </code></pre> <p>If we want to perform the element-wise calculation &quot;Two times of <code>img1</code> plus <code>img2</code> then minus the result of <code>img3</code> multiply <code>img4</code>, this task could be done with the following code:</p> <pre><code>auto output = TinyDIP::pixelwiseOperation( [](auto&amp;&amp; pixel_in_img1, auto&amp;&amp; pixel_in_img2, auto&amp;&amp; pixel_in_img3, auto&amp;&amp; pixel_in_img4) { return 2 * pixel_in_img1 + pixel_in_img2 - pixel_in_img3 * pixel_in_img4; }, img1, img2, img3, img4 ); </code></pre> <p>The result can be printed with <code>output.print();</code>:</p> <pre><code>9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 </code></pre> <p><strong>The experimental implementation</strong></p> <ul> <li><p><code>pixelwiseOperation</code> template function implementation: based on <code>recursive_transform</code></p> <pre><code>template&lt;typename Op, class InputT, class... Args&gt; constexpr static Image&lt;InputT&gt; pixelwiseOperation(Op op, const Image&lt;InputT&gt;&amp; input1, const Args&amp;... inputs) { Image&lt;InputT&gt; output( recursive_transform&lt;1&gt;( [&amp;](auto&amp;&amp; element1, auto&amp;&amp;... elements) { auto result = op(element1, elements...); return static_cast&lt;InputT&gt;(std::clamp( result, static_cast&lt;decltype(result)&gt;(std::numeric_limits&lt;InputT&gt;::min()), static_cast&lt;decltype(result)&gt;(std::numeric_limits&lt;InputT&gt;::max()))); }, (input1.getImageData()), (inputs.getImageData())...), input1.getWidth(), input1.getHeight()); return output; } </code></pre> </li> <li><p><code>image_operations.h</code>: The file contains <code>pixelwiseOperation</code> template function and other image processing functions</p> <pre><code>/* Developed by Jimmy Hu */ #ifndef ImageOperations_H #define ImageOperations_H #include &lt;string&gt; #include &quot;base_types.h&quot; #include &quot;image.h&quot; // Reference: https://stackoverflow.com/a/26065433/6667035 #ifndef M_PI #define M_PI 3.14159265358979323846 #endif namespace TinyDIP { // Forward Declaration class Image template &lt;typename ElementT&gt; class Image; template&lt;typename T&gt; T normalDistribution1D(const T x, const T standard_deviation) { return std::exp(-x * x / (2 * standard_deviation * standard_deviation)); } template&lt;typename T&gt; T normalDistribution2D(const T xlocation, const T ylocation, const T standard_deviation) { return std::exp(-(xlocation * xlocation + ylocation * ylocation) / (2 * standard_deviation * standard_deviation)) / (2 * M_PI * standard_deviation * standard_deviation); } template&lt;class InputT1, class InputT2&gt; constexpr static auto cubicPolate(const InputT1 v0, const InputT1 v1, const InputT1 v2, const InputT1 v3, const InputT2 frac) { auto A = (v3-v2)-(v0-v1); auto B = (v0-v1)-A; auto C = v2-v0; auto D = v1; return D + frac * (C + frac * (B + frac * A)); } template&lt;class InputT = float, class ElementT&gt; constexpr static auto bicubicPolate(const ElementT* const ndata, const InputT fracx, const InputT fracy) { auto x1 = cubicPolate( ndata[0], ndata[1], ndata[2], ndata[3], fracx ); auto x2 = cubicPolate( ndata[4], ndata[5], ndata[6], ndata[7], fracx ); auto x3 = cubicPolate( ndata[8], ndata[9], ndata[10], ndata[11], fracx ); auto x4 = cubicPolate( ndata[12], ndata[13], ndata[14], ndata[15], fracx ); return std::clamp( cubicPolate( x1, x2, x3, x4, fracy ), static_cast&lt;InputT&gt;(std::numeric_limits&lt;ElementT&gt;::min()), static_cast&lt;InputT&gt;(std::numeric_limits&lt;ElementT&gt;::max())); } template&lt;class FloatingType = float, class ElementT&gt; Image&lt;ElementT&gt; copyResizeBicubic(Image&lt;ElementT&gt;&amp; image, size_t width, size_t height) { auto output = Image&lt;ElementT&gt;(width, height); // get used to the C++ way of casting auto ratiox = static_cast&lt;FloatingType&gt;(image.getWidth()) / static_cast&lt;FloatingType&gt;(width); auto ratioy = static_cast&lt;FloatingType&gt;(image.getHeight()) / static_cast&lt;FloatingType&gt;(height); for (size_t y = 0; y &lt; height; ++y) { for (size_t x = 0; x &lt; width; ++x) { FloatingType xMappingToOrigin = static_cast&lt;FloatingType&gt;(x) * ratiox; FloatingType yMappingToOrigin = static_cast&lt;FloatingType&gt;(y) * ratioy; FloatingType xMappingToOriginFloor = std::floor(xMappingToOrigin); FloatingType yMappingToOriginFloor = std::floor(yMappingToOrigin); FloatingType xMappingToOriginFrac = xMappingToOrigin - xMappingToOriginFloor; FloatingType yMappingToOriginFrac = yMappingToOrigin - yMappingToOriginFloor; ElementT ndata[4 * 4]; for (int ndatay = -1; ndatay &lt;= 2; ++ndatay) { for (int ndatax = -1; ndatax &lt;= 2; ++ndatax) { ndata[(ndatay + 1) * 4 + (ndatax + 1)] = image.at( std::clamp(xMappingToOriginFloor + ndatax, static_cast&lt;FloatingType&gt;(0), image.getWidth() - static_cast&lt;FloatingType&gt;(1)), std::clamp(yMappingToOriginFloor + ndatay, static_cast&lt;FloatingType&gt;(0), image.getHeight() - static_cast&lt;FloatingType&gt;(1))); } } output.at(x, y) = bicubicPolate(ndata, xMappingToOriginFrac, yMappingToOriginFrac); } } return output; } // multiple standard deviations template&lt;class InputT&gt; constexpr static Image&lt;InputT&gt; gaussianFigure2D( const size_t xsize, const size_t ysize, const size_t centerx, const size_t centery, const InputT standard_deviation_x, const InputT standard_deviation_y) { auto output = TinyDIP::Image&lt;InputT&gt;(xsize, ysize); auto row_vector_x = TinyDIP::Image&lt;InputT&gt;(xsize, 1); for (size_t x = 0; x &lt; xsize; ++x) { row_vector_x.at(x, 0) = normalDistribution1D(static_cast&lt;InputT&gt;(x) - static_cast&lt;InputT&gt;(centerx), standard_deviation_x); } auto row_vector_y = TinyDIP::Image&lt;InputT&gt;(ysize, 1); for (size_t y = 0; y &lt; ysize; ++y) { row_vector_y.at(y, 0) = normalDistribution1D(static_cast&lt;InputT&gt;(y) - static_cast&lt;InputT&gt;(centery), standard_deviation_y); } for (size_t y = 0; y &lt; ysize; ++y) { for (size_t x = 0; x &lt; xsize; ++x) { output.at(x, y) = row_vector_x.at(x, 0) * row_vector_y.at(y, 0); } } return output; } // single standard deviation template&lt;class InputT&gt; constexpr static Image&lt;InputT&gt; gaussianFigure2D( const size_t xsize, const size_t ysize, const size_t centerx, const size_t centery, const InputT standard_deviation) { return gaussianFigure2D(xsize, ysize, centerx, centery, standard_deviation, standard_deviation); } template&lt;typename Op, class InputT, class... Args&gt; constexpr static Image&lt;InputT&gt; pixelwiseOperation(Op op, const Image&lt;InputT&gt;&amp; input1, const Args&amp;... inputs) { Image&lt;InputT&gt; output( recursive_transform&lt;1&gt;( [&amp;](auto&amp;&amp; element1, auto&amp;&amp;... elements) { auto result = op(element1, elements...); return static_cast&lt;InputT&gt;(std::clamp( result, static_cast&lt;decltype(result)&gt;(std::numeric_limits&lt;InputT&gt;::min()), static_cast&lt;decltype(result)&gt;(std::numeric_limits&lt;InputT&gt;::max()))); }, (input1.getImageData()), (inputs.getImageData())...), input1.getWidth(), input1.getHeight()); return output; } template&lt;class InputT&gt; constexpr static Image&lt;InputT&gt; plus(const Image&lt;InputT&gt;&amp; input1) { return input1; } template&lt;class InputT, class... Args&gt; constexpr static Image&lt;InputT&gt; plus(const Image&lt;InputT&gt;&amp; input1, const Args&amp;... inputs) { return TinyDIP::pixelwiseOperation(std::plus&lt;&gt;{}, input1, plus(inputs...)); } template&lt;class InputT&gt; constexpr static Image&lt;InputT&gt; subtract(const Image&lt;InputT&gt;&amp; input1, const Image&lt;InputT&gt;&amp; input2) { assert(input1.getWidth() == input2.getWidth()); assert(input1.getHeight() == input2.getHeight()); return TinyDIP::pixelwiseOperation(std::minus&lt;&gt;{}, input1, input2); } template&lt;class InputT = RGB&gt; requires (std::same_as&lt;InputT, RGB&gt;) constexpr static Image&lt;InputT&gt; subtract(Image&lt;InputT&gt;&amp; input1, Image&lt;InputT&gt;&amp; input2) { assert(input1.getWidth() == input2.getWidth()); assert(input1.getHeight() == input2.getHeight()); Image&lt;InputT&gt; output(input1.getWidth(), input1.getHeight()); for (std::size_t y = 0; y &lt; input1.getHeight(); ++y) { for (std::size_t x = 0; x &lt; input1.getWidth(); ++x) { for(std::size_t channel_index = 0; channel_index &lt; 3; ++channel_index) { output.at(x, y).channels[channel_index] = std::clamp( input1.at(x, y).channels[channel_index] - input2.at(x, y).channels[channel_index], 0, 255); } } } return output; } } #endif </code></pre> </li> <li><p><code>image.h</code>: The file contains the definition of <code>Image</code> class.</p> <pre><code>/* Developed by Jimmy Hu */ #ifndef Image_H #define Image_H #include &lt;algorithm&gt; #include &lt;array&gt; #include &lt;cassert&gt; #include &lt;chrono&gt; #include &lt;complex&gt; #include &lt;concepts&gt; #include &lt;functional&gt; #include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;list&gt; #include &lt;numeric&gt; #include &lt;string&gt; #include &lt;type_traits&gt; #include &lt;variant&gt; #include &lt;vector&gt; #include &quot;image_operations.h&quot; namespace TinyDIP { template &lt;typename ElementT&gt; class Image { public: Image() = default; Image(const std::size_t width, const std::size_t height): width(width), height(height), image_data(width * height) { } Image(const std::size_t width, const std::size_t height, const ElementT initVal): width(width), height(height), image_data(width * height, initVal) {} Image(const std::vector&lt;ElementT&gt;&amp; input, std::size_t newWidth, std::size_t newHeight): width(newWidth), height(newHeight) { assert(input.size() == newWidth * newHeight); this-&gt;image_data = input; // Deep copy } Image(const std::vector&lt;std::vector&lt;ElementT&gt;&gt;&amp; input) { this-&gt;height = input.size(); this-&gt;width = input[0].size(); for (auto&amp; rows : input) { this-&gt;image_data.insert(this-&gt;image_data.end(), std::begin(input), std::end(input)); // flatten } return; } constexpr ElementT&amp; at(const unsigned int x, const unsigned int y) { checkBoundary(x, y); return this-&gt;image_data[y * width + x]; } constexpr ElementT const&amp; at(const unsigned int x, const unsigned int y) const { checkBoundary(x, y); return this-&gt;image_data[y * width + x]; } constexpr std::size_t getWidth() const { return this-&gt;width; } constexpr std::size_t getHeight() const { return this-&gt;height; } std::vector&lt;ElementT&gt; const&amp; getImageData() const { return this-&gt;image_data; } // expose the internal data void print() { for (std::size_t y = 0; y &lt; this-&gt;height; ++y) { for (std::size_t x = 0; x &lt; this-&gt;width; ++x) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number std::cout &lt;&lt; +this-&gt;at(x, y) &lt;&lt; &quot;\t&quot;; } std::cout &lt;&lt; &quot;\n&quot;; } std::cout &lt;&lt; &quot;\n&quot;; return; } // Enable this function if ElementT = RGB void print() requires(std::same_as&lt;ElementT, RGB&gt;) { for (std::size_t y = 0; y &lt; this-&gt;height; ++y) { for (std::size_t x = 0; x &lt; this-&gt;width; ++x) { std::cout &lt;&lt; &quot;( &quot;; for (std::size_t channel_index = 0; channel_index &lt; 3; ++channel_index) { // Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number std::cout &lt;&lt; +this-&gt;at(x, y).channels[channel_index] &lt;&lt; &quot;\t&quot;; } std::cout &lt;&lt; &quot;)\t&quot;; } std::cout &lt;&lt; &quot;\n&quot;; } std::cout &lt;&lt; &quot;\n&quot;; return; } Image&lt;ElementT&gt;&amp; operator+=(const Image&lt;ElementT&gt;&amp; rhs) { assert(rhs.width == this-&gt;width); assert(rhs.height == this-&gt;height); std::transform(image_data.cbegin(), image_data.cend(), rhs.image_data.cbegin(), image_data.begin(), std::plus&lt;&gt;{}); return *this; } Image&lt;ElementT&gt;&amp; operator-=(const Image&lt;ElementT&gt;&amp; rhs) { assert(rhs.width == this-&gt;width); assert(rhs.height == this-&gt;height); std::transform(image_data.cbegin(), image_data.cend(), rhs.image_data.cbegin(), image_data.begin(), std::minus&lt;&gt;{}); return *this; } Image&lt;ElementT&gt;&amp; operator*=(const Image&lt;ElementT&gt;&amp; rhs) { assert(rhs.width == this-&gt;width); assert(rhs.height == this-&gt;height); std::transform(image_data.cbegin(), image_data.cend(), rhs.image_data.cbegin(), image_data.begin(), std::multiplies&lt;&gt;{}); return *this; } Image&lt;ElementT&gt;&amp; operator/=(const Image&lt;ElementT&gt;&amp; rhs) { assert(rhs.width == this-&gt;width); assert(rhs.height == this-&gt;height); std::transform(image_data.cbegin(), image_data.cend(), rhs.image_data.cbegin(), image_data.begin(), std::divides&lt;&gt;{}); return *this; } Image&lt;ElementT&gt;&amp; operator=(Image&lt;ElementT&gt; const&amp; input) = default; // Copy Assign Image&lt;ElementT&gt;&amp; operator=(Image&lt;ElementT&gt;&amp;&amp; other) = default; // Move Assign Image(const Image&lt;ElementT&gt; &amp;input) = default; // Copy Constructor Image(Image&lt;ElementT&gt; &amp;&amp;input) = default; // Move Constructor private: size_t width; size_t height; std::vector&lt;ElementT&gt; image_data; void checkBoundary(const size_t x, const size_t y) { assert(x &lt; width); assert(y &lt; height); } }; } #endif </code></pre> </li> <li><p><code>base_types.h</code>: The base types declaration</p> <pre><code>/* Developed by Jimmy Hu */ #ifndef BASE_H #define BASE_H #define _USE_MATH_DEFINES #include &lt;math.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string&gt; #include &lt;utility&gt; constexpr int MAX_PATH = 256; #define FILE_ROOT_PATH &quot;./&quot; using BYTE = unsigned char; struct RGB { unsigned char channels[3]; }; using GrayScale = BYTE; struct HSV { double channels[3]; // Range: 0 &lt;= H &lt; 360, 0 &lt;= S &lt;= 1, 0 &lt;= V &lt;= 255 }; struct BMPIMAGE { char FILENAME[MAX_PATH]; unsigned int XSIZE; unsigned int YSIZE; unsigned char FILLINGBYTE; unsigned char *IMAGE_DATA; }; #endif </code></pre> </li> <li><p><code>basic_functions.h</code>: The file contains the definition of <code>recursive_transform</code></p> <pre><code>/* Developed by Jimmy Hu */ #ifndef BasicFunctions_H #define BasicFunctions_H #include &lt;algorithm&gt; #include &lt;array&gt; #include &lt;cassert&gt; #include &lt;chrono&gt; #include &lt;complex&gt; #include &lt;concepts&gt; #include &lt;deque&gt; #include &lt;execution&gt; #include &lt;exception&gt; #include &lt;functional&gt; #include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;list&gt; #include &lt;map&gt; #include &lt;mutex&gt; #include &lt;numeric&gt; #include &lt;optional&gt; #include &lt;ranges&gt; #include &lt;stdexcept&gt; #include &lt;string&gt; #include &lt;tuple&gt; #include &lt;type_traits&gt; #include &lt;utility&gt; #include &lt;variant&gt; #include &lt;vector&gt; namespace TinyDIP { // recursive_variadic_invoke_result_t implementation template&lt;std::size_t, typename, typename, typename...&gt; struct recursive_variadic_invoke_result { }; template&lt;typename F, class...Ts1, template&lt;class...&gt;class Container1, typename... Ts&gt; struct recursive_variadic_invoke_result&lt;1, F, Container1&lt;Ts1...&gt;, Ts...&gt; { using type = Container1&lt;std::invoke_result_t&lt;F, std::ranges::range_value_t&lt;Container1&lt;Ts1...&gt;&gt;, std::ranges::range_value_t&lt;Ts&gt;...&gt;&gt;; }; template&lt;std::size_t unwrap_level, typename F, class...Ts1, template&lt;class...&gt;class Container1, typename... Ts&gt; requires ( std::ranges::input_range&lt;Container1&lt;Ts1...&gt;&gt; &amp;&amp; requires { typename recursive_variadic_invoke_result&lt; unwrap_level - 1, F, std::ranges::range_value_t&lt;Container1&lt;Ts1...&gt;&gt;, std::ranges::range_value_t&lt;Ts&gt;...&gt;::type; }) // The rest arguments are ranges struct recursive_variadic_invoke_result&lt;unwrap_level, F, Container1&lt;Ts1...&gt;, Ts...&gt; { using type = Container1&lt; typename recursive_variadic_invoke_result&lt; unwrap_level - 1, F, std::ranges::range_value_t&lt;Container1&lt;Ts1...&gt;&gt;, std::ranges::range_value_t&lt;Ts&gt;... &gt;::type&gt;; }; template&lt;std::size_t unwrap_level, typename F, typename T1, typename... Ts&gt; using recursive_variadic_invoke_result_t = typename recursive_variadic_invoke_result&lt;unwrap_level, F, T1, Ts...&gt;::type; template&lt;typename OutputIt, typename NAryOperation, typename InputIt, typename... InputIts&gt; OutputIt transform(OutputIt d_first, NAryOperation op, InputIt first, InputIt last, InputIts... rest) { while (first != last) { *d_first++ = op(*first++, (*rest++)...); } return d_first; } // recursive_transform for the multiple parameters cases (the version with unwrap_level) template&lt;std::size_t unwrap_level = 1, class F, class Arg1, class... Args&gt; constexpr auto recursive_transform(const F&amp; f, const Arg1&amp; arg1, const Args&amp;... args) { if constexpr (unwrap_level &gt; 0) { recursive_variadic_invoke_result_t&lt;unwrap_level, F, Arg1, Args...&gt; output{}; transform( std::inserter(output, std::ranges::end(output)), [&amp;f](auto&amp;&amp; element1, auto&amp;&amp;... elements) { return recursive_transform&lt;unwrap_level - 1&gt;(f, element1, elements...); }, std::ranges::cbegin(arg1), std::ranges::cend(arg1), std::ranges::cbegin(args)... ); return output; } else { return f(arg1, args...); } } } #endif </code></pre> </li> </ul> <p><strong>The testing code</strong></p> <pre><code>/* Developed by Jimmy Hu */ #include &quot;image.h&quot; #include &quot;basic_functions.h&quot; int main() { auto img1 = TinyDIP::Image&lt;GrayScale&gt;(10, 10, 4); auto img2 = TinyDIP::Image&lt;GrayScale&gt;(10, 10, 3); auto img3 = TinyDIP::Image&lt;GrayScale&gt;(10, 10, 2); auto img4 = TinyDIP::Image&lt;GrayScale&gt;(10, 10, 1); auto output = TinyDIP::pixelwiseOperation( [](auto&amp;&amp; pixel_in_img1, auto&amp;&amp; pixel_in_img2, auto&amp;&amp; pixel_in_img3, auto&amp;&amp; pixel_in_img4) { return 2 * pixel_in_img1 + pixel_in_img2 - pixel_in_img3 * pixel_in_img4; }, img1, img2, img3, img4 ); output.print(); return 0; } </code></pre> <p><strong>Test platform</strong></p> <p>MacOS: g++-11 (Homebrew GCC 11.1.0_1) 11.1.0</p> <p>All suggestions are welcome.</p> <p>The summary information:</p> <ul> <li><p>Which question it is a follow-up to?</p> <p><a href="https://codereview.stackexchange.com/q/263729/231235">Tests for the operators of image template class in C++</a> and</p> <p><a href="https://codereview.stackexchange.com/q/263956/231235">A recursive_transform template function for the multiple parameters cases in C++</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <p>I am attempting to extend the mentioned element-wise operations in this post.</p> </li> <li><p>Why a new review is being asked for?</p> <p>If there is any possible improvement, please let me know.</p> </li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-22T03:05:56.557", "Id": "521890", "Score": "1", "body": "I’ve commented this in an answer to you before, include only the include files you actually need in that source file. Your `basic_functions.h` includes everything that you never need. There are more lines of include statements than actual code. There is a reason there’s not just one `<std>` header. It is very inefficient to include everything." } ]
[ { "body": "<pre><code>#ifndef M_PI\n #define M_PI 3.14159265358979323846\n#endif\n</code></pre>\n<p>Don't use <code>#define</code>, and since you marked this as C++20 <a href=\"https://en.cppreference.com/w/cpp/numeric/constants\" rel=\"nofollow noreferrer\">use the constants supplied in the standard library</a>.</p>\n<pre><code>constexpr int MAX_PATH = 256;\n#define FILE_ROOT_PATH &quot;./&quot;\n</code></pre>\n<p>Use the <code>path</code> type, not fixed-size arrays of characters, for filename manipulation. Don't use <code>#define</code>.</p>\n<p><code>using BYTE = unsigned char;</code></p>\n<p>There is a <code>std::byte</code> type now. If that is not what you want, you ought to use <code>uint_8</code> to avoid confusion and be consistent with standard code.</p>\n<pre><code>struct RGB\n{\n unsigned char channels[3];\n};\n</code></pre>\n<p>Come on, you <em>just</em> defined <code>BYTE</code> on the previous line! Why don't you use it?</p>\n<pre><code>struct BMPIMAGE\n{\n char FILENAME[MAX_PATH];\n\n unsigned int XSIZE;\n unsigned int YSIZE;\n unsigned char FILLINGBYTE;\n unsigned char *IMAGE_DATA;\n};\n</code></pre>\n<p>Use <code>std::filesystem::path</code> rather than a fixed array of characters. Use <code>int32_t</code> or whatever, rather than the implementation-dependant <code>unsigned int</code>. Prefer <em>signed</em> types unless you really need that one more bit for the range, or are doing bitwise operations.</p>\n<p>You defined <code>BYTE</code> and probably mean that here, but don't use it. Use <code>uint8_t</code> or <code>std::byte</code> for these.</p>\n<p>You might consider using a 2-D point class rather than separate height and width fields. You may find it is common to have x and y things always being used together, for positions and sizes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T00:28:23.773", "Id": "264226", "ParentId": "264161", "Score": "1" } } ]
{ "AcceptedAnswerId": "264226", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-18T18:48:12.400", "Id": "264161", "Score": "0", "Tags": [ "c++", "image", "template", "lambda", "c++20" ], "Title": "Image pixelwise operation function with multiple inputs in C++" }
264161
<p>I have a macro I have been using to generate daily fantasy (dfs) lineups for soccer matches. I would like to know where I can speed up my code so I can run more simulations.</p> <p>Briefly, I have a worksheet in which I try to 'simulate' individual scores for each player in a match (e.g. &quot;ITAvENG&quot; in the code below). This uses the rand() formula in excel so I have to copy and paste values of these scores each time my code runs.</p> <p>I then call the Excel Solver to calculate the optimal lineup based on those scores (within the constraints of the game/site).</p> <p>Finally it copies and pastes that lineup into a different worksheet before repeating the process again.</p> <p>I can currently run 1,000 sims in about 10-15 minutes* but I know I can improve this speed (e.g. I think I am copying and pasting inefficiently?). Can someone advise please?</p> <p>*There is a lot going on elsewhere in the workbook that I think might be slowing me down as well, I would be happy to explain / share this privately.</p> <pre><code>Sub Showdown() Application.Calculation = xlCalculationManual Application.ScreenUpdating = False Application.DisplayStatusBar = False Dim StartTime As Double Dim MinutesElapsed As String StartTime = Timer Dim i As Integer For i = 0 To 999 Calculate Sheets(&quot;ITAvENG&quot;).Select Range(&quot;N16:R54&quot;).Select Selection.Copy Range(&quot;S16&quot;).Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False SolverReset SolverAdd CellRef:=&quot;$AC$16:$AC$39&quot;, Relation:=1, FormulaText:=&quot;1&quot; SolverAdd CellRef:=&quot;$Z$3&quot;, Relation:=2, FormulaText:=&quot;1&quot; SolverAdd CellRef:=&quot;$Z$4&quot;, Relation:=2, FormulaText:=&quot;5&quot; SolverAdd CellRef:=&quot;$AC$3&quot;, Relation:=1, FormulaText:=&quot;50000&quot; SolverAdd CellRef:=&quot;$Z$6&quot;, Relation:=3, FormulaText:=&quot;1&quot; SolverAdd CellRef:=&quot;$Z$7&quot;, Relation:=3, FormulaText:=&quot;1&quot; SolverOk SetCell:=&quot;$AC$4&quot;, MaxMinVal:=1, ValueOf:=0, ByChange:=&quot;$AA$16:$AB$39&quot;, _ Engine:=2, EngineDesc:=&quot;Simplex LP&quot; SolverAdd CellRef:=&quot;$AA$16:$AB$39&quot;, Relation:=5, FormulaText:=&quot;binary&quot; SolverSolve True Range(&quot;AD16:AD81&quot;).Select Selection.Copy Sheets(&quot;ITAvENG Lineups&quot;).Select Range(&quot;$C$12&quot;).Offset(i, 0).Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=True, Transpose:=True Next i Application.Calculation = xlCalculationAutomatic Application.ScreenUpdating = True Application.DisplayStatusBar = True MinutesElapsed = Format((Timer - StartTime) / 86400, &quot;hh:mm:ss&quot;) MsgBox &quot;This code ran successfully in &quot; &amp; MinutesElapsed &amp; &quot;minutes&quot;, vbInformation End Sub </code></pre>
[]
[ { "body": "<p>Without knowing what <code>SolverReset</code>, <code>SolverAdd</code>, <code>SolverOK</code>, <code>SolverSolve</code>, and <code>Calculate</code> are doing specifically, there are limits to how much optimization can be suggested. That said, there are some general comments that may be useful that can have <em>some</em> effect on speed, but probably not of the magnitude you are hoping for.</p>\n<ol>\n<li><p>(Best Practice) Always declare <code>Option Explicit</code> at the top of all modules. This forces all variables to be declared explicitly within the module. In this case, adding <code>Option Explicit</code> did not identify any variables being used that were not declared..congrats!...still, it is recommended to avoid a number of hard to debug issues that arise from using undeclared variables (including typos of declared variables).</p>\n</li>\n<li><p>(Best Practice) When setting and resetting Application flags, it is best to cache the original values, set the values desired, and reset to the prior values at the end of an operation. Further, to absolutely guarantee that the values are reset, always call the 'business' code with error handling protection.</p>\n</li>\n<li><p>There is no need to <code>Select</code> cells to copy if you are using VBA to assign values/content. <code>Select</code> is required for a 'human-client' to accomplish the operation - but not a 'code-client'. This should provide some speed improvement - though probably minor.</p>\n</li>\n<li><p>Within the loop, there is only a single statement that depends on the index <code>i</code> (<code>Range(&quot;$C$12&quot;).Offset(i, 0).Select</code>).</p>\n<p>4a. This means that any statement within the loop that does <em>not depend</em> on the iteration value (or is not modified during each iteration) should be set prior to the loop. The only opportunity here (without knowing the contents of the subroutines listed above) is that <code>Sheets(&quot;ITAvENG Lineups&quot;)</code> need only be called once (rather than 2000 times).</p>\n<p>4b. Placing all the calls to <code>SolverReset</code>, <code>SolverAdd</code>, <code>SolverOK</code>, <code>SolverSolve</code>, and <code>Calculate</code> within the loop implies that each call is probably modifying content in the <code>CellRef</code> parameter of all the <code>SolverAdd</code> calls during each iteration. If this is not true, then set these cell formulas <em><strong>once</strong></em> outside the loop.</p>\n</li>\n</ol>\n<p>Below is a version that incorporates the comments above.</p>\n<pre><code> Option Explicit\n\n Sub Showdown()\n Dim originalApplicationCalcSetting As Long\n Dim originalApplicationScreenUpdating As Boolean\n Dim originalApplicationDisplayStatusBar As Boolean\n \n originalApplicationCalcSetting = Application.Calculation\n originalApplicationScreenUpdating = Application.ScreenUpdating\n originalApplicationDisplayStatusBar = Application.DisplayStatusBar\n\n Application.Calculation = xlCalculationManual\n Application.ScreenUpdating = False\n Application.DisplayStatusBar = False\n \n Dim StartTime As Double\n Dim MinutesElapsed As String\n StartTime = Timer\n \n Dim succeeded As Boolean\n succeeded = False\n On Error GoTo ErrorExit\n \n ShowdownImpl\n \n MinutesElapsed = Format((Timer - StartTime) / 86400, &quot;hh:mm:ss&quot;)\n \n MsgBox &quot;This code ran successfully in &quot; &amp; MinutesElapsed &amp; &quot;minutes&quot;, vbInformation\n succeeded = True\n ErrorExit:\n Application.Calculation = originalApplicationCalcSetting\n Application.ScreenUpdating = originalApplicationScreenUpdating\n Application.DisplayStatusBar = originalApplicationDisplayStatusBar\n \n If succeeded = False Then\n MsgBox &quot;Error Encountered&quot;\n End If\n End Sub\n\n Private Sub ShowdownImpl()\n \n Dim i As Integer\n \n Dim itAvENG As Worksheet\n Set itAvENG = Sheets(&quot;ITAvENG Lineups&quot;)\n \n For i = 0 To 999\n Calculate\n \n itAvENG.Range(&quot;N16:R54&quot;).Copy\n \n ActiveWorksheet.Range(&quot;S16&quot;).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _\n :=False, Transpose:=False\n \n SolverReset\n \n 'Are these cells modified each iteration?...if not, set these values outside of the loop\n SolverAdd CellRef:=&quot;$AC$16:$AC$39&quot;, Relation:=1, FormulaText:=&quot;1&quot;\n SolverAdd CellRef:=&quot;$Z$3&quot;, Relation:=2, FormulaText:=&quot;1&quot;\n SolverAdd CellRef:=&quot;$Z$4&quot;, Relation:=2, FormulaText:=&quot;5&quot;\n SolverAdd CellRef:=&quot;$AC$3&quot;, Relation:=1, FormulaText:=&quot;50000&quot;\n SolverAdd CellRef:=&quot;$Z$6&quot;, Relation:=3, FormulaText:=&quot;1&quot;\n SolverAdd CellRef:=&quot;$Z$7&quot;, Relation:=3, FormulaText:=&quot;1&quot;\n \n SolverOK SetCell:=&quot;$AC$4&quot;, MaxMinVal:=1, ValueOf:=0, ByChange:=&quot;$AA$16:$AB$39&quot;, _\n Engine:=2, EngineDesc:=&quot;Simplex LP&quot;\n \n SolverAdd CellRef:=&quot;$AA$16:$AB$39&quot;, Relation:=5, FormulaText:=&quot;binary&quot;\n \n SolverSolve True\n \n ActiveWorksheet.Range(&quot;AD16:AD81&quot;).Copy\n \n itAvENG.Range(&quot;$C$12&quot;).Offset(i, 0).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _\n :=True, Transpose:=True\n Next i\n End Sub\n\n 'Subroutines added below to allow the code to compile\n Private Sub SolverReset()\n End Sub\n\n Private Sub SolverAdd(CellRef As String, Relation As Long, FormulaText As String)\n End Sub\n\n Private Sub SolverOK(SetCell As String, MaxMinVal As Long, ValueOf As Long, ByChange As String, Engine As Long, EngineDesc As String)\n End Sub\n\n Private Sub SolverSolve(val As Boolean)\n End Sub\n\n Private Sub Calculate()\n End Sub\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T10:55:54.273", "Id": "521731", "Score": "2", "body": "Also, notice how much more readable it is with proper indention. Makes it _much_ easier to see where loops are and much easier to know what's _in_ the loop and what's _not_." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T00:58:58.733", "Id": "264167", "ParentId": "264162", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-18T19:44:16.227", "Id": "264162", "Score": "2", "Tags": [ "performance", "beginner", "vba", "excel" ], "Title": "Daily Fantasy (DFS) Lineup Generator in Excel VBA" }
264162
<p>Before start, I'd like to give some context.</p> <p>A couple of years ago I implemented an autocompletion function for one particular case: <a href="https://github.com/innogames/serveradmin/blob/master/zsh-completion/adminapi#L13" rel="nofollow noreferrer">querying all hosts from database</a>.</p> <p>It has a couple of flows. One of the most - rewriting and losing original completion.</p> <p>That's why after some evenings I've implemented the new approach. Now the function preserves the original one and extends it. As well it runs in the background and doesn't lock the console. The <a href="https://github.com/Felixoid/zsh-hoco/blob/master/hoco.zsh#L41-L105" rel="nofollow noreferrer">sources</a> are on github, but I'll post it here as well</p> <pre><code># Preserve _hosts as _hosts_orig, but only once if ! (( $_HOCO_INIT_DONE )); then typeset -g _HOCO_INIT_DONE=1 # _hosts needs to be intiated before tweaking _hosts 2&gt;/dev/null &gt;&amp;1 || true eval &quot;$(type -f _hosts | sed -r '1 s/_hosts/_hosts_orig/')&quot; fi __hosts_cache_callback() { ((_HOCO_RUNNING_JOBS--)) # It's 99.9% impossible to have empty original _cache_hosts, # but it's checked before filling originally. We should wait untill it's set while (( $+_cache_hosts == 0 )); do sleep 0.1 done # $2: exit status; $3: stdout [[ &quot;$2&quot; == 0 ]] &amp;&amp; _cache_hosts+=(&quot;${(f)3}&quot;) # cleaunup for the last job if (( _HOCO_RUNNING_JOBS == 0 )); then async_unregister_callback hosts_cache_updater async_stop_worker hosts_cache_updater fi } # Arguments: # $1 - cache_age __hosts_cache_update() { # if cache age is twice older than ${HOCO_CACHE_TTL:-600}, then it's definitely an issue # with long runnung tasks, abort them if (( ${HOCO_CACHE_TTL:-600} &lt; ${1} / 2 )); then unset _HOCO_UPDATE_RUNNING_SINCE async_flush_jobs hosts_cache_updater async_unregister_callback hosts_cache_updater async_stop_worker hosts_cache_updater fi (( ${_HOCO_UPDATE_RUNNING_SINCE} )) &amp;&amp; return 0 _HOCO_CACHE_UPDATED=${EPOCHSECONDS} unset _cache_hosts # starting worker that runs only one unic function with notifications async_start_worker hosts_cache_updater -n -u async_register_callback hosts_cache_updater __hosts_cache_callback _HOCO_RUNNING_JOBS=${#HOCO_FUNCTIONS} for func (${HOCO_FUNCTIONS}); do async_job hosts_cache_updater ${func} done } _hosts() { # Should be cache updated or not local cache_age cache_age=$((EPOCHSECONDS - _HOCO_CACHE_UPDATED)) if (( ${HOCO_CACHE_TTL:-600} &lt; ${cache_age} )); then __hosts_cache_update ${cache_age} fi # original logic _hosts_orig } </code></pre> <p>I've dug quite deep into the ZSH completion system, but maybe I still miss some points that could be useful. That's why I'd like to have my code reviewed.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-18T21:35:36.613", "Id": "264165", "Score": "1", "Tags": [ "autocomplete", "zsh" ], "Title": "Extension for original zsh _hosts completion" }
264165
<p>ArchiveInputStream is from apache-commons compress. it is an InputStream. <code>nextEntry</code> is the only method for traversing the stream i've found the while loop is IDE converted from apache docs.</p> <pre><code>fun ArchiveInputStream.forEachEntry(doThis: (ArchiveEntry) -&gt; Unit) { var e: ArchiveEntry? while (this.nextEntry.also { e = it } != null) { e?.let { doThis(it) } } } </code></pre> <p>I'm wondering if there is a better way to call next on an item until it is null and then use that in supplied function. It feels a bit weird to check if it's null and then to still have to use <code>e?.let</code> instead of just <code>doThis(e)</code></p> <p>full context of code</p> <pre><code> Files.newInputStream(Paths.get(filePath)).use { fi -&gt; BufferedInputStream(fi).use { bi -&gt; GzipCompressorInputStream(bi).use { gzi -&gt; TarArchiveInputStream(gzi).use { tarStream -&gt; tarStream .forEachEntry { // do things with entry and tarStream } } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T18:38:37.663", "Id": "521772", "Score": "3", "body": "Welcome to Code Review! I rolled back your last edit. After getting an answer you are not allowed to change your code anymore. This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). See the section _What should I not do?_ on [_What should I do when someone answers my question?_](https://codereview.stackexchange.com/help/someone-answers) for more information" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T19:15:48.063", "Id": "521773", "Score": "0", "body": "I read the edit you made (and Sam is right). Glad I could help :)" } ]
[ { "body": "<p>You basically created your own <code>forEach</code>.</p>\n<p>More idiomatic way is to provide Iterator/Iterable interfaces. Then you can use built-in functions like <code>forEach</code>, <code>filter</code> and <code>map</code>.</p>\n<p>Otherwise your implementation seems fine. Maybe I'd shorten your one liner to (I hope I get this right):</p>\n<pre><code>e?.let(::doThis)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T11:36:00.290", "Id": "521735", "Score": "1", "body": "Another alternative is `e?.also(::doThis)`, as `.let` is for returning a different value, while `.also` always returns the original value." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T11:37:03.953", "Id": "521736", "Score": "0", "body": "I totally agree about Iterator/Iterable, if it's possible to do in this data structure (unclear where the class comes from)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T12:51:04.780", "Id": "521749", "Score": "0", "body": "yes the intent is to get it to operate like those functions. i forgot i can look up the implementations to those functions and can compare to my solution. thank you" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T10:26:56.743", "Id": "264174", "ParentId": "264168", "Score": "0" } }, { "body": "<p>A more idiomatic approach would be to transform your <code>ArchiveInputStream</code> to a <code>Sequence&lt;ArchiveEntry&gt;</code>, on which you can do things like <code>filter</code>, <code>map</code>, <code>forEach</code>...</p>\n<p>As the only way you have of iterating through the input stream is <code>getNextEntry()</code>, we can write a method using a <em>sequence builder</em> to create the sequence.</p>\n<pre><code>fun ArchiveInputStream.asSequence(): Sequence&lt;ArchiveEntry&gt; {\n return sequence {\n var next = this.getNextEntry()\n while (next != null) {\n yield(next)\n next = this.getNextEntry()\n }\n }\n}\n</code></pre>\n<p>Note that while Kotlin might suggest writing it as <code>this.nextEntry</code> (property accessor) I would recommend against it, as property accessors should be used for <em>properties</em> and not for methods with side-effects. (As <code>getNextEntry()</code> returns a different result each time, it has a side effect). The Java API for this class was clearly not written with Kotlin in mind.</p>\n<p>With this <code>asSequence</code> function you can do this:</p>\n<pre><code>archiveInputStream.asSequence().forEach { ... }\n</code></pre>\n<hr />\n<p>Considering the full context of the code, you can reduce the nesting and amount of <code>.use</code> operations.</p>\n<pre><code>Files.newInputStream(Paths.get(filePath)).let {\n TarArchiveInputStream(GzipCompressorInputStream(BufferedInputStream(it)))\n}.use { tarStream -&gt;\n tarStream.forEachEntry {\n // do things with entry and tarStream \n }\n}\n</code></pre>\n<p>or if you want to split it up a bit:</p>\n<pre><code>Files.newInputStream(Paths.get(filePath))\n .let { BufferedInputStream(it) }\n .let { GzipCompressorInputStream(it) }\n .let { TarArchiveInputStream(it) }\n .use { tarStream -&gt;\n tarStream.forEachEntry {\n // do things with entry and tarStream \n }\n }\n</code></pre>\n<p>It's enough to close one of the streams as closing the decorating streams will also close the underlying stream.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T14:09:24.300", "Id": "264184", "ParentId": "264168", "Score": "2" } } ]
{ "AcceptedAnswerId": "264184", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T03:53:31.757", "Id": "264168", "Score": "0", "Tags": [ "kotlin" ], "Title": "Iterating through ArchiveInputStream or structures having a 'next'-accessor" }
264168
<p>I have a simple ZeroMQ client from <a href="https://gist.github.com/wonkoderverstaendige/7521416" rel="nofollow noreferrer">zmqClient</a>. I have refactored the code and done the following things.</p> <ol> <li><p>Created a class ZmqServer and added member variables and methods.</p> </li> <li><p>Added a Server thread, using std::async</p> </li> <li><p>Initialized a shared_ptr with ZmqServer and used std::move to pass that to the thread.</p> <pre><code>#include &lt;zmq.hpp&gt; #include &lt;iostream&gt; #include &lt;unistd.h&gt; #include &lt;future&gt; #include &lt;thread&gt; class ZmqServer{ public: ZmqServer() : m_context(1), m_socket(m_context, ZMQ_REP) { } void Bind(std::string protocol ,int port){ std::string bind_param; bind_param = protocol + &quot;://*:&quot; + std::to_string(port); m_socket.bind(bind_param); } void receive(){ zmq::message_t request; // Wait for next request from client m_socket.recv (&amp;request); std::cout &lt;&lt; &quot;Received message : &quot; &lt;&lt; request &lt;&lt; std::endl; } void send(std::string msg){ // Send reply back to client zmq::message_t reply (msg.size()); memcpy (reply.data (), msg.c_str(), 5); m_socket.send (reply); } private: zmq::context_t m_context; zmq::socket_t m_socket; }; void server_thread(std::shared_ptr&lt;ZmqServer&gt; zmq){ while (true) { zmq-&gt;receive(); // Do some 'work' sleep(1); // Send reply back to client zmq-&gt;send(&quot;World&quot;); } } int main () { auto zmq = std::shared_ptr&lt;ZmqServer&gt;(new ZmqServer()); zmq-&gt;Bind(&quot;tcp&quot;, 5555); auto f = std::async(std::launch::async, server_thread, std::move(zmq)); while(true){ std::cout &lt;&lt; &quot;Yay!!&quot; &lt;&lt; std::endl; f.get(); std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } return 0; </code></pre> <p>}</p> </li> </ol> <p>I want comments on the following</p> <ol> <li>overall refactoring of the code.</li> <li>The usage of std::async in this case? is it correct and appropriate</li> <li>usage of shared_ptr and std::move() in the context of thread.</li> </ol>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T06:11:51.360", "Id": "264170", "Score": "0", "Tags": [ "c++11", "asynchronous", "pthreads", "zeromq" ], "Title": "Refactoring a simple ZeroMQ Server" }
264170
<p>Very simple question. Imagine are designing library API, where you want to provide way to switch boolean flag. Typically to disable or enable a functionality. For argument's sake, let's say it's enabling/disabling sounds and I will be using kotlin in my code samples, but language doesn't really matter. I see 2 ways to put that into interface:</p> <ol> <li>Use toggle/set style:</li> </ol> <pre><code>fun setSound(enabled: Boolean) //or toogleSound </code></pre> <ol start="2"> <li>Use explicit method or each functionality:</li> </ol> <pre><code>fun enableSound() fun disableSound() </code></pre> <p>Now I can map those way easily between each other so in a sense they are equal:</p> <pre><code>fun setSound(enabled: Boolean) { if (enabled) { enableSound() } else { disabledSound() } } </code></pre> <p>Or opposite direction:</p> <pre><code>fun enableSound() { setSound(true) } fun disableSound() { setSound(false) } </code></pre> <p>First method is more friendly for programming, because you can just pass boolean variable, which can sometimes be convenient. One feedback I got here is, that in languages, that are not type-safe, this can be broken/unpredictable by passing non-boolean type.</p> <p>Second method is on the other hand more explicit, easier to read and feels better overall from designing API perspective.</p> <p>API should obviously contain only one of the options because of the DRY principle and even though I can create mapping (and extension methods in <code>kotlin</code> world), I have to choose only one. I know there are some specific things to consider (ex: what kind of library, what is likely usage of it - if there are hundreds of flags, then &quot;setter&quot; methods is most likely better), but I am looking for general guidance without many specifics.</p> <p>Which option would you choose and why? If there is another 3rd option, I'd like to hear about it too, but nothing comes to mind.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T11:55:52.850", "Id": "521742", "Score": "0", "body": "Code Review requires concrete code from a project. Pseudocode, stub code, hypothetical code are outside the scope of this site. Please [**follow the tour**](https://CodeReview.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://CodeReview.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://CodeReview.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://CodeReview.StackExchange.com/help/dont-ask)." } ]
[ { "body": "<blockquote>\n<p>One feedback I got here is, that in languages, that are not type-safe, this can be broken/unpredictable by passing non-boolean type.</p>\n</blockquote>\n<p>In such languages, you should have a type check at the beginning of the method and throw an exception if it's invalid.</p>\n<hr />\n<p>A setter has multiple benefits.</p>\n<p>First of all, <code>setEnabled</code> is turned into a property so that you can use the following:</p>\n<pre><code>object.sound = true\n</code></pre>\n<p>Secondly, I imagine that a common thing to do is to toggle the sound on/off (basically switch the current state), <strong>I would not recommend adding a <code>toggleSound</code> method that does this</strong>, it feels so much better for me as a programmer to do</p>\n<pre><code>object.sound = !object.sound\n</code></pre>\n<p>or</p>\n<pre><code>object.setSound(!object.isSound())\n</code></pre>\n<p>If the user wants to toggle the sound the user probably want to know the state that the sound is already in, and a method called <code>toggleSound</code> hides the current state so that you're not aware of it. You could have <code>toggleSound</code> return the state of course, but should it return the old state or the new state?</p>\n<p>Using the other approach I would have to do</p>\n<pre><code>if (object.isSound()) {\n object.disableSound()\n} else {\n object.enableSound()\n}\n</code></pre>\n<p>Which takes more space, is harder to read in its entirety, and is just less clean IMO.</p>\n<p>If you have a boolean property that can be true or false, using a setter is the best way to change the property instead of having two methods to <a href=\"https://www.youtube.com/watch?v=nn2FB1P_Mn8&amp;ab_channel=CamGVideos\" rel=\"nofollow noreferrer\">turn it off and on again</a>.</p>\n<hr />\n<p>However, a nitpick with regards to this is that I would consider naming it <code>setSoundEnabled</code> which makes a bit more sense to set to <code>true/false</code> than <code>setSound</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T11:15:23.983", "Id": "264179", "ParentId": "264171", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T10:16:33.733", "Id": "264171", "Score": "0", "Tags": [ "api", "kotlin" ], "Title": "API for general boolean flag set" }
264171
<p>I have the python script that creates a sqlite database and fills it with data (originally coming from a json file). At the time I execute the code below, my <code>word</code> table has about 400 000 entries.</p> <pre><code>con = sqlite3.connect(&quot;words.db&quot;) cur = con.cursor() form_of_words_to_add: &quot;list[tuple(int, str)]&quot; = [] # other code fills this list with also about 400 000 entries index = 0 for form_of_entry in form_of_words_to_add: base_word = form_of_entry[1] word_id = form_of_entry[0] unaccented_word = unaccentify(form_of_entry[1]) index += 1 cur.execute(&quot;INSERT INTO form_of_word (word_id, base_word_id) \ SELECT ?, COALESCE ( \ (SELECT w.word_id FROM word w WHERE w.word = ?), \ (SELECT w.word_id FROM word w WHERE w.canonical_form = ?), \ (SELECT w.word_id FROM word w WHERE w.word = ?) \ )&quot;, (word_id, base_word, base_word, unaccented_word)) if index == 1000: print(index) con.commit() index = 0 </code></pre> <p>The code works, but it is very slow and only achieves about 15 insertions per second. I am looking for ideas to optimize it. The bottleneck appears to be the sql query, the rest of the loop takes almost no time in comparison once I comment the SQL out. Is there anything obvious I could do to optimize this very slow process? I am having a hard time thinking of a simpler query. I already tried using PyPy, but this did not increase performance.</p> <p>The relevant entries in the database are as follows:</p> <pre><code>CREATE TABLE word ( word_id INTEGER NOT NULL PRIMARY KEY, pos VARCHAR, --here had been pos_id canonical_form VARCHAR, romanized_form VARCHAR, genitive_form VARCHAR, adjective_form VARCHAR, nominative_plural_form VARCHAR, genitive_plural_form VARCHAR, ipa_pronunciation VARCHAR, lang VARCHAR, word VARCHAR, lang_code VARCHAR ); CREATE TABLE form_of_word ( word_id INTEGER NOT NULL, base_word_id INTEGER, FOREIGN KEY(word_id) REFERENCES word(word_id), FOREIGN KEY(base_word_id) REFERENCES word(word_id) ); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T11:11:04.710", "Id": "521732", "Score": "6", "body": "Add indexes on word and canonical_form." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T11:23:23.360", "Id": "521734", "Score": "0", "body": "@PavloSlavynskyy Ooh thank you, that was very much the answer. Now the entire code ran in seven seconds, instead of the seven hours it would have taken at original speed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T12:02:59.147", "Id": "521744", "Score": "3", "body": "@PavloSlavynskyy Do you think you could add an explanation of why indexes help and expand your comment into a full answer?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T12:04:51.917", "Id": "521745", "Score": "0", "body": "Yes, but I don't have time right now. Maybe in 10 hours or so" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T14:44:58.037", "Id": "521759", "Score": "0", "body": "How is `word` populated? You show the population of `form_of_word` but not `word`. Are the contents of `form_of_words_to_add` the same as the `word` table?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T18:30:36.453", "Id": "521771", "Score": "0", "body": "@Reinderien `word` only shares the ID with the form_of_words entries, so it is probably not very useful for optimization." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T17:40:14.433", "Id": "521805", "Score": "1", "body": "There was an article posted about this topic on Hacker News recently, in case you're curious. [Article](https://avi.im/blag/2021/fast-sqlite-inserts/) and [discussion](https://news.ycombinator.com/item?id=27872575)." } ]
[ { "body": "<p>Other than @PavloSlavynskyy's correct recommendation to add indices:</p>\n<ul>\n<li>Whereas autocommit is <a href=\"https://docs.python.org/3/library/sqlite3.html#sqlite3-controlling-transactions\" rel=\"nofollow noreferrer\">off by default for the Python library</a>, I doubt your code is doing what you think it's doing because as soon as your first <code>commit</code> occurs autocommit is going to be re-enabled. Explicitly start a transaction at the beginning of your 1000-row pages to avoid this issue.</li>\n<li>Rather than manually incrementing your loop index, use <code>enumerate</code></li>\n<li><a href=\"https://docs.python.org/3/library/sqlite3.html#using-the-connection-as-a-context-manager\" rel=\"nofollow noreferrer\">SQLite connection objects are context managers</a> - so use a <code>with</code>.</li>\n<li>Rather than</li>\n</ul>\n<pre><code> base_word = form_of_entry[1]\n word_id = form_of_entry[0]\n</code></pre>\n<p>you should unpack:</p>\n<pre><code>word_id, base_word = form_of_entry\n</code></pre>\n<ul>\n<li>Your code is going to miss a commit for the last segment of words in all cases except the unlikely one that the total number of words is a multiple of 1000. A trailing <code>commit()</code> should fix this.</li>\n<li>Rather than modulating your index, consider just having a nested loop - which also would need neither an outside <code>commit</code> nor <code>enumerate</code>. There are many ways to do this, but basically:</li>\n</ul>\n<pre><code>for index in range(0, len(form_of_words_to_add), 1000):\n cur.execute('begin')\n for word_id, base_word in form_of_words_to_add[index: index+1000]:\n cur.execute('insert ...')\n con.commit()\n</code></pre>\n<ul>\n<li>Rather than doing individual, filtered inserts into the destination table, consider doing your inserts unfiltered into a <a href=\"https://sqlite.org/lang_createtable.html\" rel=\"nofollow noreferrer\">temporary table</a>, keeping them to the &quot;literal&quot; data (no <code>where</code> etc.). After all of the inserts are done, follow it with one single statement using proper <code>join</code>s, roughly looking like</li>\n</ul>\n<pre class=\"lang-sql prettyprint-override\"><code>insert into form_of_word(word_id, base_word_id)\nselect tw.word_id, w.word_id\nfrom word w\njoin temp_words tw on (\n w.canonical_form = tw.base_word\n or w.word = tw.base_word\n or w.word = tw.unaccented_word\n)\n</code></pre>\n<p>This temporary table can be told to <a href=\"https://sqlite.org/pragma.html#pragma_temp_store\" rel=\"nofollow noreferrer\">live in memory via pragma</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T18:26:26.903", "Id": "521770", "Score": "1", "body": "Thank you very much for the answer! I implemented all of your suggestions except the temporary tables so far and got from 7 seconds (achieved after adding the indexing) to 4 seconds. I think the committing worked fine in my version of sqlite, when I accessed it through another DB navigator it updated exactly in the 1000-intervals." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T20:02:15.743", "Id": "521774", "Score": "1", "body": "You could also try enabling wal mode. That can sometimes speed things up significantly. See https://sqlite.org/wal.html" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T13:58:20.170", "Id": "264182", "ParentId": "264172", "Score": "7" } }, { "body": "<h3 id=\"indexes-9tff\">Indexes!</h3>\n<p>Tables basically has array-like access: to find something, an engine should check all the values in a table. If you have a big table, this can be slow. But there's a solution: indexes. Database indexes work pretty much like book indexes, helping to find information quickly. But indexes are not free, they use some time and space too. So you should add indexes only for fields (or expressions) you're using to find data, in this case - <code>word</code> and <code>canonical_form</code>:</p>\n<pre><code>CREATE INDEX word_word_index ON word(word);\nCREATE INDEX word_canonical_form_index ON word(canonical_form);\n</code></pre>\n<p>Keys are indexed by default. You can find more information about indexes on <a href=\"https://www.sqlite.org/lang_createindex.html\" rel=\"noreferrer\">SQLite site</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T04:24:34.000", "Id": "264198", "ParentId": "264172", "Score": "5" } }, { "body": "<h1 id=\"split-the-data-o14x\">Split the data</h1>\n<p>When you are inserting, use <a href=\"https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool\" rel=\"nofollow noreferrer\"><code>multiprocessing.Pool()</code></a> to distribute the workload by parallelising it = you push more data within the same time</p>\n<h1 id=\"why-1000-yqs2\">Why 1000?</h1>\n<p>Don't use own <code>1000</code> limit, SQLite and other DBs allow <em><strong>much much more</strong></em>. Instead check the <a href=\"https://sqlite.org/limits.html\" rel=\"nofollow noreferrer\"><code>SQLITE_MAX_SQL_LENGTH</code></a> and other limits to assemble queries <strong>efficiently</strong> as in push as much data as possible so it's:</p>\n<ol>\n<li>quick on your network (if non-SQLite)</li>\n<li>quick with your computer</li>\n</ol>\n<p>You'll need to measure the time with e.g. inserting 1k-10k rows while adjusting the number of processes and inserted rows in a single query.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T10:35:39.650", "Id": "264202", "ParentId": "264172", "Score": "2" } } ]
{ "AcceptedAnswerId": "264182", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T10:19:00.067", "Id": "264172", "Score": "4", "Tags": [ "python", "performance", "sql", "sqlite" ], "Title": "Optimizing the insertion of 400 000 records in sqlite" }
264172
<p>To divide 9 persons into 3 groups, when the ordering of groups is not important can be done in</p> <p>(9C3 * 6C3 * 3C3) / (3!) = 280 ways</p> <p>Here, we divide by (3!) because the ordering of 3 groups is not important</p> <h2 id="what-i-did-jo81">What I did?</h2> <ol> <li>Gather all the permutations from the given array.</li> <li>While grouping the combinations, discard the hands that has been traversed.</li> </ol> <pre><code>function generatePermutations(array, size) { const result = []; function permutation(target, i) { if (target.length === size) { result.push(target); return; } if (i + 1 &gt; array.length) return; permutation(target.concat(array[i]), i + 1); permutation(target, i + 1); } permutation([], 0); return result; } function createCombinationsBag() { let travsedCombinationIdentity = 0; const traversedCombinationMap = new Map(); let travsedCombinationsIdentity = 0; const traversedCombinationsMap = new Map(); function getCombinationId(arrNums) { const reordered = arrNums.slice().sort().join(&quot;&quot;); const combinationId = traversedCombinationMap.get(reordered); if (combinationId) return combinationId; travsedCombinationIdentity++; traversedCombinationMap.set(reordered, travsedCombinationIdentity); return travsedCombinationIdentity; } function isCombinationTraversed(firstId, secondId, thirdId) { const reordered = [firstId, secondId, thirdId].sort().join(&quot;&quot;); const combinationsId = traversedCombinationsMap.get(reordered); if (combinationsId) return true; travsedCombinationsIdentity++; traversedCombinationsMap.set(reordered, travsedCombinationsIdentity); return false; } function has(first, second, third) { return isCombinationTraversed( getCombinationId(first), getCombinationId(second), getCombinationId(third) ); } return { has }; } export function generateCombinations(array, size) { const allPermutations = generatePermutations(array, size); const combinations = []; const CombinationBag = createCombinationsBag(); for (let i = 0; i &lt; allPermutations.length; i++) { const first = allPermutations[i]; for (let j = 0; j &lt; allPermutations.length; j++) { const second = allPermutations[j]; const firstSecond = first.concat(second); if (firstSecond.length !== new Set(firstSecond).size) continue; for (let k = 0; k &lt; allPermutations.length; k++) { const third = allPermutations[k]; const maybeCombination = firstSecond.concat(third); const combinationSet = new Set(maybeCombination); if (maybeCombination.length === combinationSet.size) { if (CombinationBag.has(first, second, third)) continue; combinations.push(maybeCombination); } } } } return combinations; } console.log(generateCombinations([0, 1, 2, 3, 4, 5, 6, 7, 8], 3).length); // 280 </code></pre> <p>Is there a better and optimize way to do this?</p> <p>Rather than finding all the permutations of group and then looping over them, could there be a solution where we could reach to solution much quicker than this.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T05:00:33.990", "Id": "521829", "Score": "0", "body": "I have absolutely no idea what the program is supposed to do. Finding some kind of combinations is as far as I understood. The rest is in fog. Do you have any formal specification for the problem? Or at least can you show a complete example output and describe why it is what it is?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T15:38:22.130", "Id": "521853", "Score": "0", "body": "According to the title: k is the size (with of?) the array. According to the 1st sentence: k is the size of the groups (each group in the array?).\n\n.. which would mean there is exactly one group in the array (which is silly).\n\nIt feels like there's a fun problem here and I had hoped I could reverse engineer the problem statement into something sensible, but somehow the description managed to become utterly unintelligible (to me). Please rephrase the question accurately because it still seems something that could be interesting." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-22T04:52:34.517", "Id": "521896", "Score": "0", "body": "@slepic I've updated the question. Please consider it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-22T04:52:52.907", "Id": "521897", "Score": "1", "body": "@KoenAIS I've updated the question. Please consider it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-22T13:29:38.083", "Id": "521934", "Score": "0", "body": "Your update is great, well done! \nHere's my approach (it doesn't need to generate all permutations or checks for double counts). The crux is to distinguish between 3C2 cases: 1) all first 3 persons in the 1st group, 2) 1st person in the 1st group, the next two both in the 2nd, 3) 1st person the the 1st group, 2nd person in in the 2nd group and 3rd person in the 3rd group. These cases can't yield double-counts, eliminating the need to check. After this is it just becomes a recursive problem with independent subproblems. If this is not fully clear I can elaborate and make it an answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-22T14:07:43.987", "Id": "521938", "Score": "0", "body": "@KoenAIS Honestly, the above thing just went top of my head. I would appreciate a working answer if it wasn't much of a ask." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-22T14:21:07.313", "Id": "521941", "Score": "0", "body": "Ok, but not sooner than tomorrow (it's late here)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-23T03:26:01.730", "Id": "521975", "Score": "0", "body": "@Prateek Thapa I've explained it in more detail in the form of an answer. I made it a simpler (non-optimized) version of the algorithm that I sketched in yesterdays comment. If you're interested in the optimized version, have a look at the edit-history (because I deleted it). The optimized version is about 10 times as fast, but has the downside that its correctness is a bit harder to understand." } ]
[ { "body": "<p>The problem is metaphorically to assign 9 persons to 9 seats (each person their own seat). The seats come in groups of 3.</p>\n<p>There are 362880 seating arrangements, but only 280 canonical ones because:</p>\n<ul>\n<li><p>A) Reseating the persons within one group doesn't essentially change\nthe arrangement.</p>\n</li>\n<li><p>B) Reordering the groups also doesn't essentially change\nthe arrangement.</p>\n</li>\n</ul>\n<p>The idea is to generate only the canonical permutations, so let's express A and B a bit more precise by imposing an ordering. Let P[1..9] be a permutation of [1..9] (a seating arrangement). It is canonical if:</p>\n<ul>\n<li>A) P[1..3], P[4..6] and P[7..9] are sorted</li>\n<li>B) P[1] &lt; P[4] &lt; P[7]</li>\n</ul>\n<p>Generating only the permutations that satisfy A and B avoids the overhead of generating (and checking) 362880 - 280 &quot;duplicates&quot;. An easy way to do this is to recursively assign persons to seats in lexicographic order while keeping a close eye on A and B.</p>\n<p>That's roughly the algorithm done. All that's left is to pick a language and implement it. I chose Java:</p>\n<pre><code>N = 0;\nboolean[] needsASeat = new boolean[10];\nArrays.fill(needsASeat, true);\nseatPersons(0, needsASeat, new int[9]);\nif (N != 280) throw new SanityCheckFailed();\n</code></pre>\n<p>where</p>\n<pre><code>void seatPersons(int seatIdx, boolean[] needsASeat, int[] seatingArrangement) {\n if (seatIdx &lt; 9) { // this seat is still unoccupied\n // pick each person who still needs a seat and is allowed to sit here (i.e., without violating A and B)\n int minPersonIdx;\n if (seatIdx % 3 != 0) // A is at stake\n minPersonIdx = seatingArrangement[seatIdx - 1] + 1;\n else if (seatIdx != 0) // B is at stake\n minPersonIdx = seatingArrangement[seatIdx - 3] + 1;\n else\n minPersonIdx = 1; // this is also the maximum, but there's no need for tricky optimizations\n for (int personIdx = minPersonIdx; personIdx &lt;= 9; personIdx++) if (needsASeat[personIdx]) {\n seatingArrangement[seatIdx] = personIdx;\n needsASeat[personIdx] = false;\n seatPersons(seatIdx + 1, needsASeat, seatingArrangement);\n needsASeat[personIdx] = true;\n seatingArrangement[seatIdx] = 0;\n }\n } else { // all seats occupied\n // do sth with the arrangement\n N++;\n }\n}\n</code></pre>\n<p>PS: an earlier version of this answer gives a more efficient implementation by starting in initial configurations in which first seats of groups are already occupied. In realized afterwards I had made that optimization unconsciously without even explaining why it works and why it is faster. This new version is significantly slower but it explains the algorithm clearer and is still must faster than the &quot;check all permutations&quot;-approach.</p>\n<hr />\n<p>Never mind. Here's that optimized version:</p>\n<pre><code>N = 0;\n// partition the set of canonical permutations by &quot;pre-seating&quot; 1, 2 and 3:\nint[][] startingPoints = new int[][]{\n {1, 2, 3, 4, 0, 0, 0, 0, 0}, // 1,2,3 together\n {1, 2, 0, 3, 0, 0, 0, 0, 0}, // 1,2 together, 3 alone\n {1, 0, 0, 2, 3, 0, 0, 0, 0}, // 1 alone, 2,3 together\n {1, 3, 0, 2, 0, 0, 0, 0, 0}, // 2 alone, 1,3 together\n {1, 0, 0, 2, 0, 0, 3, 0, 0} // each alone\n};\nboolean[] needsASeat = new boolean[10];\nfor (int[] startingPoint : startingPoints) {\n Arrays.fill(needsASeat, true);\n for (int p : startingPoint) needsASeat[p] = false;\n seatPersons(0, needsASeat, startingPoint);\n}\nif (N != 280) throw new SanityCheckFailed();\n</code></pre>\n<p>where</p>\n<pre><code>void seatPersons(int seatIdx, boolean[] needsASeat, int[] seatingArrangement) {\n while (seatIdx &lt; 9 &amp;&amp; seatingArrangement[seatIdx] != 0) seatIdx++; // skip occupied seats\n if (seatIdx &lt; 9) {\n int minPersonIdx = seatIdx % 3 != 0 ? seatingArrangement[seatIdx - 1] + 1 : 4; // B is never at stake thanks to the initial configuration\n for (int personIdx = minPersonIdx; personIdx &lt;= 9; personIdx++) if (needsASeat[personIdx]) {\n seatingArrangement[seatIdx] = personIdx;\n needsASeat[personIdx] = false;\n seatPersons(seatIdx + 1, needsASeat, seatingArrangement);\n needsASeat[personIdx] = true;\n seatingArrangement[seatIdx] = 0;\n }\n } else {\n // do sth with the arrangement\n N++;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T15:37:38.643", "Id": "264242", "ParentId": "264178", "Score": "1" } } ]
{ "AcceptedAnswerId": "264242", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T11:06:41.567", "Id": "264178", "Score": "2", "Tags": [ "javascript", "algorithm", "combinatorics" ], "Title": "In how many different ways can a group of 9 people be divided into 3 groups, with each group containing 3 people?" }
264178
<p>Am writing a bash function to run <code>rsync</code>, with possibility of using <code>--dry-run</code> option and <code>--exec</code> option. Need some criticism improvements and additional checks.</p> <p>Might not make much sense for the user to specify both <code>--dry-run</code> and <code>--exec</code>. I would simply use --dry-run anyway.</p> <p>Have started with the following setup.</p> <pre><code>filetr-archive () { # Process command line options shortopts=&quot;nel:s:d:&quot; longopts=&quot;dry-run,exec,log:,source:,destin:&quot; opts=$(getopt -o &quot;$shortopts&quot; -l &quot;$longopts&quot; \ -n &quot;$(basename $0)&quot; -- &quot;$@&quot;) if [ $? -eq 0 ]; then eval &quot;set -- ${opts}&quot; while [ $# -gt 0 ]; do case &quot;$1&quot; in -n|--dry-run) shift 1 local -r dryrun=1 ;; -e|--exec) shift 1 local -r exec=1 ;; -l|--log) local logfl=$2 shift 2 ;; -s|--source) local source=$2 shift 2 ;; -d|--destin) local destin=$2 shift 2 ;; --) shift; break ;; esac done else shorthelp=1 # getopt returned (and reported) an error. fi if (( filetr_dryrun == 1 )); then echo &quot;rsync -av --progress --log-file=$logfl --dry-run&quot; echo &quot; $source $destin&quot; rsync -av --progress --log-file=$logfl --dry-run $source $destin elif (( filetr_exec == 1 )); then # use rsync archive option -a (equivalent to -rlptgoD) echo &quot;rsync -av --progress --log-file=$logfl $source $destin&quot; # rsync -av --progress --log-file=$logfl $source $destin else echo &quot;rsync -av --progress --log-file=$logfl $source $destin&quot; fi </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T12:10:23.047", "Id": "521746", "Score": "1", "body": "What does your script do?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T11:21:30.433", "Id": "264180", "Score": "0", "Tags": [ "bash", "optional" ], "Title": "Bash function with dry-run and exec options" }
264180
<p>I'm going to start out by saying this is the 1st python program I have ever written and have no real background in the language so my code is probably pretty rough. Take it easy on me!</p> <p>When I wrote this it works fine for a small number of tickers but when I have a file with 6k+ it is very slow. Now I know there are other ways I can improve performance BUT I want to try and tackle the async thing first.</p> <p>I thought it was as simple as making the read_ticker_file function async and adding await in front of the yfin_options() call but obviously that didn't work.</p> <p>I'm thinking possibly I need to restructure the way things are called but kind of stuck here. Hoping someone can point me in the right direction! Thanks in advance</p> <pre><code>import logging import pyodbc import config import yahoo_fin as yfin from yahoo_fin import options from datetime import datetime, date from selenium import webdriver def main(): read_ticker_file() def init_selenium(): driver = webdriver.Chrome(config.CHROME_DRIVER) return driver def yfin_options(symbol): logging.basicConfig(filename='yfin.log', level=logging.INFO) logging.basicConfig(filename='no_options.log', level=logging.ERROR) try: # get all options dates (in epoch) from dropdown on yahoo finance options page dates = get_exp_dates(symbol) # iterate each date to get all calls and insert into sql db for date in dates: arr = yfin.options.get_calls(symbol, date) arr_length = len(arr.values) i = 0 for x in range(0, arr_length): strike = str(arr.values[i][2]) volume = str(arr.values[i][8]) open_interest = str(arr.values[i][9]) convert_epoch = datetime.fromtimestamp(int(date)) try: sql_insert(symbol, strike, volume, open_interest, convert_epoch) i += 1 except Exception as insert_fail: print(&quot;I failed at sqlinsert {0}&quot;.format(insert_fail)) file_name_dir = &quot;C:\\temp\\rh\\options{0}{1}.xlsx&quot;.format(symbol, date) logging.info(arr.to_excel(file_name_dir)) except Exception as e: bad_tickers_file_dir = config.BAD_TICKERS f = open(bad_tickers_file_dir, &quot;a&quot;) f.write(symbol) f.write('\n') def sql_insert(symbol, strike, volume, open_interest, exp_date): conn_string = ('Driver={SQL Server};' 'Server={0};' 'Database={1};' 'Trusted_Connection=yes;').format(config.SERVER, config.DATABASE) conn = pyodbc.connect(conn_string) cursor = conn.cursor() insert_string = &quot;&quot;&quot;INSERT INTO dbo.options (Ticker, Strike, Volume, OpenInterest, expDate) VALUES (?, ?, ?, ?, ?)&quot;&quot;&quot; cursor.execute(insert_string, symbol, strike, volume, open_interest, str(exp_date)) conn.commit() def get_exp_dates(symbol): url = &quot;https://finance.yahoo.com/quote/&quot; + symbol + &quot;/options?p=&quot; + symbol chromedriver = init_selenium() chromedriver.get(url) # Yahoo Finance options dropdown class name (find better way to do this) select_dropdown = chromedriver.find_element_by_css_selector(&quot;div[class='Fl(start) Pend(18px)'] &gt; select&quot;) options_list = [x for x in select_dropdown.find_elements_by_tag_name(&quot;option&quot;)] dates = [] for element in options_list: dates.append(element.get_attribute(&quot;value&quot;)) return dates def read_ticker_file(): file1 = open(config.TICKER_FILE, 'r') lines = file1.readlines() count = 0 # loop to read each ticker in file for line in lines: count += 1 line = line.strip('\n') line = line.strip() yfin_options(line) if __name__ == &quot;__main__&quot;: main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T18:09:43.483", "Id": "521767", "Score": "1", "body": "Just to be sure (in addition to your remark), you're aware that, at best, ``async`` will still be single-threaded, right? It's definitely something worth learning, but it's primarily intended to allow a single thread to run multiple tasks where some may be blocked by IO at any given moment. Just want to make sure that's what you want to learn about." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T18:10:57.720", "Id": "521768", "Score": "1", "body": "BTW, this might get closed since your code is technically non-working (it doesn't do what you want it to do, since you want it to be ``async``.) You might get better results asking this over at Stack Overflow, then come back here once you have the code you want and you just want to know how to make it better/cleaner/nicer/more Pythonic/etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T23:33:21.543", "Id": "521779", "Score": "0", "body": "@scnerd I know the concept of how async works and I think I can use that to my advantage in this case. So I am utilizing selenium to initialize chrome driver and load a web page. I was thinking that I could use the async wait functionality to pause the execution while the web page loaded and spin up another one in the background." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T02:23:36.100", "Id": "521780", "Score": "0", "body": "I would encourage you to change you strategy for learning parallelism in Python. Start with the basics: writing programs that use multiple processes or threads (learn both and why you would choose one or the other). The place to start that is the multiprocessing module. Then learn async, which generally applies to a narrower range of real-world situations -- at least in my experience writing programs making many internet requests and/or DB calls." } ]
[ { "body": "<p>After doing some reading and taking the advice of FMc, I decided against async for what I was doing.</p>\n<p>I ended up with multi-processing</p>\n<pre><code>pool = multiprocessing.Pool()\n\n# input list\ninputs = read_ticker_file()\n# pool object with number of element\npool = multiprocessing.Pool(processes=4)\n\npool.map(yfin_options, inputs)\n\npool.close()\npool.join()\n</code></pre>\n<p>I've noticed some weird behavior but we'll see if it gets the same result more quickly when it's done running.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T11:43:41.510", "Id": "264205", "ParentId": "264185", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T14:16:33.607", "Id": "264185", "Score": "3", "Tags": [ "python", "beginner", "asynchronous", "asyncio" ], "Title": "Converting python code to async calls" }
264185
<p>I'm coding this program that allows you to encrypt files using vernam cipher in C language. I would be glad if you could inspect my code and tell me if I can make some improvements to it or if there are any error.</p> <p>The request they gave me is:</p> <blockquote> <p><em>The goal is to develop a simple application that allows you to encrypt files using a variant of the Vernam cipher, here called bvernan. The proposed algorithm exploits a simple property of the binary operator XOR: (A XOR B) XOR B = A Given a sequence of k-bytes b0 ... bk-1 (called key), the encoding function of a sequence of bytes d0 ... dN, the encoding / decoding function follows the following simple procedure. The sequence d0 ... dN is first divided into N / k blocks (integer division), D0, ..., D [(N / k) -1] each of which consists of exactly k bytes (apart from the 'last sequence which, obviously, may contain a smaller number of bytes). Subsequently each sequence Dj = dj, 0 ... dj, k-1 is transformed into the sequence D'j = d'j, 0 ... d'j, k-1 such that for each i: d'j, i = b (j + i) mod k XOR dj, i That is, the byte in position i of block j is placed in XOR with the byte (j + i) mod k of the key. The output sequence will then be obtained from the juxtaposition of the sequences D'0, ..., D '[(N / k) -1].</em></p> </blockquote> <p>This is the code:</p> <h3 id="file-main.c-i8cu">file main.c</h3> <pre><code>#include &quot;encode.h&quot; int main (int argc ,char** argv){ if(argc!=4){ printf(&quot;Usage: bvernan keyfile inputfile outputfile \n&quot;); return 1; } Key_t* key=openKey(argv[1]); Register_t* file=openFile(argv[2],argv[3],key-&gt;lenght); encode(file,key); closeRegister(file); freeKey(key); printf(&quot;Success!\n&quot;); } </code></pre> <h3 id="file-encode.c-8dgj">file encode.c</h3> <pre><code>#include &quot;encode.h&quot; int encode (Register_t* file, Key_t* key ){ while(readF(file)&gt;0){ encodeDivision(file-&gt;buffer,file-&gt;bufferLenght,key); writeF(file); } } void encodeDivision (unsigned char* block,long lenght,Key_t*key){ for(int i=0;i&lt;lenght;i++){ block[i]=block[i]^key-&gt;buffer[i]; } } </code></pre> <h3 id="file-encode.h-uame">file encode.h</h3> <pre><code>#include &quot;key.h&quot; #include &quot;register.h&quot; int encode (Register_t* file, Key_t* key ); void encodeDivision (unsigned char* block,long lenght,Key_t*key); </code></pre> <h3 id="file-key.c-plpp">file key.c</h3> <pre><code>#include &quot;key.h&quot; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; long keySize (FILE* file){ fseek (file,0,SEEK_END); long size=ftell(file); rewind (file); return size; } Key_t* openKey(char* path){ Key_t* kFile= malloc (sizeof(Key_t)); FILE*file= fopen(path,&quot;rb&quot;); kFile-&gt;lenght=keySize(file); kFile-&gt;buffer= malloc(kFile-&gt;lenght); fread(kFile-&gt;buffer,1,kFile-&gt;lenght,file); fclose(file); return kFile; } void freeKey (Key_t* key ){ free (key-&gt;buffer); free (key); } </code></pre> <h3 id="file-key.h-ij5y">file key.h</h3> <pre><code>typedef struct Key { unsigned char* buffer; long lenght; } Key_t; Key_t* openKey(char* path); void freeKey (Key_t*); </code></pre> <h3 id="file-register.c-q8rk">file register.c</h3> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &quot;register.h&quot; Register_t* openFile (char* inPath,char* outPath,long bufferLenght){ Register_t* file = malloc (sizeof(Register_t)); file-&gt;buffer= malloc(bufferLenght); file-&gt;bufferLenght=bufferLenght; file-&gt;fdIn= fopen(inPath,&quot;rb&quot;); file-&gt;fdOut= fopen(outPath,&quot;wb&quot;); if(file-&gt;fdOut==NULL || file-&gt;fdIn==NULL){ return NULL; } return file; } int readF (Register_t* file){ int readbyte = fread(file-&gt;buffer,1,file-&gt;bufferLenght,file-&gt;fdIn); file-&gt;bufferLenght=readbyte; return readbyte; } int writeF (Register_t* file){ int writebyte = fwrite(file-&gt;buffer,1,file-&gt;bufferLenght,file-&gt;fdOut); return writebyte; } void closeRegister (Register_t* file){ free(file-&gt;buffer); fclose(file-&gt;fdIn); fclose(file-&gt;fdOut); free(file); } </code></pre> <h3 id="file-register.h-awep">file register.h</h3> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; typedef struct Register { unsigned char *buffer; FILE *fdIn; FILE *fdOut; long bufferLenght; } Register_t; Register_t *openFile(char *inPath, char *outPath, long bufferLenght); int readF(Register_t *); int writeF(Register_t *); void closeRegister(Register_t *); </code></pre> <h3 id="file-makefile-1l1t">file Makefile</h3> <pre><code>all: bvernan bvernan: encode.o key.o main.o register.o gcc -o bvernan $^ %.o: %.c gcc -c $&lt; clean: rm *.o bvernan </code></pre>
[]
[ { "body": "<blockquote>\n<p>if I can make some improvements to it or if there are any error.</p>\n</blockquote>\n<p><strong>Lack of error checking</strong></p>\n<p><code>fopen(), malloc(), ftell(), fread()</code>, (all I/O functions), etc. deserve to have their return values checked for errors.</p>\n<p>In particular when a file may fail to open or memory fail to allocate, handle such cases to not forget the other. e. g.: do not forget to <code>fclose()</code>, or <code>fclose()</code> twice when memory allocation failed.</p>\n<p>Gracefully handling errors and still maintaining nice code flow is challenging.</p>\n<p><strong>Lack of comments</strong></p>\n<p><em>some</em> comments would help, especially in .h files. A header files is sometimes all a user sees (or cares to see) .</p>\n<p><strong>.h files</strong></p>\n<p>Missing code guards.</p>\n<p>Reduce namespace scattering. Recommend a common prefix per objects in a .h file</p>\n<p><strong>Types</strong></p>\n<p><code>long</code> OK for most files sizes. <code>size_t</code> better for array sizing and indexing.</p>\n<p><code>long lenght ... for(int i=0;i&lt;lenght;i++)</code> --&gt; <code>i</code> and <code>length</code> should be the same type: <code>size_t</code>.</p>\n<p><strong>Style</strong></p>\n<p>Use an auto formatter to improve code appearance at less time cost.</p>\n<p><strong>Tolerant free</strong></p>\n<p>Note that <code>free(NULL)</code> is well defined. Do so like-wise for <code>freeKey(NULL);</code></p>\n<p><strong>Spelling</strong></p>\n<p><code>lenght</code> --&gt; <code>length</code>.</p>\n<p><strong>Spaces</strong></p>\n<p>Style is very dense left=to=right. Some spaces would help.</p>\n<pre><code>// block[i]=block[i]^key-&gt;buffer[i];\nblock[i] = block[i] ^ key-&gt;buffer[i];\n</code></pre>\n<p><strong>Include order</strong></p>\n<p>For xxx.c, I recommend including xxx.h first, to help test its ability to stand alone.</p>\n<pre><code>// file register.c\n\n#include &quot;register.h&quot; // Put first\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n</code></pre>\n<p>Unclear why <code>register.h</code> has <code>#include &lt;stdlib.h&gt;</code>. Excessive <code>#include</code> files in a .c file have their place and are not so much a timely concern. (Some coding environments offer a check.)</p>\n<p>.h file should use a minimal set.</p>\n<p><strong>Naming</strong></p>\n<p>Consider using the same <em>case</em> and order for the names <code>key.c, Key_t</code> --&gt; <code>key.c, key_t</code>. <code>keySize(), openKey()</code> --&gt; <code>keySize(), keyOpen()</code>.</p>\n<p><strong>Allocating</strong></p>\n<p>Rather than size by <em>type</em>, size by the referenced object. Easier to code right, review and maintain.</p>\n<pre><code>// ptr = malloc(sizeof(hopefully_the_right_type));\nptr = malloc(sizeof *ptr);\n</code></pre>\n<hr />\n<p><strong><em>Simplistic</em> error handling examples</strong></p>\n<pre><code>FILE*file = fopen(path,&quot;rb&quot;);\nif (file == NULL) {\n fprintf(stderr, &quot;Unable to open file &lt;%s&gt; for reading.\\n&quot;, path);\n exit EXIT_FAILURE;\n}\n\nKey_t* kFile = malloc(sizeof *kFile);\nif (kFile == NULL) {\n fprintf(stderr, &quot;Out of memory.\\n&quot;);\n exit EXIT_FAILURE;\n}\n\nlong size = ftell(file);\nif (size == -1 || size &gt; SIZE_MAX) {\n fprintf(stderr, &quot;File size problem %ld.\\n&quot;, size);\n exit EXIT_FAILURE;\n}\n</code></pre>\n<p><strong>Allow <code>freeKey(NULL)</code></strong></p>\n<p>This allows calls to <code>freeKey(k)</code> without first checking if <code>k</code> is non-null, just like <code>free(NULL)</code> is allowed. Having a check inside <code>freeKey(NULL)</code> allows for simply calls to it, especially if the higher level code itself is in some error recovery block.</p>\n<pre><code>void freeKey(Key_t* key) {\n if (key) { // add\n free (key-&gt;buffer);\n free (key);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T15:47:54.717", "Id": "521854", "Score": "0", "body": "could you add an example for error checking?\ni dont get it what you mean with code guards in .h files.\nsorry im not so expert in C language" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T15:55:38.333", "Id": "521856", "Score": "1", "body": "@Somakun See [include guard](https://en.wikipedia.org/wiki/Include_guard#Use_of_#include_guards). Error checking example later." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T23:45:04.003", "Id": "521882", "Score": "0", "body": "ok i got it. i successfully added code guards. you link was really helpful. could you give me help with error checking?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-22T00:01:02.513", "Id": "521884", "Score": "0", "body": "i also didn't understand what you mean when you talked about free(NULL) well defined" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-22T13:42:04.407", "Id": "521936", "Score": "1", "body": "@Somakun Done.." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T19:41:44.023", "Id": "264192", "ParentId": "264187", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T16:39:27.527", "Id": "264187", "Score": "2", "Tags": [ "c", "file", "vigenere-cipher", "encryption" ], "Title": "encrypt files using a variant of Vernam Cipher in C language" }
264187
<p>I try to solve some old Codeforces questions. The problem is;</p> <blockquote> <p>Petya once wrote a sad love song and shared it to Vasya. The song is a string consisting of lowercase English letters. Vasya made up q questions about this song. Each question is about a subsegment of the song starting from the l-th letter to the r-th letter. Vasya considers a substring made up from characters on this segment and repeats each letter in the subsegment k times, where k is the index of the corresponding letter in the alphabet. For example, if the question is about the substring &quot;abbcb&quot;, then Vasya repeats letter 'a' once, each of the letters 'b' twice, letter 'c&quot; three times, so that the resulting string is &quot;abbbbcccbb&quot;, its length is 10. Vasya is interested about the length of the resulting string.</p> <p>Help Petya find the length of each string obtained by Vasya.</p> <p>Input The first line contains two integers n and q (1≤n≤100000, 1≤q≤100000) — the length of the song and the number of questions.</p> <p>The second line contains one string s — the song, consisting of n lowercase letters of English letters.</p> <p>Vasya's questions are contained in the next q lines. Each line contains two integers l and r (1≤l≤r≤n) — the bounds of the question.</p> <p>Output Print q lines: for each question print the length of the string obtained by Vasya.</p> <p>Example input:</p> <pre class="lang-none prettyprint-override"><code>7 3 abacaba 1 3 2 5 1 7 </code></pre> <p>Corresponding output:</p> <pre class="lang-none prettyprint-override"><code>4 7 11 </code></pre> </blockquote> <p>I used C++ to solve with dynamic programming and it works, but I am getting timeouts. Therefore, I need suggestions to decrease execution time.</p> <h3 id="my-code-4fi9">My code:</h3> <pre><code>#include&lt;bits/stdc++.h&gt; using namespace std; #define PII pair&lt;int,int&gt; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); map&lt;char, int&gt; alph; string latin = &quot;abcdefghijklmnopqrstuvwxyz&quot;; for(int x = 0; x &lt; (int)latin.length(); x++) alph[latin[x]] = x + 1; int n, q; cin &gt;&gt; n &gt;&gt; q; string s; cin &gt;&gt; s; vector&lt;int&gt; results; map&lt;string, int&gt; memo; for(int k = 0; k &lt; q; k++){ int l,r, length; length = 0; cin &gt;&gt; l &gt;&gt; r; if(memo.find(s.substr(l-1, r - l + 1)) == memo.end()){ for(int b= l-1; b &lt; r; b++){ length += alph[s[b]]; } memo[s.substr(l-1, r - l + 1)] = length; } else length = memo[s.substr(l-1, r - l + 1)]; results.push_back(length); } for(auto b: results) cout &lt;&lt; b &lt;&lt; &quot;\n&quot;; } </code></pre> <h3 id="my-notes-zet3">My notes:</h3> <ol> <li>I think that I have successfully implemented DP with my code.</li> <li>I have named the variables are according to problem requirements, not arbitrarily.</li> </ol>
[]
[ { "body": "<h3 id=\"algorithm-snpf\">Algorithm</h3>\n<p>The idea, at a first glance, is to calculate some index on a string to make all queries as fast as possible.\nThe second glance gives that <span class=\"math-container\">\\$length(l,r)=length(0,r)-length(0,l-1)\\$</span>. Just precalculate an array of <span class=\"math-container\">\\$length(0,i)\\$</span> (it can be done in a single loop) and return the difference on a query.</p>\n<h3 id=\"wrong-use-of-a-map-h3q2\">Wrong use of a map</h3>\n<pre><code>map&lt;char, int&gt; alph;\n</code></pre>\n<p>is a bad idea. Map is a tree structure; would you write a code for a tree for this matter? If not, map should not be used. Here, it is much easier and faster to use an array, subtracting 'a' from index:</p>\n<pre><code>int alph['z'-'a'+1];\n...\nalph[latin[x]-'a'] = x+1;\n...\nlength += alph[s[b]-'a'];\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T14:36:42.073", "Id": "521794", "Score": "1", "body": "We don't even need `alph` at all: `length += s[b] + 1 - 'a'`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T18:53:35.150", "Id": "521806", "Score": "0", "body": "Saying using `map` is a bad idea is a bit strong (it's not the best idea given the problem). I would have used map to start with. Then I could verify the result. Swapping the map out for an array is then trivial (now that you can easily test that your new array and map can generate the same results). I would say it is easier to use the map (the array unless wrapped) requires some index manipulation and validation but probably faster to use the array." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T07:14:08.720", "Id": "521832", "Score": "0", "body": "Actually, on second thoughts, the `alph` lookup is good for portability (though I would make it an array of size `UCHAR_MAX`). The code here with subtraction won't work with environments where the Latin letters are non-contiguous (notably EBCDIC systems)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T19:26:38.420", "Id": "521874", "Score": "1", "body": "@TobySpeight There are two hard things in computer science: *cache invalidation, naming things, and off-by-one errors.*" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T19:18:36.143", "Id": "264190", "ParentId": "264189", "Score": "4" } }, { "body": "<p>Include the necessary <em>standard</em> headers; don't use compiler's internal private header.</p>\n<p>Don't <code>using namespace std;</code>.</p>\n<p>Prefer a <code>using</code> alias to the macro. Actually, nix the macro completely, since it's unused.</p>\n<p>Get rid of the function call that always returns the same value in <code>for</code> loop test.</p>\n<p>When streaming from an input, ensure that failure is considered (either by testing the stream's state after reading, or setting it to throw exceptions).</p>\n<p>Print results as they are computed - no need to store them all and print at the end.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T18:55:33.510", "Id": "521808", "Score": "0", "body": "Using `istream::exceptions()` is very esoteric. Easier to just test the state of the stream after a read." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T07:02:00.730", "Id": "521830", "Score": "0", "body": "I wouldn't call it esoteric; arguably it's easier and could well have been the default, rather than having to check status after each operation as we do in C. But I've edited anyway to mention both styles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T18:38:52.823", "Id": "521871", "Score": "0", "body": "Practicing my one new word a day :-)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T14:43:37.030", "Id": "264210", "ParentId": "264189", "Score": "2" } }, { "body": "<p>Don't do this:</p>\n<pre><code>#include&lt;bits/stdc++.h&gt;\n</code></pre>\n<p>I know coding sites say use it. But don't. Its not standard. It will get you into bad habits that will kick you in the butt one day.</p>\n<hr />\n<p>Don't do this:</p>\n<pre><code>using namespace std;\n</code></pre>\n<p>Bad habit. Can get you banned from projects.</p>\n<hr />\n<p>Unless you are building the library that has external stuff there is no need to use macros.</p>\n<pre><code>#define PII pair&lt;int,int&gt;\n</code></pre>\n<p>In C++ we moved away from this as we have in language better options.</p>\n<pre><code>/// C++03\ntypedef std::pair&lt;int, int&gt; PII\n\n// C++11\nusing PII = std::pair&lt;int, int&gt;;\n</code></pre>\n<p>But you don't even use this type.</p>\n<hr />\n<p>Sure:</p>\n<pre><code> ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n</code></pre>\n<p>Standard optimization. Not going to buy you much in this code though.</p>\n<hr />\n<p>This seems like a waste.</p>\n<pre><code> map&lt;char, int&gt; alph;\n string latin = &quot;abcdefghijklmnopqrstuvwxyz&quot;;\n for(int x = 0; x &lt; (int)latin.length(); x++)\n alph[latin[x]] = x + 1;\n</code></pre>\n<p>Could you not replace all that with:</p>\n<pre><code> int alpha(char x) {\n return x - 'a' + 1;\n }\n</code></pre>\n<hr />\n<p>OK.\nint n, q;\ncin &gt;&gt; n &gt;&gt; q;</p>\n<hr />\n<p>Did the specs say that the string had zero spaces in it?</p>\n<pre><code> string s;\n cin &gt;&gt; s; // If there is a space in the input this breaks.\n</code></pre>\n<p>Knowing coding sites, there will be exactly one test that will test for this.</p>\n<hr />\n<p>Why are you storing results?</p>\n<pre><code> vector&lt;int&gt; results;\n</code></pre>\n<p>The output from each question is a number. There is no other output. So simply print the number when you work it out.</p>\n<hr />\n<p>You are optimizing?</p>\n<pre><code> map&lt;string, int&gt; memo;\n</code></pre>\n<p>Storing previously calculated results?<br />\nCreating these substrings (the key) is going to be really expensive. Not sure if you are saving much by caching this value, given the cost. Might want to use a <code>std::string_view</code> so you don't have to pay the cost of creating those substrings to store as the key. But I would test it first without the cache to see if it is worth even bothering to do this.</p>\n<hr />\n<p>Sure:</p>\n<pre><code> for(int k = 0; k &lt; q; k++){\n int l,r, length;\n length = 0;\n cin &gt;&gt; l &gt;&gt; r;\n \n</code></pre>\n<hr />\n<p>Is this correct?</p>\n<pre><code> for(int b= l-1; b &lt; r; b++){\n length += alph[s[b]];\n }\n</code></pre>\n<p>I though the cost was the position in the sub-string not position in the alphabet.</p>\n<hr />\n<p>You just did a find (after creating the substring). Now you are creating the substring again and repeating the search to get the value! The call to find above returns an iterator you can get the length from the iterator!</p>\n<pre><code> length = memo[s.substr(l-1, r - l + 1)];\n\n\n std::string_view key(&amp;s[l-1], &amp;s[r]);\n auto find = memo.find(key);\n if (find == memo.end()) {\n length = memo[key] = calcLength();\n }\n else {\n length = find-&gt;second;\n }\n</code></pre>\n<hr />\n<p>Just print the value.</p>\n<pre><code> results.push_back(length); \n</code></pre>\n<p>This is just going to be slow as you are doing memory management here.</p>\n<hr />\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;sstream&gt;\n#include &lt;string_view&gt;\n#include &lt;map&gt;\n\nint main()\n{\n std::ios_base::sync_with_stdio(false);\n std::cin.tie(NULL);\n\n std::string line;\n std::getline(std::cin, line);\n std::stringstream linestream(std::move(line));\n\n int n, q;\n if (!(linestream &gt;&gt; n &gt;&gt; q) {\n throw std::runtime_error(&quot;Fail 1&quot;);\n }\n\n std::string s;\n std::getline(std::cin, s);\n\n // Personally, I need convincing this is a valid optimization\n // creating the tree is relatively trivial but still far\n // more costly than summing a set of integers. You would\n // have to have some long strings and lots of repeats before\n // this becomes worth it.\n\n // Also this technical could be improved by allowing for\n // totally enclosed substrings to be used in calculating the\n // length for larger strings. \n std::map&lt;std::string_view, int&gt; memo;\n\n for(int loop = 0; loop &lt; q; loop++){\n line.clear();\n std::getline(std::cin, line);\n std::stringstream linestream(std::move(line));\n\n int l,r, length;\n if (!(linestream &gt;&gt; l &gt;&gt; r)) {\n throw std::runtime_error(&quot;Fail 2&quot;);\n }\n\n std::string_view key(&amp;s[l], (r - l + 1));\n\n auto find = memo.find(key);\n if (find == memo.end()) {\n length = 0;\n for(auto val: key) {\n // Not sure about this.\n // Need some unit tests.\n length += std::islower(val) ? val - 'a' + 1: 0;\n }\n memo[key] = length;\n }\n else {\n length = find-&gt;second;\n }\n std::cout &lt;&lt; length &lt;&lt; &quot;\\n&quot;;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T04:34:31.213", "Id": "521828", "Score": "0", "body": "I know it is not allowed to reply with \"Thank you\" to an answer but I do appreciate your suggestions. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T07:10:28.317", "Id": "521831", "Score": "0", "body": "It's pretty certain that it is the position in the alphabet that counts, given the example `abbcb`⟶ `abbbbcccbb`. In reality, given that we only need to report the length, we're just summing the numeric values of all the letters. If it were position in the string, we wouldn't need to even read the string, as it would just be an operation on triangular numbers. The example could have been better if it didn't have so much overlap between the character values and positions!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T07:21:57.070", "Id": "521833", "Score": "0", "body": "The description says \"The song is a string consisting of lowercase English letters\", so we're probably entitled to do anything except UB if that precondition is violated. Take out the `std::islower()` test. That saves me having to remind you to make `val` an `unsigned char` rather than `auto`! One more thing: it seems that there's one string and many queries, so the `std::getline()` and initial processing needs to be outside the loop." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T19:11:31.837", "Id": "264216", "ParentId": "264189", "Score": "3" } } ]
{ "AcceptedAnswerId": "264216", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T19:03:48.450", "Id": "264189", "Score": "0", "Tags": [ "c++", "time-limit-exceeded", "dynamic-programming" ], "Title": "Calculate sum of a substring" }
264189
<p>I've been grinding some Leetcode for an interview coming up and just completed Square Spiral in Javascript.</p> <p>Looking for feedback on performance. This ranked faster than 58% of submissions, would there be anyway to increase the speed using a similar implementation to what I have here?</p> <p><a href="https://i.stack.imgur.com/iE7LT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iE7LT.png" alt="enter image description here" /></a></p> <pre><code>let matrix = [ [1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11,12,13,14,15], [16,17,18,19,20], [21,22,23,24,25] ] var spiralOrder = (matrix) =&gt; { //make copy var dup=JSON.parse(JSON.stringify(matrix)); //setup variables let maxX, maxY, baseX, baseY, x, y, vecX, vecY, nums, totalSquares; //Max indexes for array and sub arrays maxY=matrix[0].length-1; maxX=matrix.length-1; //baseX tells x when it has reached the first sub array. baseX=0; //baseY tells y when it has reached the first index of a sub array. baseY=0; //our indexes x=0; y=0; //our movement vectors vecX=0; vecY=0; //the count for keeping track of positions iterated count=0; //the total amount of squares to be iterated totalSquares=matrix.length*matrix[0].length; //return value array nums=[]; //I don't get how subArrays with only a single element could //still be considered spiralable, but this if-statement handles //those edge cases. Thanks Leetcode. if (matrix[0].length===1) { for (var i=0;i&lt;matrix.length;i++) { nums.push(matrix[i][0]) } return nums } //While our iterated count is not equal to the total amount of //squares to be iterated. When this is true we know we //have completed the spiral. while(count!==totalSquares) { nums.push(dup[x][y]); count++; //Our loop iterates around in a spiral. On every turn //the loop increases the opposite side baseX, baseY, //maxX or maxY to increase the tightness of the spiral //as it loops. //This handles starting the very first iteration, moving right. if (x===0&amp;&amp;y===0) { vecX=0; vecY=1; //We've reached the top rightmost square, move down. } else if (x===baseX&amp;&amp;y===maxY) { vecX=1; vecY=0; //We can't increment baseY until we're on //our second turn downwards. if (baseX&gt;0) { baseY+=1; } //We've reached bottom rightmost square, move left, increment baseX. } else if (x===maxX&amp;&amp;y===maxY) { vecX=0; vecY=-1; baseX+=1; //We've reached bottom leftmost square, move up, decrement maxY. } else if (x===maxX&amp;&amp;y===baseY) { vecX=-1; vecY=0 maxY-=1; //We've reached top leftmost square, move right, decrement maxX. } else if (x===baseX&amp;&amp;y===baseY) { vecX=0; vecY=1; maxX-=1; } //Increment x or y by the vector. x+=vecX; y+=vecY; } return nums } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-22T04:22:22.063", "Id": "521891", "Score": "2", "body": "Want to increase performance remove the JSON (super slow) copy hack. There is no reason to copy the array in this code. Nor should you ever use JSON for anything but data transport . To copy a 2D array `const dup = array2D.map(subArray=>[...subArray]);`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-22T04:37:10.973", "Id": "521893", "Score": "0", "body": "You're right there isn't any reason to copy, however when I take out the copy the speed is increased to 72 ms, but if I use this 2d copy map function the speed increases up to 64 ms, weird." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-22T04:46:05.463", "Id": "521895", "Score": "0", "body": "Not weird. Reason 1 Most likely, run the code several times, server load will effect run time at leetcode. Reason 2 unlikely but possible that there could be a proxy on the array" } ]
[ { "body": "<h2 id=\"review-q1p6\">REVIEW</h2>\n<p>As a solution it is simple and performant which is the aim of all good code.</p>\n<p>However there are many style issues likely due to inexperience</p>\n<h2 id=\"code-style-review-9auu\">Code style review</h2>\n<ul>\n<li><p>Way too many comments. Many of them stating the obvious, some inaccurate.</p>\n<p>Comments should only be used when the code can not describe what the code does, and generally when the code is such that it needs comments then it is best to change the code rather than add comments.</p>\n<p>Often comments are added to clarify poor variable names. If you are adding comments to clarify a name then don't add the comment, change the name.</p>\n</li>\n<li><p>Spaces between operators.</p>\n</li>\n<li><p>Take care to define all variables. The variable <code>count</code> is undefined when you assign 0 to it.</p>\n<p>JS will declare the variable for you but it will be declared in global scope and is thus slower to access and likely to clash with existing globals resulting in very hard to debug bugs. ALWAYS declare variables.</p>\n<p>The rewrite function adds the directive <code>&quot;use strict&quot;</code> to prevent undeclared variables from being used. For more on <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/strict_mode\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript reference 'strict mode'\">strict_mode</a></p>\n</li>\n<li><p>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. 'const'\">const</a> for variables that do not change.</p>\n</li>\n<li><p>You can assign variables as you declare them.</p>\n</li>\n<li><p>Be consistent in your use of semicolons. Some lines are missing semicolons, and each return is also missing semicolons.</p>\n</li>\n<li><p>Always use the simplest style - i.e. don't write 4 lines of code when 1 will do.</p>\n</li>\n<li><p>When using x,y coordinates on 2D arrays the x Axis is for columns and y for rows. In the rewrite I changed x and y to col and row.</p>\n</li>\n</ul>\n<h2 id=\"rewrite-ukbx\">Rewrite</h2>\n<p>The rewrite keeps the same logic (apart from added early exit when only one row).</p>\n<ul>\n<li><p>Added <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/strict_mode\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript reference 'strict mode'\">strict_mode</a> directive <code>&quot;use strict&quot;</code></p>\n</li>\n<li><p>It removes the array copy at the top.</p>\n</li>\n<li><p>Uses <code>var</code> rather than <code>let</code> but which to use is up to you.</p>\n</li>\n<li><p>Uses a style that is focused on performance rather than source brevity.</p>\n<p>Eg <code>if (row === 0 &amp;&amp; col === 0) {</code> could be <code>if (!row &amp;&amp; !col) {</code> however that requires type coercion which is slower. Same with <code>if (baseRow &gt; 0) {</code> can be <code>if (baseRow) {</code></p>\n</li>\n</ul>\n<pre><code>function spiralOrder1(matrix) {\n &quot;use strict&quot;;\n var baseRow = 0, baseCol = 0, row = 0, col = 0, colStep = 0, rowStep = 0, count = 0;\n\n if (matrix.length === 1) { return matrix[0] } // Leetcode rules may need\n // [...matrix[0]] rather than matrix[0]\n if (matrix[0].length === 1) { return matrix.map(a =&gt; a[0]) }\n var width = matrix[0].length - 1;\n var height = matrix.length - 1;\n const total = matrix.length * matrix[0].length;\n const result = [];\n while (count++ &lt; total) {\n result.push(matrix[row][col]);\n if (row === 0 &amp;&amp; col === 0) {\n colStep = 1;\n rowStep = 0;\n } else if (row === baseRow &amp;&amp; col === width) {\n colStep = 0;\n rowStep = 1;\n if (baseRow &gt; 0) { baseCol ++ }\n } else if (row === height &amp;&amp; col === width) {\n colStep = -1;\n rowStep = 0;\n baseRow ++;\n } else if (row === height &amp;&amp; col === baseCol) {\n colStep = 0;\n rowStep = -1;\n width --;\n } else if (row === baseRow &amp;&amp; col === baseCol) {\n colStep = 1;\n rowStep = 0;\n height --;\n }\n row += rowStep;\n col += colStep;\n }\n return result;\n}\n</code></pre>\n<h2 id=\"performance-mpub\">Performance</h2>\n<p>Leetcode has a focus on performance. Your function (with the array copy removed) is performant however there is room for some improvements.</p>\n<h3 id=\"hints-keen\">Hints</h3>\n<p>The first row can be a straight copy of the first array e.g. <code>result = [...matrix[0]]</code> saving the need to execute all the statements in the while loop on the first row.</p>\n<p>At each turn of the spiral you can know the distance to the next turn. This gives an opportunity to skip many of the (if) statements.</p>\n<p>Each corner of the spiral is a right turn. The new direction can thus be computed as <code>[col, row] = [-row, col]</code> thus you only need to know when you are at a corner, not which corner you are at.</p>\n<h3 id=\"gains-fmty\">Gains</h3>\n<p>Implementing these optimization I get about a 10-20% performance increase on a 5 by 5 array.</p>\n<p>That said there could be other algorithms that are even more performant.</p>\n<p>Assuming that the array must not be changed in place the limiting factor is set by the best case time complexity of <span class=\"math-container\">\\$O(n)\\$</span></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-23T13:56:31.543", "Id": "522012", "Score": "0", "body": "Missing the count var was definitely a huge mess-up on my end, I understand strict mode better now." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-23T04:29:47.747", "Id": "264307", "ParentId": "264193", "Score": "2" } } ]
{ "AcceptedAnswerId": "264307", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-19T21:14:21.907", "Id": "264193", "Score": "1", "Tags": [ "javascript", "interview-questions" ], "Title": "Square Spiral Matrix in Javascript" }
264193
<p>I'm working on a simple <a href="https://en.wikipedia.org/wiki/Leaky_bucket" rel="nofollow noreferrer">Leaky Bucket algorithm</a>. I have found a lot of samples on the internet, but something always bothers me. Most of them use Collections and DateTime to track current actions and calculate the time of a Delay.</p> <p>So, I try a controversial (according to my co-workers) implementation, using 2 semaphores and a separate thread to do the leaky job.</p> <p>That's in production now, handling thousands of requests per second without a hitch.</p> <p>The logic was based on the code found in <a href="https://dotnetcoretutorials.com/2019/11/24/implementing-a-leaky-bucket-client-in-net-core/" rel="nofollow noreferrer">this</a> article.</p> <p>I have 3 questions:</p> <ol> <li>Is it a problem to use a semaphore inside another?</li> <li>Do you guys see any problem with this code or this approach?</li> <li>Can we optimize something to gain better performance?</li> </ol> <p><strong>SimpleLeakyBucket.cs</strong></p> <pre><code>namespace Limiter { using System; using System.Threading; using System.Threading.Tasks; public class SimpleLeakyBucket : IDisposable { readonly SemaphoreSlim semaphore = new SemaphoreSlim(1, 1); readonly SemaphoreSlim semaphoreMaxFill = new SemaphoreSlim(1, 1); readonly CancellationTokenSource leakToken = new CancellationTokenSource(); readonly Config configuration; readonly Task leakTask; int currentItems = 0; public SimpleLeakyBucket(Config configuration) { this.configuration = configuration; leakTask = Task.Run(Leak, leakToken.Token); //start leak task here } public async Task Wait(CancellationToken cancellationToken) { await semaphore.WaitAsync(cancellationToken); try { if (currentItems &gt;= configuration.MaxFill) { await semaphoreMaxFill.WaitAsync(cancellationToken); } Interlocked.Increment(ref currentItems); return; } finally { semaphore.Release(); } } void Leak() { //Wait for our first queue item. while (currentItems == 0 &amp;&amp; !leakToken.IsCancellationRequested) { Thread.Sleep(100); } while (!leakToken.IsCancellationRequested) { Thread.Sleep(configuration.LeakRateTimeSpan); if (currentItems &gt; 0) { var leak = Math.Min(currentItems, configuration.LeakRate); Interlocked.Add(ref currentItems, -leak); if (semaphoreMaxFill.CurrentCount == 0) { semaphoreMaxFill.Release(); } } } } public void Dispose() { if (!leakToken.IsCancellationRequested) { leakToken.Cancel(); leakTask.Wait(); } GC.SuppressFinalize(this); } public class Config { public int MaxFill { get; set; } public TimeSpan LeakRateTimeSpan { get; set; } public byte LeakRate { get; set; } } } } </code></pre> <p><strong>Usage sample</strong></p> <pre><code>namespace LimiterPlayground { class Program { static void Main(string[] args) { //will limite the execution by 100 per 10 second using var leaky = new SimpleLeakyBucket(new SimpleLeakyBucket.Config { LeakRate = 100, LeakRateTimeSpan = TimeSpan.FromSeconds(10), MaxFill = 100 }); Task.WaitAll(Enumerable.Range(1, 100000).Select(async idx =&gt; { await leaky.Wait(CancellationToken.None); Console.WriteLine($&quot;[{DateTime.Now:HH:mm:ss.fff}] - {idx.ToString().PadLeft(5, '0')}&quot;); }).ToArray()); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T21:43:56.570", "Id": "521819", "Score": "0", "body": "What is .NET version?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T23:13:11.747", "Id": "521881", "Score": "0", "body": "The code is compatible and run on netcorepp3.1 and net5.0.\nBut i´m think thid is compatible with net48 too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-22T05:28:17.090", "Id": "521901", "Score": "0", "body": "From a bird-view the code isn't completely thread-safe. I'll dig in it a bit later. Just interesting: would there a difference in behavior between 100 items per 10 sec and 10 items per 1 sec?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-22T14:10:47.893", "Id": "521939", "Score": "1", "body": "@FabioAvila Am I right that your implementation is based on [this](https://dotnetcoretutorials.com/2019/11/24/implementing-a-leaky-bucket-client-in-net-core/)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-22T16:29:45.543", "Id": "521949", "Score": "0", "body": "@aepot - tnks for your time. About your question, there is a difference if you have a lot of tasks to run.\nIn 100 itens per 10sec for example: you are can queue up to 100 tasks at same time\nIn 10 itens per 1sec, you can queur only 10 taks at max.\nif your taks are fast, there is a big difference." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-22T16:33:26.683", "Id": "521950", "Score": "0", "body": "@PeterCsala, youre right this is one of the code base that i bases of. Sorry for dont put this in question, becouse i get too much samples on the internet to do my test i forgot the credits, my bad. I´ll update the question for this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-22T16:38:53.340", "Id": "521951", "Score": "0", "body": "Iam working on a variation ot this code, that not use Interlocked, this user direct the properties ans recources of the semaphoreMaxFill property." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T01:12:35.777", "Id": "264195", "Score": "3", "Tags": [ "c#", "performance", "algorithm" ], "Title": "Simple Leaky Bucket Async and Low Footprint" }
264195
<p>I am computing pairwise Euclidean distances for 3-D vectors representing particle positions in a periodic system. The minimum image convention is applied for each periodic boundary such that a particle only considers the <em>nearest image</em> of another particle when computing the distance.</p> <p>This code is part of a larger post-processing effort in Python. Here is a working example of what I am implementing:</p> <pre><code>import numpy as np from scipy.spatial.distance import cdist s = np.array([40, 30, 20]) half_s = 0.5*s a = np.transpose(np.random.rand(1000,3) * s) b = np.transpose(np.random.rand(1000,3) * s) dists = np.empty((3, a.shape[1]*b.shape[1])) for i in range(3): dists[i,:] = cdist(a[i,:].reshape(-1,1), b[i,:].reshape(-1,1), 'cityblock').ravel() dists[i,:] = np.where(dists[i,:] &gt; half_s[i], dists[i,:] - s[i], dists[i,:]) dists = np.sqrt(np.einsum(&quot;ij,ij-&gt;j&quot;, dists, dists)) </code></pre> <p>The domain size <code>s</code> and the 3xn particle position arrays <code>a</code> and <code>b</code> are obtained from existing data structures, but this example uses sizes I would typically expect. I should emphasize that <code>a</code> and <code>b</code> can have different lengths, but on average I expect the final <code>dists</code> array to represent around a million distances (+/- an order of magnitude).</p> <p>The <strong>last 5 lines computing the distances</strong> will need to be run many thousands of times, so <strong>this is what I hope to optimize</strong>.</p> <p>The difficulty arises from the need to apply the minimum image convention to each component independently. I haven't been able to find anything which can beat SciPy's cdist for computing the unsigned distance components, and NumPy's einsum function seems to be the most efficient way to reduce the distances for arrays of this size. At this point, the bottleneck in the code is in the NumPy where function. I also tried using NumPy's casting method by replacing the penultimate line with</p> <pre><code>dists[i,:] -= (dists[i,:] * s_r[i] + 0.5).astype(int) * s[i] </code></pre> <p>where <code>s_r = 1/s</code>, but this yielded the same runtime. <a href="https://doi.org/10.1524/zpch.2013.0311" rel="nofollow noreferrer">This paper</a> discusses various techniques to handle this operation in C/C++, but I'm not familiar enough with the underlying CPython implementation in NumPy/SciPy to determine what's best here. I'd love to parallelize this section, but I had little success with the multiprocessing module and cdist is incompatible with Numba. I would also entertain suggestions on writing a C extension, though I've never incorporated one in Python before.</p>
[]
[ { "body": "<p>I think you could move the <code>where</code> function out of the loop:</p>\n<pre><code>dists = np.empty((3, a.shape[1] * b.shape[1]))\n\nfor i in range(3):\n dists[i, :] = cdist(a[i, :].reshape(-1, 1),\n b[i, :].reshape(-1, 1), 'cityblock').reshape(-1)\n\ndists = np.where(dists &gt; half_s[..., None], dists - s[..., None], dists)\n...\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T09:32:05.343", "Id": "268284", "ParentId": "264196", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T02:24:13.987", "Id": "264196", "Score": "2", "Tags": [ "python-3.x", "numpy", "scipy" ], "Title": "Applying Minimum Image Convention in Python" }
264196
<pre><code>&lt;!DOCTYPE html&gt; &lt;!--Declare the doctype as the html standard of HTML 5--&gt; &lt;html lang=&quot;en-us&quot;&gt; &lt;!--Lang Attribute to declare the language of a webpage--&gt; &lt;head&gt; &lt;!--Every html doc needs a head which contains important information for viewing the code on different devices.--&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;!--The declaration of correct character encoding ensures proper interpretation and indexing for search purposes.--&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;!--Another default meta definition sets the user's device display area to a default.--&gt; &lt;title&gt;Men need multiple mental health options. The content on this site holds no claim to expertise in the mental health profession.&lt;/title&gt; &lt;!--Primarily used for SEO, accurate titles help algorithms do their thang.--&gt; &lt;/head&gt; &lt;body&gt; &lt;!--The body serves as the main content of your page.--&gt; &lt;h1&gt;Pitfalls&lt;/h1&gt; &lt;!--h1 represents a section of the body (a heading); the primary heading, followed by lower-priority additional headings in ascending order.--&gt; &lt;p&gt;Nearly every man deals with major pitfalls in life &lt;strong&gt;--&lt;/strong&gt; &lt;em&gt;depression, sorrow, rage, lonliness, jealousy, resentment &lt;/em&gt;&lt;/p&gt; &lt;!--A p tag represents a style, similar to a paragraph, and visually separates elements.--&gt; &lt;p&gt;A pitfall is concealed.&lt;/p&gt; &lt;p&gt;A pitfall takes work to maintain.&lt;/p&gt; &lt;p&gt;A pitfall can ruin your life.&lt;/p&gt; &lt;p&gt;You don't have to fall victim these traps. You can learn skills to overcome them, so that when you're faced with decisions that may lead to pitfalls, you can avoid them.&lt;/p&gt; &lt;p&gt;The most important thing to remember is, the choice is yours.&lt;/p&gt; &lt;/body&gt; &lt;footer&gt;&lt;a href=&quot;/Users/******/Documents/bmi/page2.html&quot;&gt;Learn more..&lt;/a&gt;&lt;/footer&gt; &lt;!--Sometimes important links or references are necessarily included in a footer, similar to a research document.--&gt; &lt;/html&gt; </code></pre> <p>I want to make sure everything is proper with regards to HTML style and coding conventions, and comments. Indents are two (2) spaces. I took notes on each line to help me learn and remember.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T09:17:33.463", "Id": "521786", "Score": "0", "body": "A small remark about typographical conventions: Don't use two hyphens as a parenthetic dash. It should be either an en dash (with spaces around) or a em dash (without spaces). Either use the literal Unicode characters ( –, — ) or the HTML character references (`&ndash;`, `&mdash;`). Also using `strong` on it seems wrong." } ]
[ { "body": "<p>HTML isn't intended for humans to read (but still it can be read), so that's more of a training, not real work. Real production HTML is better stripped of comments and spaces, minified and zipped to save network traffic. But if you need it to be readable...</p>\n<h3 id=\"use-validator-aqag\">Use validator</h3>\n<p>The only formal error here can be found immediately by an <a href=\"https://validator.w3.org/nu/#textarea\" rel=\"nofollow noreferrer\">online validator</a>: <code>&lt;footer&gt;</code> tag is out of <code>&lt;body&gt;</code>.</p>\n<h3 id=\"strong-is-not-bold-fkdo\"><code>&lt;strong&gt;</code> is not bold</h3>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/strong\" rel=\"nofollow noreferrer\">The <code>&lt;strong&gt;</code> HTML element indicates that its contents have strong importance, seriousness, or urgency.</a> It is shown in <strong>bold</strong>, but if you need bold font - use CSS, not <code>&lt;strong&gt;</code> tag.</p>\n<h3 id=\"line-width-1lwz\">Line width</h3>\n<p>If you need the code to be read by humans, limit string width. Traditional maximum width is somewhere near 80 symbols per line (80 or 78), but with modern wide screens you can make it some wider; check out how you see your code on this site. Break long lines.</p>\n<h3 id=\"use-same-indentation-for-comments-zv52\">Use same indentation for comments</h3>\n<p>If comments start at the same distance, it makes clear for reader they are of the same kind. Like</p>\n<pre><code>&lt;!DOCTYPE html&gt; &lt;!--Declare the doctype as the html standard of HTML 5--&gt;\n&lt;html lang=&quot;en-us&quot;&gt; &lt;!--Lang Attribute to declare the language of a webpage--&gt;\n\n&lt;head&gt; &lt;!--Every html doc needs a head which contains important \n information for viewing the code on different devices.--&gt;\n &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;!--The declaration of correct character encoding ensures \n proper interpretation and indexing for search purposes.--&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T04:45:27.650", "Id": "264199", "ParentId": "264197", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T03:43:25.970", "Id": "264197", "Score": "2", "Tags": [ "html", "html5" ], "Title": "HTML page with mental health tips" }
264197
<p>Here is the improved code</p> <pre><code>#include &lt;iostream&gt; #include &lt;sstream&gt; #include &lt;string&gt; #include &lt;random&gt; #include &lt;vector&gt; #include &lt;iomanip&gt; enum class ending { win , lose , tie }; enum class States { Human , robot , blank }; enum class command { deletE , move }; class BOARD { public: std::vector&lt;States&gt; Cells; BOARD(States type , int x , int y); bool wincon(const std::vector&lt;States&gt;&amp; rboard, int coordx, int coordy); }; //functions bool legal(const std::vector&lt;States&gt;&amp; Cells, int choice); void printer(int x, int y, std::vector&lt;States&gt;&amp; Cells, char skin = 'K'); void instructions(); void newpage(); ending mainloop(int realx, int realy , char skin, std::vector&lt;States&gt;&amp; Cells, BOARD board); void moving(int choice, std::vector&lt;States&gt;&amp; Cells, int cols, command decide , States player , int limit); int Ai(std::vector&lt;States&gt;&amp; Cells, int coordx, int coordy , BOARD board ); int main() { srand(static_cast&lt;unsigned int&gt;(time(0))); //elements int realx, realy; char skin; //asking player for input and intro std::cout &lt;&lt; &quot;\t\t 4-CONNNECT \n\t________________________\n&quot;; std::cout &lt;&lt; &quot;enter x cordinate please:&quot;; std::cin &gt;&gt; realx; std::cout &lt;&lt; &quot;enter y cordinate please:&quot;; std::cin &gt;&gt; realy; BOARD board(States::Human, realx, realy); printer(realx, realy, board.Cells); instructions(); std::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\n'); std::cin.get(); newpage(); //get player skin (letter) and pass it into game loop std::cout &lt;&lt; &quot;enter ur skin please:&quot;; std::cin &gt;&gt; skin; newpage(); //test mainloop(realx, realy, skin, board.Cells, board); } //classes function defintion BOARD::BOARD(States type , int x , int y) { for (int i = 0; i &lt; x; i++) { for (int j = 0; j &lt; y; j++) { Cells.push_back(States::blank); } } } //function defintion void printer(int x, int y, std::vector&lt;States&gt;&amp; Cells , char skin ) { int boardnumber = 0; for (int i = 0; i &lt; x; i++) { for (int j = 0; j &lt; y; j++) { switch (Cells[boardnumber]) { case States::Human: std::cout &lt;&lt; skin; std::cout &lt;&lt; std::setw(2); break; case States::robot: std::cout &lt;&lt; &quot;B&quot;; std::cout &lt;&lt; std::setw(2); break; case States::blank: std::cout &lt;&lt; boardnumber+1; if (boardnumber+1 &lt; 10) { std::cout &lt;&lt; std::setw(2); } break; default: break; } std::cout &lt;&lt; &quot;|&quot;; boardnumber++; } std::cout &lt;&lt; &quot;\n&quot;; } } void instructions() { std::cout &lt;&lt; &quot;\ninstructions\n_________________\n&quot;; std::cout &lt;&lt; &quot;\n&quot;; std::cout &lt;&lt; &quot;just search google for instructions for this game :)\n&quot;; } void newpage() { for (int i = 0; i &lt; 50; i++) { std::cout &lt;&lt; &quot;\n&quot;; } } ending mainloop(int realx, int realy , char skin, std::vector&lt;States&gt;&amp; Cells, BOARD board) { //elements int lobbyposition; int blank = 1; int limit = realx * realy; int userchoice , aichoice; //first or last std::cout &lt;&lt; &quot;start first(yes = 0 or no = 1):&quot;; std::cin &gt;&gt; lobbyposition; newpage(); //loob while (blank != limit) { if (lobbyposition % 2 == 0) { printer(realx, realy, Cells, skin); std::cout &lt;&lt; &quot;enter the position:&quot;; std::cin &gt;&gt; userchoice; moving(userchoice , Cells, realy, command::move, States::Human , limit); newpage(); printer(realx, realy, Cells, skin); std::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\n'); std::cin.get(); newpage(); blank++; lobbyposition++; if (board.wincon(Cells, realx, realy)) return ending::win; } else if (lobbyposition % 2 != 0) { aichoice = Ai(Cells, realx, realy, board ); printer(realx, realy, Cells, skin); std::cout &lt;&lt; &quot;\nmy result is :&quot; &lt;&lt; aichoice; newpage(); printer(realx, realy, Cells, skin); std::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\n'); std::cin.get(); newpage(); blank++; lobbyposition++; if (board.wincon(Cells, realx, realy)) return ending::lose; } } } bool BOARD::wincon(const std::vector&lt;States&gt;&amp; rboard, int coordx, int coordy) { bool check = false; int equ1, equ2 , counter; counter = 0; States startvalue = rboard[counter]; for (int x = 0; x &lt; coordx; x++) { for (int y = 0; y &lt; coordy; y++) { startvalue = rboard[counter]; int possiblex[4][2] = { {0 , 1} , {1 , 0} , {1 , -1} , {1 , 1} }; if (startvalue != States::blank) { //checkloop for (int j = 0; j &lt; 4; j++) { check = true; int i = 0; for (int b = 1; b &lt; 4; ++b) { equ1 = (x + (b * possiblex[j][i])); equ2 = (y + (b * possiblex[j][i + 1])); if (equ1 &lt; 0 || equ1 == coordx) { check = false; break; } else if (equ2 &lt; 0 || equ2 == coordy) { check = false; break; } else { if (rboard[equ2 + equ1 * coordy] != startvalue) { check = false; } } } if (check == true) { return check; } } } counter++; } } return check; } bool legal(const std::vector&lt;States&gt;&amp; Cells, int choice) { int counter = 1; for (States loop : Cells){ if (counter == choice) { if (loop != States::blank) { return false; } else { return true; } } counter++; } return false; } void moving(int choice, std::vector&lt;States&gt;&amp; Cells, int cols, command decide, States player , int limit) { int position = choice+cols; while (legal(Cells, position) == true) { choice += cols; position += cols; } choice -= 1; if (decide == command::move) { Cells[choice] = player; } else if ( decide == command::deletE) { if (legal(Cells, (choice+1)) != true){ Cells[choice] = States::blank; } else { Cells[choice+cols] = States::blank; } } } int Ai(std::vector&lt;States&gt;&amp; Cells,int coordx, int coordy , BOARD board ) { //checkwin and stop win int limit = coordx * coordy; int counter = 1; while (counter &lt; limit) { if (legal(Cells, counter)) { //check win moving(counter, Cells, coordy, command::move, States::robot, limit); if (board.wincon(Cells, coordx, coordy) == true) { return counter; } moving(counter, Cells, coordy, command::deletE, States::robot, limit); } counter++; } counter = 1; while (counter &lt; limit) { if (legal(Cells, counter)) { //check enemy moving(counter, Cells, coordy, command::move, States::Human, limit); if (board.wincon(Cells, coordx, coordy) == true) { moving(counter, Cells, coordy, command::deletE, States::Human, limit); moving(counter, Cells, coordy, command::move, States::robot, limit); return counter; } moving(counter, Cells, coordy, command::deletE, States::Human, limit); } counter++; } //random number generatror (sry was lazy to updata to c++ 11, its too complicated for my brain) for (int i = 0; i &lt; 1000; i++) { counter = (rand() % limit)+1; if (legal(Cells , counter)){ moving(counter, Cells, coordy, command::move, States::robot , limit); return counter + 1; } } } </code></pre> <p>That's an improved version from <a href="https://codereview.stackexchange.com/q/261155">my first 4-connect post</a>. I added classes and enums and no multidimentional vectors I think.</p> <p>I also made the code look better and removed childish names.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-16T00:06:18.530", "Id": "528556", "Score": "0", "body": "My first impression is that many of the things you list under \"functions\" ought to be members. Don't pass in a vector of states... make it a member function _of the BOARD class_." } ]
[ { "body": "<p>It's good to see the improvements you've made to your code! There's still more that can be done better though, some of which I'll list below.</p>\n<h1>Use a consistent code style</h1>\n<p>The style of your code has lots of inconsistencies. Some of them are related to the use of spaces (especially around commas) and empty lines. A code formatting tool, like <a href=\"http://astyle.sourceforge.net/\" rel=\"nofollow noreferrer\">Artistic Style</a> or <a href=\"https://clang.llvm.org/docs/ClangFormat.html\" rel=\"nofollow noreferrer\">ClangFormat</a>, can fix these issues in an automated way for you. Or perhaps even your editor or IDE has a function to format the code for you. Which style you use is not as important as being consistent.</p>\n<p>Even more important is the choice of names for types, variables and functions. Try to be consistent with the way you capitalize them. I recommend you use the following rules of thumb:</p>\n<ul>\n<li>Types (<code>struct</code>s, <code>class</code>es and <code>enum</code>s) are in <a href=\"https://en.wikipedia.org/wiki/Pascal_case\" rel=\"nofollow noreferrer\">PascalCase</a>: every individual word in the name of the type starts with a capital. So:\n<ul>\n<li><code>ending</code> -&gt; <code>Ending</code></li>\n<li><code>command</code> -&gt; <code>Command</code></li>\n<li><code>BOARD</code> -&gt; <code>Board</code></li>\n</ul>\n</li>\n<li>Functions and variables in either <a href=\"https://en.wikipedia.org/wiki/Snake_case\" rel=\"nofollow noreferrer\">snake_case</a> or <a href=\"https://en.wikipedia.org/wiki/Camel_case\" rel=\"nofollow noreferrer\">camelCase</a>. So if you go for snake_case, then:\n<ul>\n<li><code>wincon()</code> -&gt; <code>win_con()</code></li>\n<li><code>mainloop()</code> -&gt; <code>main_loop()</code></li>\n<li><code>coordx</code> -&gt; <code>coord_x</code></li>\n<li>and so on.</li>\n</ul>\n</li>\n<li>Enum <em>values</em> are in all UPPER_CASE, so:\n<ul>\n<li><code>win</code> -&gt; <code>WIN</code></li>\n<li><code>Human</code> -&gt; <code>HUMAN</code></li>\n<li>and so on.</li>\n</ul>\n</li>\n</ul>\n<h1>Naming things</h1>\n<p>Some names for functions and variables could be better. Make a distinction between x and y <em>coordinates</em>, and between width and height. So the constructor of <code>BOARD</code> for example should use <code>width</code> and <code>height</code> as the parameters, and then it can use <code>x</code> and <code>y</code> as the loop indices, like so:</p>\n<pre><code>Board::Board(int width, int height)\n{\n for (int y = 0; y &lt; height; ++y)\n {\n for (int x = 0; x &lt; width; ++x)\n {\n Cells.push_back(States::BLANK);\n }\n }\n}\n</code></pre>\n<p>In <code>printer()</code>, there is a variable <code>boardnumber</code>. However, there's only one board in the game, so this name is a bit confusing. Instead it's just the index into <code>Cells</code>. In that case, I would name it <code>cell_index</code>, or perhaps just <code>index</code> since it's a rather small function and it should be rather clear.</p>\n<p>You are also being inconsistent with naming. In some other functions you used variables named <code>counter</code> and <code>position</code> for the index into <code>Cells</code>.</p>\n<p>Inside <code>main()</code> and <code>mainloop()</code>, you use <code>realx</code> and <code>realy</code> for what probably should be named <code>width</code> and <code>height</code>.</p>\n<p>Some other rules of thumb:</p>\n<ul>\n<li>Use singular for most things, except for collections of things. So:\n<ul>\n<li><code>States</code> -&gt; <code>State</code></li>\n</ul>\n</li>\n<li>Prefer verbs for functions, nouns for variables. For functions returning a yes/no answer, prefix it with <code>is_</code>. So:\n<ul>\n<li><code>legal()</code> -&gt; <code>is_legal()</code></li>\n<li><code>printer()</code> -&gt; <code>print()</code></li>\n<li><code>instructions()</code> - <code>show_instructions()</code></li>\n<li>and so on.</li>\n</ul>\n</li>\n</ul>\n<h1>Avoid redundant function arguments</h1>\n<p>Some functions take arguments that are either never used (like <code>type</code> in <code>BOARD::BOARD()</code>), or are redundant. For example, <code>mainloop()</code> takes both a reference to <code>Cells</code>, and has a paramter <code>board</code>. But the <code>board</code> already has the vector of cells as a member variable. In this case, remove the reference to the cells, and just pass the board as a reference:</p>\n<pre><code>Ending main_loop(int width, int height, char skin, Board &amp;board)\n{\n ...\n printer(width, height, board.Cells, skin);\n ...\n</code></pre>\n<p>Even better if all functions take references to a <code>Board</code> instead of a reference to a <code>std::vector&lt;States&gt;</code>. But it can be improved a lot more:</p>\n<h1>Make <code>BOARD</code> a better class</h1>\n<p>At the moment, your <code>class BOARD</code> doesn't do much; it just holds the cells, and has only one function that checks for a winning condition. However, this class doesn't know its own width and height, it doesn't know how to print itself, it can't tell if a given move is valid, and so on. Some of your regular functions should be made member functions of this class. That way, you don't have to pass the width, height, and a reference to a <code>BOARD</code> or to a <code>std::vector&lt;States&gt;</code> to them. It might look like this:</p>\n<pre><code>class Board {\npublic:\n const int width;\n const int height;\n std::vector&lt;State&gt; cells(width * height, State::BLANK);\n\n Board(int width, int height);\n void print() const;\n void make_move(State player, int column);\n bool is_legal_move(int column) const;\n bool is_winning_condition() const;\n};\n</code></pre>\n<p>And then the implementation of the functions can look like this:</p>\n<pre><code>Board::Board(int width, int height): width(width), height(height) {}\n\nvoid Board::print() const {\n int index = 0;\n for (int y = 0; y &lt; height; ++y) {\n for (int x = 0; x &lt; width; ++x) {\n switch (cells[index]) {\n ...\n }\n std::cout &lt;&lt; '|';\n index++:\n }\n std::cout &lt;&lt; '\\n';\n }\n}\n\nbool Board::is_legal(int column) const {\n return cells[column] == State::blank;\n}\n...\n</code></pre>\n<p>Don't just make every function a member function of <code>class Board</code> though. Functions that have nothing to do with the <code>Board</code> should of course not be in it, but also functions like <code>Ai()</code> might be a bad candidate; while they do interact with the board, an AI is not part of the board, it's just one of the players. So for functions like that, just pass a reference like before.</p>\n<h1>Use C++11's random number generators</h1>\n<p>I mentioned this in the previous review, but I'll repeat this again (for the benefit of other readers): the <code>srand()</code> and <code>rand()</code> functions come from C, and are of low quality. Consider using the <a href=\"https://en.cppreference.com/w/cpp/numeric/random\" rel=\"nofollow noreferrer\">C++11 random number functionality</a>. See <a href=\"https://stackoverflow.com/questions/13445688/how-to-generate-a-random-number-in-c\">this StackOverflow post</a> for how to use it.</p>\n<p>It's really not that hard to use. First, create the following variables:</p>\n<pre><code>std::random_device rdev;\nstd::mt19937 rng(rdev());\n</code></pre>\n<p>These basically replace the call to <code>srand()</code> at the top of <code>main()</code>. Then to use it to generate a random numbers between 1 and <code>limit + 1</code> for example, write:</p>\n<pre><code>std::uniform_int_distribution distrib(1, limit + 1);\n\nfor (int i = 0; i &lt; 1000; ++i) {\n counter = distrib();\n ...\n}\n</code></pre>\n<p>Here the variable <a href=\"https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution\" rel=\"nofollow noreferrer\"><code>distrib</code></a> basically is a replacement for <code>rand()</code> that is specialized to provide integers perfectly distributed between the two limits you give it, and by &quot;calling&quot; it you will get one of those integers out.</p>\n<h1>Overload <code>operator&lt;&lt;</code> to print the board</h1>\n<p>The C++ way to print things is to write <code>std::cout &lt;&lt; something</code>. It would be nice if you could just write:</p>\n<pre><code>Board board(7, 6);\nstd::cout &lt;&lt; board;\n</code></pre>\n<p>This is actually not that hard to do in C++, see for example <a href=\"https://www.learncpp.com/cpp-tutorial/overloading-the-io-operators/\" rel=\"nofollow noreferrer\">this tutorial</a>. Instead of having a function <code>printer()</code> or member function <code>print()</code>, you have to create a <a href=\"https://en.cppreference.com/w/cpp/language/friend\" rel=\"nofollow noreferrer\"><code>friend</code></a><code> operator&lt;&lt;()</code> function for your class, which looks like this:</p>\n<pre><code>class Board {\n ...\n friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const Board&amp; board);\n};\n\nstd::ostream&amp; operator&lt;&lt;(std::ostream &amp;out, const Board&amp; board) {\n int index = 0;\n for (int y = 0; y &lt; height; ++y) {\n for (int x = 0; x &lt; width; ++x) {\n switch (cells[index]) {\n ...\n }\n out &lt;&lt; '|'; // We just had to replace std::cout with out here!\n index++:\n }\n out &lt;&lt; '\\n';\n }\n\n return out; // Don't forget to return out\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-07T22:23:18.167", "Id": "530135", "Score": "0", "body": "sorry for the late reply, was busy in school." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-07T22:23:35.887", "Id": "530136", "Score": "0", "body": "I will try to correct myself this information" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-15T20:38:57.507", "Id": "268031", "ParentId": "264200", "Score": "5" } }, { "body": "<p>Your <code>mainloop</code> and <code>Ai</code> functions take a BOARD object <em>by value</em>, which will make a copy. You can pass those as <code>const BOARD &amp;board</code> to avoid this. And since the <code>board</code> object already has the <code>Cells</code> data, you shouldn't need to pass that in as a separate parameter.</p>\n<p>From your comment near the end, you're already aware you should use the random number facilities provided by the language. You're including the <code>&lt;random&gt;</code> header, and you should make use of it. It won't make much difference for a simple game like this, but take the opportunity to learn it now so you'll know it later when it is important.</p>\n<p>The coordinate naming seems to be backwards, as you use the <code>y</code> value to index horizontally and the <code>x</code> to index vertically. This makes it a bit harder for someone else to understand, because usually X is horizontal and Y is vertical.</p>\n<p>The <code>BOARD</code> constructor is doing a lot of unnecessary work, and it doesn't use the <code>type</code> parameter at all. You can simplify it to</p>\n<pre><code>BOARD::BOARD(int x, int y): Cells(x * y, States::blank)\n{\n}\n</code></pre>\n<p>The <code>x</code> and <code>y</code> values should be stored in <code>BOARD</code>, because they need to be known to properly access <code>Cells</code>.</p>\n<p><code>printer</code> can be a member of <code>BOARD</code>, as can several of your other functions (anything you pass <code>Cells</code> to would be a good candidate). Your <code>setw</code> calls seem to be in the wrong place; they should come before the value whose width you want to set. The <code>boardnumber+1 &lt; 10</code> comparison can be simplifed to <code>boardnumber &lt; 9</code>, although if you move the <code>setw</code>s you'll wnat to compare <code>boardnumber &lt; 10</code>. Since you don't use the <code>i</code> or <code>j</code> values, you can get rid of them. Use a range-based for (<code>for (auto c: Cells)</code>), increment a counter to track the column and output a newline every <code>x</code> columns.</p>\n<p>Rather than a loop to output newlines one at a time, <code>newpage</code> can make use of a static char array (manually filled with newlines) or a temporary string (<code>std::cout &lt;&lt; std::string(50, '\\n');</code>). Consider changing that 50 to a named constant.</p>\n<p><code>mainloop</code> doesn't return a value if the board fills up (<code>blank == limit</code>), which is undefined behavior. You should return something to indicate that the game was a draw (a tie). The <code>else if</code> condition is unnecessary, because it will always be true (because if <code>lobbyposition % 2 == 0</code> is false, <code>lobbyposition % 2 != 0</code> will be true).</p>\n<p>In <code>wincon</code>, declare variables as you need them, not a the function start. <code>possiblex</code> can be <code>static const int</code> to avoid constructing the array for every position. You also seem to be checking the wrong places (your array has <em>down</em>, <em>right</em>, <em>up and left</em>, <em>down and left</em>). You should be using <code>{ {0, 1}, {0, -1}, {1, 0}, {-1, 0} }</code>. The bounds checking looks for underflow but not going off the right side or bottom of the grid. You need to check for it with <code>equ1 &gt;= coordx</code> and <code>equ2 &gt;= coordy</code> in the appropriate place. You could add a <code>break;</code> if the <code>rboard</code> check sets <code>check</code> to false.</p>\n<p>The <code>legal</code> function could use a better name. It does a lot of work just to check one value. Use the indexing to look up the value in <code>Cells</code>. To make that easy, add an indexing function to return the value at a particular cell, and use it here and in <code>wincon</code>.</p>\n<p>Including some comments to explain what some of these functions do would help with the readability. What is <code>moving</code> supposed to be doing? It looks like it searches down the chose column to find where the marker ends up, then sets it. Changing <code>legal</code> to take both an <code>x</code> and <code>y</code> value, and using the indexing function can simplify this and avoid the need for adding or subtracting 1 from <code>choice</code>.</p>\n<p>What is the loop at the end of <code>Ai</code> supposed to do? There are only a limited number of moves that can be made. If it gets that far, and that loop runs to completion, you don't return anything from <code>Ai</code> which can result in a string value in <code>aichoice</code> back at the callsite. Since you don't do anything with that value other than print it out, there is no real harm but the potential is there for Something Bad to happen if that usage changes. (This could happen if, for example, you separate out the Ai logic to one function to decide the move, and another one shared between the Ai and human player that makes the move.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-15T20:54:56.703", "Id": "268032", "ParentId": "264200", "Score": "5" } } ]
{ "AcceptedAnswerId": "268031", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T06:11:25.217", "Id": "264200", "Score": "5", "Tags": [ "c++", "algorithm", "game", "vectors", "connect-four" ], "Title": "C++ Connect-four game with little AI (Version two)" }
264200
<p>I solved <a href="https://projecteuler.net/problem=58" rel="nofollow noreferrer">problem 58</a> in Project Euler and I am happy with my solution. However, are there any areas where I can improve my code here as I am learning how to write good python code.</p> <p>Prompt:</p> <blockquote> <p>Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed.</p> <pre><code>37 36 35 34 33 32 31 38 17 16 15 14 13 30 39 18 5 4 3 12 29 40 19 6 1 2 11 28 41 20 7 8 9 10 27 42 21 22 23 24 25 26 43 44 45 46 47 48 49 </code></pre> <p>It is interesting to note that the odd squares lie along the bottom right diagonal, but what is more interesting is that 8 out of the 13 numbers lying along both diagonals are prime; that is, a ratio of 8/13 ≈ 62%.</p> <p>If one complete new layer is wrapped around the spiral above, a square spiral with side length 9 will be formed. If this process is continued, what is the side length of the square spiral for which the ratio of primes along both diagonals first falls below 10%?</p> </blockquote> <pre class="lang-py prettyprint-override"><code>#! /usr/bin/env python from funcs import isPrime # Corner values of a square of size s have values: # s^2 - 3s + 3, s^2 - 2s + 2, s^2 - s + 1, s^2 def corner_values(n): &quot;&quot;&quot; returns a tuple of all 4 corners of an nxn square &gt;&gt;&gt; corner_values(3) (3, 5, 7, 9) &quot;&quot;&quot; return (n ** 2 - 3 * n + 3, n ** 2 - 2 * n + 2, n ** 2 - n + 1, n ** 2) def main(): ratio, side_length = 1, 1 primes, total = 0, 0 while ratio &gt;= 0.1: side_length += 2 for n in corner_values(side_length): if isPrime(n): primes += 1 total += 1 else: total += 1 ratio = primes / total return side_length - 2 if __name__ == &quot;__main__&quot;: print(main()) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T08:16:06.510", "Id": "521785", "Score": "0", "body": "What is funcs module?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T09:57:13.843", "Id": "521787", "Score": "0", "body": "@PavloSlavynskyy These are some local helper functions I have written." } ]
[ { "body": "<h3 id=\"identifiers-consistency-6w7i\">Identifiers consistency</h3>\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> recommends snake_case, not camelCase for functions and variables; <code>isPrime</code> breaks this. Moreover, PEP8 recommends consistency over other matters (except for readability). If it's your function - maybe you should rework it one way or another?</p>\n<h3 id=\"main-is-unclear-name-6p0t\"><code>main</code> is unclear name</h3>\n<p>Yes, it makes clear that it makes some &quot;main work&quot; in the file, but <code>find_prime_diagonals_size</code> (ok, bad example) or something like that could be more readable. How about <code>solve_euler58</code>?</p>\n<h3 id=\"dry-in-if-branches-8u0u\">DRY in if branches</h3>\n<p>If the last statement in both <code>if</code> and <code>else</code> branches is the same - it can be moved out and put after <code>if-else</code>:</p>\n<pre><code> if isPrime(n):\n primes += 1\n total += 1\n</code></pre>\n<p>The same applies if you have first statement the same - it could be put before <code>if</code>.</p>\n<h3 id=\"total-and-side_length-are-loop-variables-and-are-defined-by-each-other-w6ey\"><code>total</code> and <code>side_length</code> are loop variables and are defined by each other</h3>\n<p><code>total</code> increases by 4 every <code>while</code> iteration, and <code>side_length</code> increases by 2. Consider using only 1 variable and (arguably) itertools.count, like</p>\n<pre><code>for side_length in itertools.count():\n ...\n if primes/(side_length*2-1)&lt;0.1:\n return side_length\n</code></pre>\n<h3 id=\"corner_values-return-a-progression-so-it-can-be-replaced-with-range-hxb7\"><code>corner_values</code> return a progression, so it can be replaced with range</h3>\n<pre><code>range(n**2 - 3*n + 3, n**2 + 1, n - 1)\n</code></pre>\n<p>returns the same values as <code>corner_values</code>, even probably slightly faster, but I'm not sure if it's more readable. Probably not. Still, you should be aware of possibilities.</p>\n<h3 id=\"divisions-are-slower-than-multiplications-floating-point-operations-are-slower-than-integers-71wh\">Divisions are slower than multiplications, floating point operations are slower than integers</h3>\n<p>It's not really important here; but I think you should know that. You're calculating <code>primes / total &gt;= 0.1</code> every loop; multiply both sides by 10*total, and the expression will be <code>10 * primes &gt;= total</code>, which calculates slightly faster. I don't think it's really needed here, it looks more readable in the first form, just FYI.</p>\n<h3 id=\"complexity-of-isprime-is-unknown-augz\">Complexity of <code>isPrime</code> is unknown</h3>\n<p>I think this is the bottleneck of the code. Does it use any sieve or is just a brute force division check?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T18:12:40.617", "Id": "264214", "ParentId": "264201", "Score": "2" } } ]
{ "AcceptedAnswerId": "264214", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T07:13:53.460", "Id": "264201", "Score": "1", "Tags": [ "python-3.x", "programming-challenge" ], "Title": "Ratio of primes in square diagonals | Problem 58 Project Euler" }
264201
<p>This is my 1st Python program I've actually written and I have little to no background in the language. I just figured I could learn and do something that interested me at the same time.</p> <p>I'm not a book learner. I can't just sit down and read a bunch of technical documents and stuff like that so I'm sure a lot of this code is unconventional at best and just plain bad at worst. I learn best by doing, so now that I got this program to work I want to learn how to make it better.</p> <p>The goal of the program is to load the Yahoo finance options page for each ticker in a file that I created. Then pull all of the call options data for each expiration date and load all of that data into a SQL database (to be queried later).</p> <p>I added the multi-processing to try and make it faster, but it seems to have just slowed it down. I gotta figure that part out.</p> <pre><code>import logging import pyodbc import config import yahoo_fin as yfin import asyncio import multiprocessing import time from yahoo_fin import options from datetime import datetime, date from selenium import webdriver def main(): read_ticker_file() def init_selenium(): driver = webdriver.Chrome(config.CHROME_DRIVER) return driver def yfin_options(symbol): logging.basicConfig(filename='yfin.log', level=logging.INFO) logging.basicConfig(filename='no_options.log', level=logging.ERROR) try: # get all options dates (in epoch) from dropdown on yahoo finance options page dates = get_exp_dates(symbol) # iterate each date to get all calls and insert into sql db for date in dates: arr = yfin.options.get_calls(symbol, date) arr_length = len(arr.values) i = 0 for x in range(0, arr_length): strike: str = str(arr.values[i][2]) volume = str(arr.values[i][8]) open_interest = str(arr.values[i][9]) convert_epoch = datetime.fromtimestamp(int(date)) try: sql_insert(symbol, strike, volume, open_interest, convert_epoch) i += 1 except Exception as insert_fail: print(&quot;I failed at sqlinsert {0}&quot;.format(insert_fail)) file_name_dir = &quot;C:\\temp\\rh\\options{0}{1}.xlsx&quot;.format(symbol, date) logging.info(arr.to_excel(file_name_dir)) except Exception as e: bad_tickers_file_dir = config.BAD_TICKERS f = open(bad_tickers_file_dir, &quot;a&quot;) f.write(symbol) f.write('\n') def sql_insert(symbol, strike, volume, open_interest, exp_date): conn_string = ('Driver={SQL Server};' 'Server=DESKTOP-7ONNV8L;' 'Database=optionsdb;' 'Trusted_Connection=yes;') conn = pyodbc.connect(conn_string) cursor = conn.cursor() insert_string = &quot;&quot;&quot;INSERT INTO dbo.options (Ticker, Strike, Volume, OpenInterest, expDate) VALUES (?, ?, ?, ?, ?)&quot;&quot;&quot; cursor.execute(insert_string, symbol, strike, volume, open_interest, str(exp_date)) conn.commit() def get_exp_dates(symbol): url = &quot;https://finance.yahoo.com/quote/&quot; + symbol + &quot;/options?p=&quot; + symbol chromedriver = init_selenium() chromedriver.get(url) # Yahoo Finance options dropdown class name (find better way to do this) select_dropdown = chromedriver.find_element_by_css_selector(&quot;div[class='Fl(start) Pend(18px)'] &gt; select&quot;) options_list = [x for x in select_dropdown.find_elements_by_tag_name(&quot;option&quot;)] dates = [] for element in options_list: dates.append(element.get_attribute(&quot;value&quot;)) return dates def read_ticker_file(): file1 = open(config.TICKER_FILE, 'r') lines = file1.readlines() count = 0 ticker_arr = [] # loop to read each ticker in file for line in lines: count += 1 line = line.strip('\n') line = line.strip() ticker_arr.append(line) return ticker_arr if __name__ == &quot;__main__&quot;: pool = multiprocessing.Pool() # input list inputs = read_ticker_file() # pool object with number of element pool = multiprocessing.Pool(processes=4) pool.map(yfin_options, inputs) pool.close() pool.join() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T15:35:51.680", "Id": "521797", "Score": "0", "body": "Would be better to use yahoo finances api rather than scraping https://github.com/mxbi/yahoo-finance-api/blob/master/DOCUMENTATION.md" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T15:45:02.163", "Id": "521798", "Score": "0", "body": "@RyanSchaefer unfortunately, this API has been dead for 3+ years" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T15:46:04.343", "Id": "521799", "Score": "0", "body": "Ahh whoops its at v7 now as used here https://github.com/ranaroussi/yfinance/blob/main/yfinance/ticker.py" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T16:03:26.613", "Id": "521800", "Score": "0", "body": "@RyanSchaefer Thanks! I'm going to try and implement the same logic this way and measure the performance of both. I suspect it's not going to be all that better than what I'm doing now because the major bottleneck is getting the option chain dates with selenium. I'm not sure of another way to do it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T16:14:27.340", "Id": "521801", "Score": "0", "body": "With selenium -> you download the entire page, graphics and everything. With the above, you download just some JSON" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T16:20:28.890", "Id": "521802", "Score": "1", "body": "@RyanSchaefer well in my case I want to get the options chain for all expiration dates. The unofficial api requires a specific date to be passed for each chain. The only way to dynamically get all of the dates (as far as I am aware) is to actually load the page and grab them from the dropdown.\n\nSo really no way around using Selenium without hardcoding the dates. But they vary by ticker so that approach doesn't really make sense" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T16:25:51.837", "Id": "521803", "Score": "2", "body": "It has an `.options` property which shows the expiration dates. From that, you can then iterate through the dates and load the chain for each date." } ]
[ { "body": "<p>For <code>get_exp_dates</code> - and everything else here - Selenium is unneeded. The dates you seek are not based on AJAX etc., but baked right into the HTML:</p>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;select class=&quot;Fz(s) H(25px) Bd Bdc($seperatorColor)&quot; data-reactid=&quot;5&quot;&gt;\n&lt;option selected=&quot;&quot; value=&quot;1626998400&quot; data-reactid=&quot;6&quot;&gt;July 23, 2021&lt;/option&gt;\n&lt;option value=&quot;1627603200&quot; data-reactid=&quot;7&quot;&gt;July 30, 2021&lt;/option&gt;\n&lt;option value=&quot;1628208000&quot; data-reactid=&quot;8&quot;&gt;August 6, 2021&lt;/option&gt;\n&lt;option value=&quot;1628812800&quot; data-reactid=&quot;9&quot;&gt;August 13, 2021&lt;/option&gt;\n&lt;option value=&quot;1629417600&quot; data-reactid=&quot;10&quot;&gt;August 20, 2021&lt;/option&gt;\n&lt;option value=&quot;1630022400&quot; data-reactid=&quot;11&quot;&gt;August 27, 2021&lt;/option&gt;\n&lt;option value=&quot;1631836800&quot; data-reactid=&quot;12&quot;&gt;September 17, 2021&lt;/option&gt;\n&lt;option value=&quot;1634256000&quot; data-reactid=&quot;13&quot;&gt;October 15, 2021&lt;/option&gt;\n&lt;option value=&quot;1637280000&quot; data-reactid=&quot;14&quot;&gt;November 19, 2021&lt;/option&gt;\n&lt;option value=&quot;1642723200&quot; data-reactid=&quot;15&quot;&gt;January 21, 2022&lt;/option&gt;\n&lt;option value=&quot;1647561600&quot; data-reactid=&quot;16&quot;&gt;March 18, 2022&lt;/option&gt;\n&lt;option value=&quot;1655424000&quot; data-reactid=&quot;17&quot;&gt;June 17, 2022&lt;/option&gt;\n&lt;option value=&quot;1663286400&quot; data-reactid=&quot;18&quot;&gt;September 16, 2022&lt;/option&gt;\n&lt;option value=&quot;1674172800&quot; data-reactid=&quot;19&quot;&gt;January 20, 2023&lt;/option&gt;\n&lt;option value=&quot;1679011200&quot; data-reactid=&quot;20&quot;&gt;March 17, 2023&lt;/option&gt;\n&lt;option value=&quot;1686873600&quot; data-reactid=&quot;21&quot;&gt;June 16, 2023&lt;/option&gt;\n&lt;/select&gt;\n</code></pre>\n<p>So just get the HTML via Requests and parse it via BeautifulSoup.</p>\n<p><code>for x in range(0, arr_length):</code> can drop the <code>0, </code> as it's default.</p>\n<p>Since everything within <code>arr.values[i]</code> has a positional meaning, it's worth unpacking; something like</p>\n<pre><code>@dataclass\nclass SymbolRow:\n contract_name: str\n last_trade_date: datetime\n strike: Decimal\n last_price: Decimal\n bid: Decimal\n ask: Decimal\n change: Decimal\n change_percent: float\n volume: int\n open_interest: int\n implied_volatility: float\n \n...\n\nrow = SymbolRow(*arr.values[i])\n</code></pre>\n<p>^ That version assumes that the fields are already properly deserialized from the markup into reasonable types, which they probably aren't. A constructor could do this.</p>\n<pre><code>&quot;C:\\\\temp\\\\rh\\\\options{0}{1}.xlsx&quot;\n</code></pre>\n<p>should not be hard-coded within your method, and should exist in either configuration or maybe a separated global variable.</p>\n<pre><code>f = open(bad_tickers_file_dir, &quot;a&quot;)\n</code></pre>\n<p>should be using a <code>with</code>.</p>\n<p><code>conn_string</code> should not exist within your <code>sql_insert</code>, and indeed the <code>sql_insert</code> method should not be connecting; that should be done at the outer level and only once per program run.</p>\n<pre><code>[x for x in select_dropdown.find_elements_by_tag_name(&quot;option&quot;)]\n</code></pre>\n<p>can just be</p>\n<pre><code>list(select_dropdown.find_elements_by_tag_name(&quot;option&quot;))\n</code></pre>\n<p>There's no kind of close-guarantee for your connection and cursors. Based on the <a href=\"https://github.com/mkleehammer/pyodbc/blob/master/src/connection.cpp#L1569\" rel=\"nofollow noreferrer\">code</a> it doesn't look like their implementation of <code>__exit__</code> is sensible, so just <code>try/finally/.close()</code>.</p>\n<p>Your logger configuration doesn't make much sense. You should probably make your own module-specific logger instance (rather than calling into the basic config stuff and using the root logger) - and have just a single logger with multiple handlers, each having a different level.</p>\n<p>The following code demonstrates (minus your SQL stuff) a way to scrape Yahoo Finance without needing the <code>yahoo_fin</code> library, covering some of the above, and also demonstrating two different kinds of HTML path selector precompilation.</p>\n<pre><code>import enum\nimport locale\nfrom datetime import datetime\nfrom decimal import Decimal\nfrom enum import Enum\nfrom locale import setlocale, LC_NUMERIC\nfrom pprint import pprint\nfrom typing import Iterable, Optional, Dict\n\nimport pytz\nimport soupsieve\nfrom soupsieve import SoupSieve\nfrom bs4 import BeautifulSoup, SoupStrainer, Tag\nfrom requests import Session\n\n\nDATE_STRAINER = SoupStrainer(\n 'select', class_='Fz(s) H(25px) Bd Bdc($seperatorColor)',\n)\nOPTION_STRAINER = SoupStrainer(\n 'section', attrs={'data-yaft-module': 'tdv2-applet-OptionContracts'},\n)\nCALLS_SIEVE = soupsieve.compile('table.calls')\nPUTS_SIEVE = soupsieve.compile('table.puts')\n\n\n@enum.unique\nclass OptionKind(Enum):\n CALL = enum.auto()\n PUT = enum.auto()\n\n\nclass Option:\n def __init__(self, row: Dict[str, Tag], kind: OptionKind):\n self.kind = kind\n\n self.contract_name = row['Contract Name'].text\n self.contract_path = row['Contract Name'].a['href']\n\n dt, tz = row['Last Trade Date'].text.rsplit(maxsplit=1)\n # Ugh.\n tz = {\n 'EDT': 'US/Eastern',\n # ...\n }.get(tz, tz)\n\n self.last_trade_date = datetime.strptime(\n dt, '%Y-%m-%d %I:%M%p'\n ).replace(tzinfo=pytz.timezone(tz))\n\n self.strike = money_or_none(row['Strike'].text)\n self.last_price = money_or_none(row['Last Price'].text)\n self.bid = money_or_none(row['Bid'].text)\n self.ask = money_or_none(row['Ask'].text)\n self.change = money_or_none(row['Change'].text)\n self.percent_change = percent_or_none(row['% Change'].text)\n self.volume = int_or_none(row['Volume'].text)\n self.open_interest = int_or_none(row['Open Interest'].text)\n self.implied_volatility = percent_or_none(row['Implied Volatility'].text)\n\n\ndef get_yfin(\n session: Session,\n symbol: str,\n when: Optional[int] = None,\n straddle: bool = False,\n) -&gt; str:\n params = {\n 'p': symbol,\n 'straddle': straddle,\n }\n if when is not None:\n params['date'] = when\n\n with session.get(\n f'https://finance.yahoo.com/quote/{symbol}/options',\n params=params,\n headers={'Accept': 'text/html'},\n ) as resp:\n resp.raise_for_status()\n return resp.text\n\n\ndef get_exp_dates(session: Session, symbol: str) -&gt; Iterable[int]:\n doc = BeautifulSoup(\n get_yfin(session, symbol),\n features='html.parser', parse_only=DATE_STRAINER,\n )\n for option in doc.find_all('option'):\n yield int(option['value'])\n\n\ndef int_or_none(s: str) -&gt; Optional[int]:\n if s == '-':\n return None\n return locale.atoi(s)\n\n\ndef percent_or_none(s: str) -&gt; Optional[float]:\n if s == '-':\n return None\n return float(s.rsplit('%', 1)[0])\n\n\ndef money_or_none(s: str) -&gt; Optional[Decimal]:\n if s == '-':\n return None\n return Decimal(s)\n\n\ndef table_to_dicts(parent: Tag, sieve: SoupSieve) -&gt; Iterable[Dict[str, Tag]]:\n table, = sieve.select(parent, limit=1)\n heads = [th.text for th in table.thead.tr.find_all('th')]\n for tr in table.tbody.find_all('tr'):\n yield dict(zip(heads, tr.find_all('td')))\n\n\ndef get_options(session: Session, symbol: str, when: int) -&gt; Iterable:\n doc = BeautifulSoup(\n get_yfin(session, symbol, when),\n features='html.parser', parse_only=OPTION_STRAINER,\n )\n\n for call in table_to_dicts(doc, CALLS_SIEVE):\n yield Option(call, OptionKind.CALL)\n for put in table_to_dicts(doc, PUTS_SIEVE):\n yield Option(put, OptionKind.PUT)\n\n\ndef main():\n setlocale(LC_NUMERIC, 'en_US.UTF8')\n\n with Session() as session:\n session.headers = {'User-Agent': 'Mozilla/5.0'}\n dates = tuple(get_exp_dates(session, 'msft'))\n for option in get_options(session, 'msft', dates[2]):\n pprint(option.__dict__)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T22:51:29.413", "Id": "264224", "ParentId": "264206", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T12:07:03.067", "Id": "264206", "Score": "2", "Tags": [ "python", "performance", "beginner", "python-3.x", "web-scraping" ], "Title": "Yahoo finance option chain scraper" }
264206
<p>This ip core simply generates a sine wave according a .mem file. It is required to specify rom depth equal to number of the sine points, the init file and the data size contained in the file. The phase offset and frequency are used as control signals.</p> <p>It also houses the ROM module as well as the ip core and ROM testbenches. The tcl scripts allow you to run Modelsim from the console due to the bash scripts.</p> <p><a href="https://www.daycounter.com/Calculators/Sine-Generator-Calculator.phtml" rel="nofollow noreferrer">https://www.daycounter.com/Calculators/Sine-Generator-Calculator.phtml</a> - points of the sine LUT calculator.</p> <p>dds.v</p> <pre><code>`timescale 1ns / 1ps module dds # ( parameter integer DATA_WIDTH = 16 , parameter integer ROM_DEPTH = 1024 , parameter INIT_FILE = &quot;&quot; , parameter integer FCW_WIDTH = $clog2(ROM_DEPTH) + 14, parameter integer PHASE_OFFSET_WIDTH = 10 ) ( input wire clk_i , input wire s_rst_n_i , input wire en_i , input wire [FCW_WIDTH - 1 : 0] fcw_i , input wire [PHASE_OFFSET_WIDTH - 1 : 0] phase_offset_i , //for instance: ROM_DEPTH / 2 == (2 * pi) / 2 == pi input wire phase_offset_wr_i, output wire [DATA_WIDTH - 1 : 0] sinus_o ); localparam integer LOOKUP_TABLE_INDEX_WIDTH = $clog2(ROM_DEPTH); localparam integer ACCUMULATOR_WIDTH = FCW_WIDTH; wire [LOOKUP_TABLE_INDEX_WIDTH - 1 : 0] lookup_table_index; rom_distributed # ( .DATA_WIDTH (DATA_WIDTH ), .ROM_DEPTH (ROM_DEPTH ), .INIT_FILE (INIT_FILE ), .ADDRESS_WIDTH (LOOKUP_TABLE_INDEX_WIDTH) ) rom_distributed_inst ( .address_i (lookup_table_index), .data_o (sinus_o ) ); dds_generator # ( .LOOKUP_TABLE_INDEX_WIDTH (LOOKUP_TABLE_INDEX_WIDTH), .ACCUMULATOR_WIDTH (ACCUMULATOR_WIDTH ), .PHASE_OFFSET_WIDTH (PHASE_OFFSET_WIDTH ), .FCW_WIDTH (FCW_WIDTH ) ) dds_generator_inst ( .clk_i (clk_i ), .s_rst_n_i (s_rst_n_i ), .en_i (en_i ), .phase_offset_wr_i (phase_offset_wr_i ), .phase_offset_i (phase_offset_i ), .fcw_i (fcw_i ), .lookup_table_index_o (lookup_table_index) ); endmodule </code></pre> <p>dds_tb.v</p> <pre><code>`timescale 1ns / 1ps //The paths need to be changed `define MEM_FILE_0 &quot;../dds_0.mem&quot; `define MEM_FILE_2 &quot;../dds_2.mem&quot; module dds_tb; localparam integer CLOCK_PERIOD = 100 ; localparam integer ITERATION_NUM = 4 * 1000000 ; localparam integer DATA_WIDTH = 16 ; localparam integer LUT_INDEX_REST = 14 ; localparam integer ROM_DEPTH_0 = 1024 ; localparam integer PHASE_OFFSET_WIDTH_0 = 10 ; localparam integer FCW_WIDTH_0 = PHASE_OFFSET_WIDTH_0 + LUT_INDEX_REST; localparam [FCW_WIDTH_0 - 1 : 0] PI_0 = 10'h200 ; localparam [FCW_WIDTH_0 - 1 : 0] SINE_FREQ_0 = {FCW_WIDTH_0{1'h0}} + 9'h100 ; localparam [PHASE_OFFSET_WIDTH_0 - 1 : 0] PHASE_OFFSET_0 = {PHASE_OFFSET_WIDTH_0{1'h0}} ; localparam [PHASE_OFFSET_WIDTH_0 - 1 : 0] PHASE_OFFSET_1 = {PHASE_OFFSET_WIDTH_0{1'h0}} + PI_0 ; localparam integer ROM_DEPTH_2 = 512 ; localparam integer PHASE_OFFSET_WIDTH_2 = 9 ; localparam integer FCW_WIDTH_2 = PHASE_OFFSET_WIDTH_2 + LUT_INDEX_REST; localparam [FCW_WIDTH_0 - 1 : 0] PI_2 = 9'h100 ; localparam [FCW_WIDTH_0 - 1 : 0] SINE_FREQ_2 = {FCW_WIDTH_0{1'h0}} + 13'h1000 ; localparam [PHASE_OFFSET_WIDTH_0 - 1 : 0] PHASE_OFFSET_2 = {PHASE_OFFSET_WIDTH_2{1'h0}} ; localparam [PHASE_OFFSET_WIDTH_0 - 1 : 0] PHASE_OFFSET_3 = {PHASE_OFFSET_WIDTH_2{1'h0}} + PI_2 ; wire [DATA_WIDTH - 1 : 0] sinus_0; wire [DATA_WIDTH - 1 : 0] sinus_1; wire [DATA_WIDTH - 1 : 0] sinus_2; wire [DATA_WIDTH - 1 : 0] sinus_3; reg clk = 1'h0; reg s_rst_n = 1'h0; reg en = 1'h0; reg phase_offset_wr_0 = 1'h0; reg phase_offset_wr_1 = 1'h0; reg phase_offset_wr_2 = 1'h0; reg phase_offset_wr_3 = 1'h0; reg [FCW_WIDTH_0 - 1 : 0] fcw_0 = SINE_FREQ_0; reg [FCW_WIDTH_0 - 1 : 0] fcw_1 = SINE_FREQ_0; reg [FCW_WIDTH_2 - 1 : 0] fcw_2 = SINE_FREQ_2; reg [FCW_WIDTH_2 - 1 : 0] fcw_3 = SINE_FREQ_2; reg [PHASE_OFFSET_WIDTH_0 - 1 : 0] phase_offset_0 = PHASE_OFFSET_0; reg [PHASE_OFFSET_WIDTH_0 - 1 : 0] phase_offset_1 = PHASE_OFFSET_1; reg [PHASE_OFFSET_WIDTH_2 - 1 : 0] phase_offset_2 = PHASE_OFFSET_2; reg [PHASE_OFFSET_WIDTH_2 - 1 : 0] phase_offset_3 = PHASE_OFFSET_3; dds # ( .DATA_WIDTH (DATA_WIDTH ), .ROM_DEPTH (ROM_DEPTH_0 ), .INIT_FILE (`MEM_FILE_0 ), .FCW_WIDTH (FCW_WIDTH_0 ), .PHASE_OFFSET_WIDTH (PHASE_OFFSET_WIDTH_0) ) sinus_generator_dut_0 ( .clk_i (clk ), .s_rst_n_i (s_rst_n ), .en_i (en ), .fcw_i (fcw_0 ), .phase_offset_i (phase_offset_0 ), .phase_offset_wr_i (phase_offset_wr_0), .sinus_o (sinus_0 ) ); dds # ( .DATA_WIDTH (DATA_WIDTH ), .ROM_DEPTH (ROM_DEPTH_0 ), .INIT_FILE (`MEM_FILE_0 ), .FCW_WIDTH (FCW_WIDTH_0 ), .PHASE_OFFSET_WIDTH (PHASE_OFFSET_WIDTH_0) ) sinus_generator_dut_1 ( .clk_i (clk ), .s_rst_n_i (s_rst_n ), .en_i (en ), .fcw_i (fcw_1 ), .phase_offset_i (phase_offset_1 ), .phase_offset_wr_i (phase_offset_wr_1), .sinus_o (sinus_1 ) ); dds # ( .DATA_WIDTH (DATA_WIDTH ), .ROM_DEPTH (ROM_DEPTH_2 ), .INIT_FILE (`MEM_FILE_2 ), .FCW_WIDTH (FCW_WIDTH_2 ), .PHASE_OFFSET_WIDTH (PHASE_OFFSET_WIDTH_2) ) sinus_generator_dut_2 ( .clk_i (clk ), .s_rst_n_i (s_rst_n ), .en_i (en ), .fcw_i (fcw_2 ), .phase_offset_i (phase_offset_2 ), .phase_offset_wr_i (phase_offset_wr_2), .sinus_o (sinus_2 ) ); dds # ( .DATA_WIDTH (DATA_WIDTH ), .ROM_DEPTH (ROM_DEPTH_2 ), .INIT_FILE (`MEM_FILE_2 ), .FCW_WIDTH (FCW_WIDTH_2 ), .PHASE_OFFSET_WIDTH (PHASE_OFFSET_WIDTH_2) ) sinus_generator_dut_3 ( .clk_i (clk ), .s_rst_n_i (s_rst_n ), .en_i (en ), .fcw_i (fcw_3 ), .phase_offset_i (phase_offset_3 ), .phase_offset_wr_i (phase_offset_wr_3), .sinus_o (sinus_3 ) ); initial begin forever begin #(CLOCK_PERIOD / 2) clk = !clk; end end initial begin @(posedge clk); s_rst_n &lt;= 1'h1; en &lt;= 1'h1; @(posedge clk); repeat(ITERATION_NUM) begin @(posedge clk); end phase_offset_wr_0 &lt;= 1'h1; phase_offset_0 &lt;= PHASE_OFFSET_1; phase_offset_wr_2 &lt;= 1'h1; phase_offset_2 &lt;= PHASE_OFFSET_3; @(posedge clk); phase_offset_wr_0 &lt;= 1'h0; phase_offset_wr_2 &lt;= 1'h0; repeat(ITERATION_NUM) begin @(posedge clk); end $stop(); end endmodule </code></pre> <p>rom_distributed.v</p> <pre><code>`timescale 1ns / 1ps module rom_distributed # ( parameter integer DATA_WIDTH = 8 , parameter integer ROM_DEPTH = 256 , parameter INIT_FILE = &quot;&quot;, parameter integer ADDRESS_WIDTH = $clog2(ROM_DEPTH) ) ( input wire [ADDRESS_WIDTH - 1 : 0] address_i, output wire [DATA_WIDTH - 1 : 0] data_o ); reg [DATA_WIDTH - 1 : 0] rom_memory [ROM_DEPTH - 1 : 0]; initial begin if (&quot;&quot; != INIT_FILE) begin $readmemh(INIT_FILE, rom_memory); end else begin $error(&quot;A rom init file is not specified.&quot;); end end assign data_o = rom_memory[address_i]; endmodule </code></pre> <p>rom_distributed_tb.v</p> <pre><code>`timescale 1ns / 1ps //The path needs to be changed `define INIT_FILE &quot;../rom_async.mem&quot; module rom_distributed_tb; localparam integer DATA_WIDTH = 16 ; localparam integer ROM_DEPTH = 1024 ; localparam integer ADDRESS_WIDTH = $clog2(ROM_DEPTH); wire [DATA_WIDTH - 1 : 0] dut_value; reg [DATA_WIDTH - 1 : 0] file_value; reg [ADDRESS_WIDTH - 1 : 0] address ; integer file = 0; integer errors = 0; rom_distributed # ( .DATA_WIDTH (DATA_WIDTH ), .ROM_DEPTH (ROM_DEPTH ), .INIT_FILE (`INIT_FILE ), .ADDRESS_WIDTH (ADDRESS_WIDTH) ) rom_distributed_dut ( .address_i (address ), .data_o (dut_value) ); initial begin file_value = 0; address = 0; file = $fopen(`INIT_FILE, &quot;r&quot;); if (0 != file) begin repeat(ROM_DEPTH) begin $fscanf(file, &quot;%h&quot;, file_value); #100 if (file_value !== dut_value) begin errors = errors + 1; end address = address + 1; end if (0 == errors) begin $display(&quot;The test passed.\n&quot;); end else begin $display(&quot;The test failed with %d errors.\n&quot;, errors); end end else begin $display(&quot;A descripter of a '%s' file is 0.\n&quot;, `INIT_FILE); end $stop(); end endmodule </code></pre> <p>dds_generator.v</p> <pre><code>`timescale 1ns / 1ps module dds_generator # ( parameter integer LOOKUP_TABLE_INDEX_WIDTH = 10, parameter integer ACCUMULATOR_WIDTH = 24, parameter integer PHASE_OFFSET_WIDTH = 10, parameter integer FCW_WIDTH = 8 ) ( input wire clk_i , input wire s_rst_n_i , input wire en_i , input wire phase_offset_wr_i , input wire [PHASE_OFFSET_WIDTH - 1 : 0] phase_offset_i , input wire [FCW_WIDTH - 1 : 0] fcw_i , output wire [LOOKUP_TABLE_INDEX_WIDTH - 1 : 0] lookup_table_index_o ); localparam integer ACCUMULATOR_WIDTH_LSB = ACCUMULATOR_WIDTH - LOOKUP_TABLE_INDEX_WIDTH; reg [ACCUMULATOR_WIDTH - 1:0] accumulator; always @ (posedge clk_i) begin if(1'h0 == s_rst_n_i ) begin accumulator[ACCUMULATOR_WIDTH_LSB - 1 : 0] &lt;= 0; accumulator[ACCUMULATOR_WIDTH : ACCUMULATOR_WIDTH_LSB] &lt;= phase_offset_i; end else if (1'h1 == phase_offset_wr_i) begin accumulator[ACCUMULATOR_WIDTH_LSB - 1 : 0] &lt;= 0; accumulator[ACCUMULATOR_WIDTH : ACCUMULATOR_WIDTH_LSB] &lt;= phase_offset_i; end else if (1'h1 == en_i) begin if (({10{1'h1}} - 2) == accumulator[ACCUMULATOR_WIDTH : ACCUMULATOR_WIDTH_LSB]) begin accumulator[ACCUMULATOR_WIDTH : ACCUMULATOR_WIDTH_LSB] &lt;= 0; end else begin accumulator &lt;= accumulator + fcw_i; end end end assign lookup_table_index_o = accumulator[ACCUMULATOR_WIDTH : ACCUMULATOR_WIDTH_LSB]; endmodule </code></pre> <p>dds_tb</p> <pre><code>#!/bin/bash #change the vivado_path to yours if required. modelsim_path=/opt/modelsim/modelsim_ase/bin tb_tcl_file_name=dds_tb.tcl $modelsim_path/vsim -do $tb_tcl_file_name </code></pre> <p>dds_tb.tcl</p> <pre><code>transcript on vlib work vmap work work # variables--------- set dut ../../hdl/dds.v set var_1 ../../hdl/dds_generator.v set var_2 ../../hdl/rom_distributed.v set tb dds_tb.v # ------------------ vlog $dut $tb $var_1 $var_2 vsim -t 100ns -voptargs=&quot;+acc&quot; dds_tb # waves --------- add wave /dds_tb/clk add wave -radix hex -format analog-step -max 65535 -min -65535 -height 100 /dds_tb/sinus_0 add wave -radix hex -format analog-step -max 65535 -min -65535 -height 100 /dds_tb/sinus_1 add wave -radix hex -format analog-step -max 32767 -min -32767 -height 100 /dds_tb/sinus_2 add wave -radix hex -format analog-step -max 32767 -min -32767 -height 100 /dds_tb/sinus_3 add wave -radix hex /dds_tb/fcw_0 add wave -radix hex /dds_tb/phase_offset_0 add wave -radix hex /dds_tb/phase_offset_wr_0 add wave -radix hex /dds_tb/fcw_1 add wave -radix hex /dds_tb/phase_offset_1 add wave -radix hex /dds_tb/phase_offset_wr_1 add wave -radix hex /dds_tb/fcw_2 add wave -radix hex /dds_tb/phase_offset_2 add wave -radix hex /dds_tb/phase_offset_wr_2 add wave -radix hex /dds_tb/fcw_3 add wave -radix hex /dds_tb/phase_offset_3 add wave -radix hex /dds_tb/phase_offset_wr_3 # ------------------ configure wave -timelineunits us run -all wave zoom full </code></pre> <p>rom_distributed_tb</p> <pre class="lang-sh prettyprint-override"><code>#!/bin/bash #change the vivado_path to yours if required. modelsim_path=/opt/modelsim/modelsim_ase/bin tb_tcl_file_name=rom_distributed_tb.tcl $modelsim_path/vsim modelsim.ini -do $tb_tcl_file_name </code></pre> <p>rom_distributed_tb.tcl</p> <pre><code>transcript on vlib work vmap work work # variables--------- set dut ../../hdl/rom_distributed.v set tb rom_distributed_tb.v # ------------------ vlog $dut $tb vsim -t 100ns -voptargs=&quot;+acc&quot; rom_distributed_tb # waves --------- add wave -radix hex /rom_distributed_tb/dut_value add wave -radix hex /rom_distributed_tb/file_value add wave -radix hex /rom_distributed_tb/errors # ------------------ configure wave -timelineunits us run -all wave zoom full </code></pre> <p>clear</p> <pre class="lang-sh prettyprint-override"><code>#!/bin/bash rm transcript modelsim.ini *vsim.wlf -r work </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-03T08:45:34.690", "Id": "524713", "Score": "4", "body": "Incorporating advice from an answer into the question violates the question-and-answer nature of this site. You could post improved code as a new question, as an answer, or as a link to an external site - as described in [I improved my code based on the reviews. What next?](/help/someone-answers#help-post-body). I have rolled back the edit, so the answers make sense again." } ]
[ { "body": "<p>When I compile your code on some simulators, I see warning messages which could indicate potential problems. For example, with the Cadence simulator:</p>\n<pre><code> accumulator[ACCUMULATOR_WIDTH : ACCUMULATOR_WIDTH_LSB] &lt;= phase_offset_i; \n |\nxmelab: *W,BNDWRN: Bit-select or part-select index out of declared bounds.\n</code></pre>\n<p>You declared <code>accumulator</code> as <code>[23:0]</code>, but you are trying to access bit <code>[24]</code>, which does not exist. I recommend that you try to avoid this warning. The warning goes away if I change the line to:</p>\n<pre><code> accumulator[ACCUMULATOR_WIDTH - 1 : ACCUMULATOR_WIDTH_LSB] &lt;= phase_offset_i;\n</code></pre>\n<p>You must decide if this is the correct way to avoid this warning. There are similar warnings elsewhere in the <code>dds_generator</code> module for the <code>accumulator</code> signal.</p>\n<p>If you do not see warnings with your simulator, you can try the simulators on <strong>edaplayground</strong> if you sign up for a free account.</p>\n<hr />\n<p>Consider taking advantage of SystemVerilog syntax, especially in your testbench code. Many simulators require you to explicitly enable these features; check your Modelsim documentation.</p>\n<p>For example, you could use the auto-increment operator. Change:</p>\n<pre><code> errors = errors + 1;\n</code></pre>\n<p>to:</p>\n<pre><code> errors++;\n</code></pre>\n<p>Also, you can use 2-state types rather than 4-state when you don't need to model <code>x</code> or <code>z</code> values. Change:</p>\n<pre><code> integer errors = 0;\n</code></pre>\n<p>to:</p>\n<pre><code> int errors = 0;\n</code></pre>\n<p>You can even omit the initialization since all 2-state types default to 0. There is less to type, and 2-state could result in better simulation performance.</p>\n<p>Typically, you don't need to drive z/x on your DUT input ports, so you could use <code>bit</code> instead of <code>reg</code>:</p>\n<pre><code> bit [ADDRESS_WIDTH - 1 : 0] address ;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-03T07:47:00.213", "Id": "524711", "Score": "0", "body": "Thank you. It is my bad. I have fixed it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-23T15:58:07.753", "Id": "264328", "ParentId": "264211", "Score": "3" } }, { "body": "<p>I improved my code based on the review =)</p>\n<pre><code>`timescale 1ns / 1ps\n\nmodule dds_generator # \n(\n parameter integer LOOKUP_TABLE_INDEX_WIDTH = 10,\n parameter integer ACCUMULATOR_WIDTH = 24,\n parameter integer PHASE_OFFSET_WIDTH = 10,\n parameter integer FCW_WIDTH = 8 \n)\n(\n input wire clk_i ,\n input wire s_rst_n_i ,\n input wire en_i ,\n \n input wire phase_offset_wr_i ,\n input wire [PHASE_OFFSET_WIDTH - 1 : 0] phase_offset_i ,\n input wire [FCW_WIDTH - 1 : 0] fcw_i ,\n \n output wire [LOOKUP_TABLE_INDEX_WIDTH - 1 : 0] lookup_table_index_o\n);\n localparam integer ACCUMULATOR_WIDTH_LSB = ACCUMULATOR_WIDTH - LOOKUP_TABLE_INDEX_WIDTH;\n \n reg [ACCUMULATOR_WIDTH - 1:0] accumulator;\n\n always @ (posedge clk_i) begin\n if(1'h0 == s_rst_n_i ) begin\n accumulator[ACCUMULATOR_WIDTH_LSB - 1 : 0] &lt;= 0;\n accumulator[ACCUMULATOR_WIDTH - 1 : ACCUMULATOR_WIDTH_LSB] &lt;= phase_offset_i; \n end\n else if (1'h1 == phase_offset_wr_i) begin\n accumulator[ACCUMULATOR_WIDTH_LSB - 1 : 0] &lt;= 0;\n accumulator[ACCUMULATOR_WIDTH - 1 : ACCUMULATOR_WIDTH_LSB] &lt;= phase_offset_i;\n end else if (1'h1 == en_i) begin\n if (({PHASE_OFFSET_WIDTH{1'h1}} - 2) == accumulator[ACCUMULATOR_WIDTH - 1 : ACCUMULATOR_WIDTH_LSB]) begin\n accumulator[ACCUMULATOR_WIDTH - 1 : ACCUMULATOR_WIDTH_LSB] &lt;= 0;\n end\n else begin\n accumulator &lt;= accumulator + fcw_i;\n end\n end\n end\n \n assign lookup_table_index_o = accumulator[ACCUMULATOR_WIDTH - 1: ACCUMULATOR_WIDTH_LSB];\nendmodule\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-03T07:46:15.537", "Id": "265652", "ParentId": "264211", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T14:46:30.537", "Id": "264211", "Score": "5", "Tags": [ "verilog", "hdl" ], "Title": "Generate a sine wave" }
264211
<pre><code>import java.util.ArrayList; import java.util.Arrays; import java.util.Random; class Student { // Student class properties int number; Double grade; // Student constructor public Student(int index) { Random generator = new Random(); number = index+1; grade = generator.nextDouble()*20; } } class Playground { public static void main(String[] args) { //declaring variables int numOfApplicants = 100; ArrayList&lt;Student&gt; applicants = new ArrayList&lt;Student&gt;(); ArrayList&lt;Student&gt; classA = new ArrayList&lt;Student&gt;(); ArrayList&lt;Student&gt; classB = new ArrayList&lt;Student&gt;(); ArrayList&lt;Student&gt; rejected = new ArrayList&lt;Student&gt;(); //create x students for(int i = 0; i &lt; numOfApplicants; i++) { applicants.add(new Student(i)); } //assign to classes for(Student applicant:applicants) { if (applicant.grade &gt;= 19) { classA.add(applicant); System.out.println(&quot;Student number &quot;+applicant.number+&quot; has been accepted in class A with a score of &quot;+applicant.grade+&quot; !&quot;); } else if (applicant.grade &gt;= 16) { classB.add(applicant); System.out.println(&quot;Student number &quot;+applicant.number+&quot; has been accepted in class B with a score of &quot;+applicant.grade+&quot; !&quot;); } else { rejected.add(applicant); System.out.println(&quot;Student number &quot;+applicant.number+&quot; were rejected because of their &quot;+applicant.grade+&quot; score!&quot;); } } //final totals System.out.println(&quot;\nThis year, class A has &quot; + classA.size() + &quot; students while class B has &quot; + classB.size() + &quot;.\nWhile &quot; + rejected.size() + &quot; were rejected&quot;); } } </code></pre> <p>So yeah here's my code, I am just starting out with Java and I am very much lost, I feel like my code could be improved in many ways so I would really appreciate any input, I am especially not proud of the ugly Double grades that I couldn't figure out how to round down. There is also a weird pattern I am seeing with the grades generated, you can kinda see that there are &lt;10 within class A, &lt;20 within class B and around 80 in the rest, I guess it has to do with the Random Seed? I'll read about that later I guess...</p> <p>Either way, thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T18:54:31.897", "Id": "521807", "Score": "1", "body": "You said that you don't like the ugly double grades. What are the possible grades that you are wanting? Are they supposed to be whole numbers?" } ]
[ { "body": "<p>This is not a full code review, but some things to start:</p>\n<ul>\n<li>Double check your indentation</li>\n<li>The properties in Student should be marked as private. It's customary in Java to always have these fields marked as private, then provide getters/setters to them. This could look like:</li>\n</ul>\n<pre><code>class Student {\n private int number;\n private double grade;\n\n public int getNumber() {\n return number;\n }\n\n public double getGrade() {\n return grade;\n }\n}\n</code></pre>\n<ul>\n<li><p>This may feel like it's unnecessary, but it allows you to control who has access to the fields of a class.</p>\n</li>\n<li><p>Notice that I did not create setter methods, and that's because so far, it doesn't appear that they are needed. Once a student gets a number, there's not really a reason for them to get a new number. And so far, with the requirements, there's no reason to change the grade either. Ultimately, this results in read only fields, which can be made explicit by marking those fields as <code>final</code>.</p>\n</li>\n</ul>\n<pre><code> private final int number;\n private final double grade;\n</code></pre>\n<ul>\n<li>Next, you need to consider when creating data for an object, should that happen in the constructor or in the code that calls the constructor. Because you have this line <code>Random generator = new Random();</code> that happens for each student, I lean towards the code that calls the constructor.</li>\n</ul>\n<pre><code>class Student {\n public Student(int number, double grade) {\n this.number = number;\n this.grade = grade;\n }\n}\n</code></pre>\n<p>That changes the calling code to:</p>\n<pre><code>//create x students\nRandom generator = new Random();\nfor(int i = 0; i &lt; numOfApplicants; i++) {\n int number = i + 1;\n double grade = generator.nextDouble() * 20;\n Student student = new Student(number, grade);\n applicants.add(student );\n}\n</code></pre>\n<ul>\n<li>I also split up that line that previously handled adding the student to the applicants and creating the Student into two lines to aid with readability and to reduce the reasons that that line of code would need to change. Generally, a single line of code should do one thing. It can do multiple things provided that it is still easy to read. In a work environment, it is estimated that code is read ten times more than it is written.</li>\n<li>You can also remove the comment that label the Student properties and constructor. The readers of the code will know that's what they are and the comments don't add anything. What might be a valuable comment is something briefly explaining why a grade is a random number between 0-20 (including 0, but not 20).</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-22T10:39:29.510", "Id": "521919", "Score": "0", "body": "Thanks for your help, I really appreciate it! I'll try to avoid these mistakes and implement your advice on my next exercise :D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-24T13:54:03.027", "Id": "522081", "Score": "0", "body": "By the way, @Xtros what is exactly wrong with my indentation?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-30T20:05:17.170", "Id": "524528", "Score": "0", "body": "The Student class looks excellent, but everything after \"//assign to classes\" needs a closer look. You have the body of a block aligned with the curly braces, rather than indented in." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T18:53:21.383", "Id": "264215", "ParentId": "264212", "Score": "3" } }, { "body": "<h2 id=\"major-issue-java-basics-oop\">Major issue: Java Basics OOP</h2>\n<p>where are your <em>objects</em>, where are your <em>methods</em>? yes, we <strong>do have</strong> a class <code>Students</code> but what else? All of your logic happens within <code>Playground</code>, which can be a suitable class for an excersize, but right now it's totally bloated up!</p>\n<p>here are some ideas for objects</p>\n<ul>\n<li><code>StudentGenerator</code> - has a method <code>generate(int amount)</code>...</li>\n<li><code>Grade</code> - yes, it's more than a mere collection it's a <a href=\"https://javascript.plainenglish.io/dont-use-collection-directly-93a5457a8e40\" rel=\"nofollow noreferrer\">first class collection</a></li>\n<li>a <code>Filter</code>, thats an obvious one</li>\n<li>a class for the purpose: <code>Enrollment</code> who is responsible for that whole applying process</li>\n</ul>\n<h2 id=\"minor-issue-duplicate-code\">Minor Issue: duplicate code</h2>\n<p>i hopefully that will disappear, when you apply OOP but your code is duplicated:</p>\n<pre><code>if (applicant.grade &gt;= 19) {\n classA.add(applicant);\n System.out.println(&quot;Student number &quot;+applicant.number+&quot; has been accepted in class A with a score of &quot;+applicant.grade+&quot; !&quot;);\n}\n</code></pre>\n<p>this appears <strong>three times in a row</strong>, you should have noticed that - <strong>even tough</strong> the text is slightly different and the object (<code>classA</code>) do vary a bit.</p>\n<h2 id=\"minor-issue-redudant-typification-interface-over-class\">Minor Issue: redudant typification, Interface over class</h2>\n<p><code>ArrayList&lt;Student&gt; applicants = new ArrayList&lt;Student&gt;();</code></p>\n<p>well, thats just peanuts, but should be:</p>\n<p><code>List&lt;Student&gt; applicants = new ArrayList&lt;&gt;();</code></p>\n<p>Using Interface over Class and removing redundant type of implementing class</p>\n<h2 id=\"already-said\">Already said</h2>\n<p>most issues concerning your <code>Student</code> clss have been properly addresses by the code Review from <a href=\"https://codereview.stackexchange.com/users/148690/xtros\">XTros</a></p>\n<h2 id=\"digging-deeper-first-class-collection\">digging deeper: <em>first class Collection</em></h2>\n<p>instead of simply adding a <code>Student</code> to a <code>List&lt;Student&gt;</code> named <strong>gradeA</strong> you create a Class around the Collection (here: around the List).</p>\n<pre><code>class Grade {\n private final Collection&lt;Student&gt; students = new ArrayList&lt;&gt;();\n void add(Student student){...}\n void remove(Student student){...}\n}\n</code></pre>\n<p>now you can provide all relevant Code to that Collection! example</p>\n<pre><code>class Grade {\n final String name;\n private final Collection&lt;Student&gt; students = new ArrayList&lt;&gt;();\n \n Grade (String name){this.name = name;}\n\n void add(Student student){\n students.add(Student);\n System.out.println(&quot;Student number &quot;+applicant.number+&quot; has been accepted in class &quot;+name+&quot; with a score of &quot;+applicant.grade+&quot; !&quot;); \n }\n\n //first class collection can do this as well\n String getClassDescription(){\n return &quot;grade &quot;+name+&quot; has &quot;+students.size()+&quot; students&quot;;\n }\n\n //first class collection can do that as well\n List&lt;Students&gt; orderedByName(){\n ...\n }\n}\n</code></pre>\n<p>of course the first class collection should provide basic methods <code>add</code> <code>remove</code> and <code>get</code> and so on (you best implement the whole interface for that) but now this Collection has all methods that are <strong>Grade</strong> specific in its belly. on the place where it should belong.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-22T10:57:22.523", "Id": "521921", "Score": "1", "body": "I tried my hand at some C# with Unity so I should really be ashamed of myself for dumping everything in one script... I guess I haven't coded in a while and just forgot you're not supposed to do that...\n\nAs for the duplicate code, I noticed it but I thought that the hassle of creating a custom method just for 3 cases was not really worth it, but if I did do things properly and applied OOP it would've been part of the enrolment class\n\nHowever for the rest, I have no idea what a collection is, I am going to have to read about that thanks! (I just started learning sorry >.<)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-22T11:15:29.107", "Id": "521922", "Score": "0", "body": "hello @Epsilon thank you for taking my review serious ;-) following the provided Link for the collections, the sub-tile reads *Creating first class collections* - which is one Point in the review. I will add an Example for this in my Answer" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T05:04:56.247", "Id": "264227", "ParentId": "264212", "Score": "0" } }, { "body": "<p>I won't repeat what XTros and Martin Frank have said...</p>\n<p>This is code written in Java, but it's not very Object Oriented as Martin pointed out.</p>\n<p>To reduce the confusion here, I'm going to use the term StudyGroup for your Classes, so that when I talk of classes in the rest of this post, it's clear I'll mean Java classes.</p>\n<p>If I were implementing this, for a start I'd read <a href=\"https://stackoverflow.com/questions/363681/how-do-i-generate-random-integers-within-a-specific-range-in-java\">this discussion</a> to get the Random number handling right.</p>\n<p>Then StudyGroups would be Java class instances, each holding a list of Students. The class would decide whether to accept a student. The main method would simply generate students, offer each student to each StudyGroup in turn until one accepted the student.</p>\n<p>Something like this is a simplistic implementation - it uses Java 8, but nothing particularly clever. A more advanced approach would probably use lambdas for the acceptance criteria, but for now a simple test for a minimum grade will do:</p>\n<pre><code>import java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.concurrent.ThreadLocalRandom;\n\npublic class StudyGroup implements Iterable&lt;Student&gt; {\n\n List&lt;Student&gt; roll = new ArrayList&lt;&gt;();\n String name;\n int minGrade;\n\n StudyGroup(String name, int minGrade) {\n this.name = name;\n this.minGrade = minGrade;\n }\n\n boolean accepted(Student candidate) {\n if (candidate.getGrade() &gt;= minGrade) {\n roll.add(candidate);\n return true;\n }\n return false;\n }\n\n @Override\n public Iterator&lt;Student&gt; iterator() {\n return roll.iterator();\n }\n\n @Override\n public String toString() {\n return String.format(&quot;Study Group %s has %d members&quot;, name, roll.size());\n }\n\n public static void main(String[] args) {\n\n StudyGroup studyGroupA = new StudyGroup(&quot;SuperStars&quot;, 19);\n StudyGroup studyGroupB = new StudyGroup(&quot;HighAchievers&quot;, 16);\n StudyGroup studyGroupC = new StudyGroup(&quot;TheRest&quot;, 0);\n\n StudyGroup[] allStudyGroups = new StudyGroup[]{studyGroupA, studyGroupB, studyGroupC};\n\n for (int studentNumber = 0; studentNumber &lt; 100; studentNumber++) {\n // Generate a student\n Student candidateStudent = Student.generate();\n // Find a study group that will accept them\n for (StudyGroup candidateStudyGroup : allStudyGroups) {\n if (candidateStudyGroup.accepted(candidateStudent)) {\n break; // found a suitable group\n }\n }\n }\n\n // Report on the distribution\n for (StudyGroup studyGroup : allStudyGroups) {\n System.out.println(studyGroup.toString());\n for (Student student : studyGroup) {\n System.out.format(&quot; %s%n&quot;, student);\n }\n System.out.println();\n }\n }\n}\n\nclass Student {\n\n private int id;\n private int grade;\n\n Student(int id, int grade) {\n this.id = id;\n this.grade = grade;\n }\n\n static int currentId = 0;\n\n static Student generate() {\n return new Student(currentId++, ThreadLocalRandom.current().nextInt(1, 21));\n }\n\n public int getGrade() {\n return grade;\n }\n\n @Override\n public String toString() {\n return String.format(&quot;Student %d - grade %d&quot;, id, grade);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-22T09:16:31.500", "Id": "264276", "ParentId": "264212", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T16:43:21.767", "Id": "264212", "Score": "1", "Tags": [ "java", "beginner", "array" ], "Title": "Generating a number of students and assigning them" }
264212
<p>I need a function of type <code>forall (n :: Nat). RandomGen q =&gt; q -&gt; Vec n q</code>. Obviously this is possible to do (correctly, don't just <code>repeat</code>) using <code>split</code>.</p> <p>(Documentation links: <a href="https://hackage.haskell.org/package/fin-0.2/docs/Data-Nat.html#t:Nat" rel="nofollow noreferrer"><code>Nat</code></a>, <a href="https://hackage.haskell.org/package/random-1.2.0/docs/System-Random.html#t:RandomGen" rel="nofollow noreferrer"><code>RandomGen</code></a>, <a href="https://hackage.haskell.org/package/vec-0.4/docs/Data-Vec-Lazy.html#t:Vec" rel="nofollow noreferrer"><code>Vec</code></a>, <a href="https://hackage.haskell.org/package/vec-0.4/docs/Data-Vec-Lazy.html#v:repeat" rel="nofollow noreferrer"><code>repeat</code></a>, <a href="https://hackage.haskell.org/package/random-1.2.0/docs/System-Random.html#v:split" rel="nofollow noreferrer"><code>split</code></a>, <a href="https://hackage.haskell.org/package/fin-0.2/docs/Data-Type-Nat.html#v:induction1" rel="nofollow noreferrer"><code>induction1</code></a>.)</p> <p>I generalized this to <em>not</em> specifically be about RNGs by taking the splitting/unfolding function as an argument. I'm not wedded to this decision; I don't think it makes much difference.</p> <pre class="lang-hs prettyprint-override"><code>import Data.Type.Nat (SNatI, induction1) import Data.Vec.Lazy (Vec(VNil, (:::))) import qualified Data.Vec.Lazy as Vec unfold :: SNatI n =&gt; (a -&gt; (a, a)) -&gt; a -&gt; Vec n a unfold uf value = induction1 VNil (\vs -&gt; let v ::: vs' = vs `Vec.snoc` value (v', v'') = uf v in Vec.init $ v' ::: v'' ::: vs') </code></pre> <p>It works, but it's pretty clunky looking. Also, consider an example like</p> <pre class="lang-hs prettyprint-override"><code>&gt; import Data.Nat (Nat(Z, S)) &gt; unfold (\n -&gt; (n * 2, n*2)) 1 :: Vec (S(S(S(S(S Z))))) Int ↪ 32 ::: 32 ::: 16 ::: 8 ::: 4 ::: VNil </code></pre> <p>That's not <em>wrong</em>, but I think it would be just as correct (and less weird looking) if it came out to<br /> <code>32 ::: 16 ::: 8 ::: 4 ::: 2 ::: VNil</code>.</p> <p>Anyone know what options I'm overlooking?</p>
[]
[ { "body": "<p>I am not an expert at type level programming, but from my experience with folds I know that you can add an extra parameter to the result type to implement foldl in terms of foldr. Here is what that would look like in this case:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>newtype VecBuilder s m a = VecBuilder { buildVec :: s -&gt; Vec m a }\n\nunfold' :: forall n a. SNatI n =&gt;\n (a -&gt; (a, a)) -&gt;\n a -&gt;\n Vec n a\nunfold' uf = buildVec (induction1 (VecBuilder base) (VecBuilder . step))\n where\n base _ = VNil\n step :: forall m. VecBuilder a m a -&gt; a -&gt; Vec (S m) a\n step vs x = let (v', x') = uf x in v' ::: buildVec vs x'\n</code></pre>\n<p>That will produce a nice output:</p>\n<pre><code>2 ::: 4 ::: 8 ::: 16 ::: 32 ::: VNil\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T00:33:02.140", "Id": "521825", "Score": "0", "body": "This does what I want! The `s` parameter to `VecBuilder` turns out to be unnecessary. The `newtype` seems to be necessary, which is frustrating. It _looks_ like clutter, both in the top-level namespace and also for reading/writing the function. But GHC won't understand how to use `induction1` on `a -> Vec n a` without it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T20:04:14.993", "Id": "264220", "ParentId": "264217", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T19:20:58.223", "Id": "264217", "Score": "1", "Tags": [ "haskell", "random", "fold" ], "Title": "Build a fixed-length vector from a recursive factory function" }
264217
<p>I'm trying to create a Collider class which will process collisions between different classes of the same base. One restriction is that I want these classes know nothing about each other, now they depend on Base and Collider classes only. Here is my code:</p> <p>collidees.h</p> <pre><code>#pragma once #include &quot;collider.h&quot; #define ALLOW_COLLIDER_VISIT \ virtual void visit(Collider&amp; c) override { c.collide(*this); }; \ virtual void visit(Collider&amp; c, Base&amp; other) override { c.collide(*this, other); }; struct Base { virtual ~Base() = default; virtual void visit(Collider&amp; c) = 0; virtual void visit(Collider&amp; c, Base&amp; other) = 0; }; struct A : Base { ALLOW_COLLIDER_VISIT; }; struct B : Base { ALLOW_COLLIDER_VISIT; }; struct C : Base { ALLOW_COLLIDER_VISIT; }; </code></pre> <p>collider.h</p> <pre><code>#pragma once #include &lt;memory&gt; #include &lt;iostream&gt; #define ADD_REVERSE_COLLISION(A, B) \ template&lt;&gt; \ inline void Collider::performCollision(B&amp; b, A&amp; a) \ { \ performCollision(a, b); \ } #define CALL_COLLIDER_FOR(CLASS) \ void collide(CLASS&amp; a) { collider.performCollision&lt;T, CLASS&gt;(static_cast&lt;T&amp;&gt;(base), a); } struct Base; struct A; struct B; struct C; struct Collider; struct HelperBase { HelperBase(Base&amp; base_, Collider&amp; collider_) : base { base_ }, collider { collider_ } {} virtual ~HelperBase() = default; virtual void collide(A&amp; base) = 0; virtual void collide(B&amp; base) = 0; virtual void collide(C&amp; base) = 0; Base&amp; base; Collider&amp; collider; }; template&lt;typename T&gt; struct Helper; struct Collider { template&lt;typename T&gt; void collide(T&amp; t) { if (helper) { helper-&gt;collide(t); } } template&lt;typename T&gt; void collide(T&amp; t, Base&amp; other) { helper = std::make_unique&lt;Helper&lt;T&gt;&gt;(t, *this); callOtherToVisit(other); } void callOtherToVisit(Base&amp; other); template&lt;typename T1, typename T2&gt; void performCollision(T1&amp; first, T2&amp; second) { std::cout &lt;&lt; &quot;No collision handler\n&quot;; } std::unique_ptr&lt;HelperBase&gt; helper = nullptr; }; template&lt;typename T&gt; struct Helper : HelperBase { Helper(T&amp; base, Collider&amp; c) : HelperBase { base, c } {} CALL_COLLIDER_FOR(A); CALL_COLLIDER_FOR(B); CALL_COLLIDER_FOR(C); }; template&lt;&gt; inline void Collider::performCollision(A&amp; a, B&amp; b) { std::cout &lt;&lt; &quot;Colliding a and b\n&quot;; } ADD_REVERSE_COLLISION(A, B); template&lt;&gt; inline void Collider::performCollision(B&amp; b1, B&amp; b2) { std::cout &lt;&lt; &quot;Colliding b1 and b2\n&quot;; } template&lt;&gt; inline void Collider::performCollision(A&amp; a, C&amp; c) { std::cout &lt;&lt; &quot;Colliding a and c\n&quot;; } ADD_REVERSE_COLLISION(A, C); template&lt;&gt; inline void Collider::performCollision(B&amp; b, C&amp; c) { std::cout &lt;&lt; &quot;Colliding b and c\n&quot;; } ADD_REVERSE_COLLISION(B, C); </code></pre> <p>collider.cpp</p> <pre><code>#include &quot;collider.h&quot; #include &quot;collidees.h&quot; void Collider::callOtherToVisit(Base&amp; other) { other.visit(*this); } </code></pre> <p>main.cpp - driver code</p> <pre><code> #include &quot;collidees.h&quot; #include &quot;collider.h&quot; int main() { Collider collider; auto a = std::make_unique&lt;A&gt;(); auto b = std::make_unique&lt;B&gt;(); auto c = std::make_unique&lt;C&gt;(); a-&gt;visit(collider, *b); a-&gt;visit(collider, *c); c-&gt;visit(collider, *b); c-&gt;visit(collider, *a); b-&gt;visit(collider, *a); return 0; } </code></pre> <p>I suppose there are some disadvantages of this code:</p> <ol> <li>It's quite complicated; adding a new collidee entails adding code in multiple places;</li> <li>There is one static_cast instead of true dispatching (although, I suppose it is safe);</li> <li>It's possible to call <code>void visit(Collider&amp; c)</code> yourself, which is meaningless;</li> <li>Class <code>Helper</code> stores reference to the object that can be easily deleted, which causes storing of dangling reference.</li> </ol> <p>(Feel free to add other drawbacks in comments)</p> <p>I would be glad to see any suggestions and improvements (or even your versions of this code).</p> <p><strong>UPDATE:</strong> Answers to comments:</p> <ul> <li>I assume collision detection as a separate step. At least in my case it is enough to add shape (or even just a rect) data to base class and find intersections of two objects, so derivatives still know nothing about each other.</li> <li>Virtual and override keywords in method declaration - it's just an inattention.</li> <li>Const correctness - again, I was focused on main problem, and missed it, although, yes, the <code>performCollision</code> method may modify arguments, so they cann't be const.</li> </ul> <p>Anyway, thanks for replies. I think I will try to correct my code according to user673679's suggestions and then try to incorporate <code>std::variant</code> and <code>std::visit</code> as both commenters mentioned. I'll wait a little bit more for others and then aacept an answer.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T23:03:58.967", "Id": "521822", "Score": "1", "body": "How can you test for collision between objects of two different types, if they don't know about each other? If the `Collider` class has the actual work, and thus knows about all the different types involved, why do to collidable classes need a virtual visit function at all?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T23:05:42.983", "Id": "521823", "Score": "1", "body": "That is, why would it not work like `std::visit`? I understand that this doesn't have a two-argument form, but I mean work in the same manner. The Collider has functions with signatures for all the classes it can handle, so having a master list as part of Collider is not out of the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T13:56:54.830", "Id": "521843", "Score": "1", "body": "Correction: [std::visit](https://en.cppreference.com/w/cpp/utility/variant/visit) *does* take multiple arguments." } ]
[ { "body": "<p>Just one coding tip:</p>\n<p><code>virtual void visit(Collider&amp; c) override </code></p>\n<p><a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rh-override\" rel=\"nofollow noreferrer\">Use <em>exactly one of</em> <code>virtual</code> or <code>override</code></a>. That is, you don't repeat the <code>virtual</code> on the overrides.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T23:08:51.620", "Id": "264225", "ParentId": "264221", "Score": "1" } }, { "body": "<h2 id=\"const-correctness\"><code>const</code> correctness:</h2>\n<p>There are a <em>lot</em> of <code>const</code>s missing.</p>\n<ul>\n<li><p>None of the member functions modify member data (on the shape classes, or the helpers), so they should all be marked <code>const</code>. e.g. <code>virtual void visit(Collider&amp; c) const = 0;</code></p>\n</li>\n<li><p>None of the function arguments passed by reference (to the shape classes or helpers) are modified, so they should be passed by <code>const&amp;</code> instead. e.g. <code>virtual void collide(A const&amp; base) = 0;</code></p>\n</li>\n</ul>\n<p>(Note: I guess if you intended to implement collision response (i.e. modify the objects) inside the <code>performCollision</code> calls, then you'd have to leave things non-const. Instead, I'd suggest returning enough information (e.g. as a <code>std::optional&lt;CollisionData&gt;</code>) to resolve the collision as a separate step later on. This is more flexible (e.g. it allows you to process collisions in groups for optimization or accuracy)).</p>\n<hr />\n<h2 id=\"unnecessary-allocation\">unnecessary allocation:</h2>\n<p>We don't need to store the <code>Helper</code> in a <code>unique_ptr</code>. Rather than storing a reference to the <code>Base</code> class in <code>HelperBase</code>, we can store a reference to the template class in the template <code>Helper</code> class, e.g.:</p>\n<pre><code>template&lt;class T&gt;\nstruct Helper: HelperBase\n{\n Helper(T const&amp; t): t(t) { }\n\n T const&amp; t;\n\n ...\n};\n</code></pre>\n<p>Since <code>Helper</code> now preserves the type of the first argument we no longer need the <code>static_cast</code>.</p>\n<p>Then we can create a <code>Helper</code> of the relevant type directly in the shape class <code>visit</code> functions, e.g:</p>\n<pre><code>struct A : Base\n{\n void visit(Shape const&amp; other) const override\n {\n auto helper = Helper&lt;A&gt;(*this);\n other.visit(helper);\n }\n\n void visit(HelperBase const&amp; helper) const override\n {\n helper.collide(*this);\n }\n};\n</code></pre>\n<p>This avoids the heap allocation, and means we don't actually need the <code>Collider</code> class. :)</p>\n<p>We could pass the shape class type to the <code>ALLOW_COLLIDER_VISIT</code> macro, or add a <code>make_helper&lt;T&gt;(*this)</code> function so that we didn't have to.</p>\n<hr />\n<h2 id=\"unnecessary-template-specialization\">unnecessary template specialization:</h2>\n<p>We don't need to use template specialization for the collision functions:</p>\n<pre><code>template&lt;typename T1, typename T2&gt;\nvoid performCollision(T1&amp; first, T2&amp; second) ...\n</code></pre>\n<p>We can use simple overloading:</p>\n<pre><code>void performCollision(A const&amp; , A const&amp; ) { std::cout &lt;&lt; &quot;(A, A)\\n&quot;; }\nvoid performCollision(B const&amp; , B const&amp; ) { std::cout &lt;&lt; &quot;(B, B)\\n&quot;; }\nvoid performCollision(C const&amp; , C const&amp; ) { std::cout &lt;&lt; &quot;(C, C)\\n&quot;; }\nvoid performCollision(A const&amp; , B const&amp; ) { std::cout &lt;&lt; &quot;(A, B)\\n&quot;; }\n... etc.\n</code></pre>\n<hr />\n<h2 id=\"example\">example:</h2>\n<p>To illustrate the points above:</p>\n<pre><code>#include &lt;iostream&gt;\n\nstruct A;\nstruct B;\nstruct C;\n\nvoid collide(A const&amp; , A const&amp; ) { std::cout &lt;&lt; &quot;(A, A)\\n&quot;; }\nvoid collide(B const&amp; , B const&amp; ) { std::cout &lt;&lt; &quot;(B, B)\\n&quot;; }\nvoid collide(C const&amp; , C const&amp; ) { std::cout &lt;&lt; &quot;(C, C)\\n&quot;; }\nvoid collide(A const&amp; , B const&amp; ) { std::cout &lt;&lt; &quot;(A, B)\\n&quot;; }\nvoid collide(B const&amp; , A const&amp; ) { std::cout &lt;&lt; &quot;(B, A)\\n&quot;; }\nvoid collide(A const&amp; , C const&amp; ) { std::cout &lt;&lt; &quot;(A, C)\\n&quot;; }\nvoid collide(C const&amp; , A const&amp; ) { std::cout &lt;&lt; &quot;(C, A)\\n&quot;; }\nvoid collide(C const&amp; , B const&amp; ) { std::cout &lt;&lt; &quot;(C, B)\\n&quot;; }\nvoid collide(B const&amp; , C const&amp; ) { std::cout &lt;&lt; &quot;(B, C)\\n&quot;; }\n\nstruct CollisionDispatcherBase\n{\n virtual void collide(A const&amp; other) const = 0;\n virtual void collide(B const&amp; other) const = 0;\n virtual void collide(C const&amp; other) const = 0;\n};\n\ntemplate&lt;class T&gt;\nstruct CollisionDispatcher : CollisionDispatcherBase\n{\n CollisionDispatcher(T const&amp; t): t(t) { }\n\n T const&amp; t;\n\n void collide(A const&amp; other) const override { ::collide(t, other); };\n void collide(B const&amp; other) const override { ::collide(t, other); };\n void collide(C const&amp; other) const override { ::collide(t, other); };\n};\n\nstruct Shape\n{\n virtual ~Shape() {}\n\n virtual void visit(Shape const&amp; other) const = 0;\n virtual void visit(CollisionDispatcherBase const&amp; c) const = 0;\n};\n\nstruct A : Shape\n{\n void visit(Shape const&amp; other) const override { auto c = CollisionDispatcher&lt;A&gt;{ *this }; other.visit(c); }\n void visit(CollisionDispatcherBase const&amp; c) const override { c.collide(*this); }\n};\n\nstruct B : Shape\n{\n void visit(Shape const&amp; other) const override { auto c = CollisionDispatcher&lt;B&gt;{ *this }; other.visit(c); }\n void visit(CollisionDispatcherBase const&amp; c) const override { c.collide(*this); }\n};\n\nstruct C : Shape\n{\n void visit(Shape const&amp; other) const override { auto c = CollisionDispatcher&lt;C&gt;{ *this }; other.visit(c); }\n void visit(CollisionDispatcherBase const&amp; c) const override { c.collide(*this); }\n};\n\n#include &lt;vector&gt;\n#include &lt;memory&gt;\n\nint main()\n{\n auto colliders = std::vector&lt;std::unique_ptr&lt;Shape&gt;&gt;();\n colliders.push_back(std::make_unique&lt;A&gt;());\n colliders.push_back(std::make_unique&lt;B&gt;());\n colliders.push_back(std::make_unique&lt;C&gt;());\n \n for (auto i = std::size_t{ 0 }; i != colliders.size() - 1; ++i)\n for (auto j = i + 1; j != colliders.size(); ++j)\n colliders[i]-&gt;visit(*colliders[j]);\n}\n</code></pre>\n<hr />\n<h2 id=\"use-stdvariant-instead\">use std::variant instead?</h2>\n<p>If the version of C++ you're using supports <code>std::variant</code>, we can ditch inheritance and use <code>std::visit</code> to do the double dispatch for us:</p>\n<pre><code>#include &lt;iostream&gt;\n#include &lt;variant&gt;\n#include &lt;vector&gt;\n\nstruct A { };\nstruct B { };\nstruct C { };\n\nstruct collide_visitor\n{\n void operator()(A const&amp; , A const&amp; ) const { std::cout &lt;&lt; &quot;(A, A)\\n&quot;; }\n void operator()(B const&amp; , B const&amp; ) const { std::cout &lt;&lt; &quot;(B, B)\\n&quot;; }\n void operator()(C const&amp; , C const&amp; ) const { std::cout &lt;&lt; &quot;(C, C)\\n&quot;; }\n void operator()(A const&amp; , B const&amp; ) const { std::cout &lt;&lt; &quot;(A, B)\\n&quot;; }\n void operator()(B const&amp; , A const&amp; ) const { std::cout &lt;&lt; &quot;(B, A)\\n&quot;; }\n void operator()(A const&amp; , C const&amp; ) const { std::cout &lt;&lt; &quot;(A, C)\\n&quot;; }\n void operator()(C const&amp; , A const&amp; ) const { std::cout &lt;&lt; &quot;(C, A)\\n&quot;; }\n void operator()(C const&amp; , B const&amp; ) const { std::cout &lt;&lt; &quot;(C, B)\\n&quot;; }\n void operator()(B const&amp; , C const&amp; ) const { std::cout &lt;&lt; &quot;(B, C)\\n&quot;; }\n};\n\nint main()\n{\n using collider = std::variant&lt;A, B, C&gt;;\n\n auto colliders = std::vector&lt;collider&gt;();\n colliders.push_back(A{});\n colliders.push_back(B{});\n colliders.push_back(C{});\n\n for (auto i = std::size_t{ 0 }; i != colliders.size() - 1; ++i)\n for (auto j = i + 1; j != colliders.size(); ++j)\n std::visit(collide_visitor{}, colliders[i], colliders[j]);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T09:38:31.577", "Id": "264233", "ParentId": "264221", "Score": "2" } } ]
{ "AcceptedAnswerId": "264233", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T20:13:33.247", "Id": "264221", "Score": "3", "Tags": [ "c++", "visitor-pattern" ], "Title": "Collider class using some kind of visitor pattern" }
264221
<p>I'm trying to make a safe builder using Kotlin that can be partially built and then copied, perhaps multiple times, to avoid repetition. Note that the properties that are reused aren't always the same - I've reused <code>name</code> and <code>real</code> here, but sometimes <code>age</code> and <code>real</code> or only <code>age</code> might be reused. This is what it looks like (<code>Main.kt</code>):</p> <pre><code>import builders.* fun main() { val bobProto = personBuilder() .name(&quot;Bob&quot;) .real(false) val bobSenior = bobProto.copy() .age(100) .build() val bobJunior = bobProto.copy() .age(0) .build() println(&quot;Bob Sr. = $bobSenior, Bob Jr. = $bobJunior&quot;) } </code></pre> <p>This code builds two instances of <code>Person</code> that share a couple of properties but differ in another. <code>Person</code> is defined in <code>people/Person.kt</code> as such:</p> <pre><code>package people data class Person(val name: String, val age: Int, val real: Boolean) </code></pre> <p>The implementation of the builder and other functions is in <code>builders/PersonBuilder.kt</code>:</p> <pre><code>package builders import people.Person object SetProp object NotSetProp open class PersonBuilder&lt;N, A, R&gt; { var _name: String? = null var _age: Int? = null var _real: Boolean? = null } fun personBuilder(): PersonBuilder&lt;NotSetProp, NotSetProp, NotSetProp&gt; = PersonBuilder() fun &lt;A, R, T&gt; T.name(name: String): PersonBuilder&lt;SetProp, A, R&gt; where T : PersonBuilder&lt;NotSetProp, A, R&gt; { this._name = name return this as PersonBuilder&lt;SetProp, A, R&gt; } fun &lt;N, R, T&gt; T.age(age: Int): PersonBuilder&lt;N, SetProp, R&gt; where T : PersonBuilder&lt;N, NotSetProp, R&gt; { this._age = age return this as PersonBuilder&lt;N, SetProp, R&gt; } fun &lt;N, A, T&gt; T.real(real: Boolean): PersonBuilder&lt;N, A, SetProp&gt; where T : PersonBuilder&lt;N, A, NotSetProp&gt; { this._real = real return this as PersonBuilder&lt;N, A, SetProp&gt; } fun &lt;N, A, R, T : PersonBuilder&lt;N, A, R&gt;&gt; T.copy(): T { val pb = PersonBuilder&lt;N, A, R&gt;() pb._name = this._name pb._age = this._age pb._real = this._real return pb as T } fun &lt;T&gt; T.build(): Person where T : PersonBuilder&lt;SetProp, SetProp, SetProp&gt; = Person(this._name!!, this._age!!, this._real!!) </code></pre> <p>This works, but because it's a bit hacky, the error message when a property is left out before calling <code>build</code> or when a property is set twice is cryptic - it simply says that the extension method could not be used because of a receiver type mismatch. There doesn't seem to be a way to add custom error messages, though, and Kotlin's contracts didn't seem to help here either.</p> <p>Furthermore, the properties of the builder (<code>_name</code>, <code>_age</code>, and <code>_real</code>) have to be public for the extension functions and so can be accessed from anywhere. I've made their names start with underscores, but that doesn't keep them from being visible.</p> <p>I'd like to know if there's a more idiomatic way to make a safe builder that checks that all properties are initialized exactly once at compile-time, or at least if there are any minor improvements I can make in this code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T20:58:32.793", "Id": "521813", "Score": "0", "body": "Is the compile-time check to make sure all properties are initialized **exactly once** a strict requirement? What's the rationale behind this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T21:06:21.770", "Id": "521814", "Score": "0", "body": "@SimonForsberg Having each property initialized once is pretty much the primary goal I had in mind while making this, although I could do without it if absolutely necessary, I guess. It's mostly a matter of convenience. One problem with having runtime checks is that you need to run it every time you want to check if it works. I think that's reasonable, but it's more convenient if IntelliJ just immediately highlights errors." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T21:10:29.373", "Id": "521816", "Score": "1", "body": "*This question has been discussed in [chat](https://chat.stackexchange.com/transcript/message/58673584#58673584)*" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T21:22:33.467", "Id": "521818", "Score": "0", "body": "Is it okay if you set the properties in always the same order, similar to [this question](https://codereview.stackexchange.com/q/263807/31562), or does the order of setting properties have to be flexible ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T22:03:53.567", "Id": "521820", "Score": "0", "body": "@SimonForsberg Since some properties may be reused (and it's not always the same properties each time), the order should be flexible." } ]
[ { "body": "<p>I have no problem at all with the essence of your idea (safe builders) but I very much dislike the code:</p>\n<ol>\n<li>It requires as many generic parameters as there are properties, practically inviting the need/desire for generic generic (not a typo) parameters or for code generation.</li>\n<li>It allows clients to decide whether a person object classifies as a person-template or a real person.</li>\n</ol>\n<p>Point 1 is my main concern while point 2 is somewhat off-topic but perhaps worth mentioning.</p>\n<p>If you really (really?) insist on compile-time verification that much, the code makes perfect sense.\nBut if so, what makes the underlying problem so important that it it prevales over much simpler run-time solutions?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T13:26:59.063", "Id": "521841", "Score": "0", "body": "Thanks for your answer. Your first point is valid, and I did plan on generating the code for the builder for classes with many parameters. Point 2 is an intended feature, and I'd like to keep it that way. Having it verified at compile-time is just more convenient than having to hit the run button to test if the `Person` object was constructed successfully. Do you have any suggestions as to make the code more \"likable\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T13:48:59.607", "Id": "521842", "Score": "1", "body": "@user: if you intend to use code-generation there's no need at all to make the code likeable, i.e. you can fully (and justifiably) ignore any likeability-aspect (as long as the compiler is fine with it of course ;-). I don't get your \"run button\"-argument, and I'd still solve your problem differently, but I'll give it the benefit of the doubt since I don't know the context." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T12:11:36.850", "Id": "264235", "ParentId": "264222", "Score": "1" } }, { "body": "<p>The only advice I have is: Don't do that.</p>\n<p>You're abusing generics, massively, IMO.</p>\n<p>A data class where all the properties are <code>val</code> is the best compile-time validation Kotlin has of &quot;making sure all properties are given a value exactly once&quot;.</p>\n<p>Then make different functions to create objects from different templates.</p>\n<p>With your <code>Person</code> example above that would be something like:</p>\n<pre><code>fun makeBob(age: Int) = Person(name = &quot;Bob&quot;, real = false, age = age)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T21:25:16.360", "Id": "264261", "ParentId": "264222", "Score": "3" } } ]
{ "AcceptedAnswerId": "264261", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T20:32:12.840", "Id": "264222", "Score": "-1", "Tags": [ "kotlin", "fluent-interface" ], "Title": "Instantiating Person objects using the builder pattern" }
264222
<p>This is a script that I've written for personal use, and to educate myself. The script is a bit comment heavy to help future me remember all the details &amp; design choices made at the time of writing.</p> <p>The use case is simply to synchronize/copy files to an AWS S3 bucket using AWS CLI. There's a separate CDK part of the project, which sets up the AWS infrastructure, but that isn't really relevant here. There are some configuration items in a properties file, which are read, and then the script checks whether everything is in place on the AWS end, and if so, it reads through a config folder structure which folders to backup, and how (include &amp; exclude patterns in respective files).</p> <p>Going with Bash instead of a basic shell script was a deliberate choice, since this wouldn't be run on any production server, and extreme portability wasn't the main point here.</p> <p>Folder structure of the overall project is:</p> <pre><code>- aws-infra -- [various things here, that are out of the scope of the question] - config -- backup --- Documents ---- includes.txt --- Pictures ---- includes.txt (example at the end) ---- excludes.txt (example at the end) --- [more files/folders following the same structure] -- configuration.properties - scripts -- sync.sh </code></pre> <p>Theoretically I could've just run <code>aws s3 sync</code> on the base path, but since it's a recursive command, and there are a lot (about 500k) of unnecessary files, it would take a lot of time to go through each of them separately.</p> <pre><code>#!/bin/bash # Get the current directory where this file is, so that the script can # called from other directories without breaking up. DIR=&quot;$( cd &quot;$( dirname &quot;${BASH_SOURCE[0]}&quot; )&quot; &amp;&amp; pwd)&quot; CONFIG_FOLDER=&quot;$DIR/../config&quot; PROP_FILE='configuration.properties' # This is an associated array, i.e., keys can be strings or variables # think Java HashMap or JavaScript Object declare -A properties # These are Bash arrays, i.e., with auto-numbered keys # think Java or JavaScript array declare -a includes excludes params function loadProperties { local file=&quot;$CONFIG_FOLDER/$PROP_FILE&quot; if [[ ! -f &quot;$file&quot; ]]; then echo &quot;$PROP_FILE not found!&quot; return 2 fi while IFS='=' read -r origKey value; do local key=&quot;$origKey&quot; # Replace all non-alphanumerical characters (except underscore) # with an underscore key=&quot;${key//[!a-zA-Z0-9_]/_}&quot; if [[ &quot;$origKey&quot; == &quot;#&quot;* ]]; then local ignoreComments elif [[ -z &quot;$key&quot; ]]; then local emptyLine else properties[&quot;$key&quot;]=&quot;$value&quot; fi done &lt; &quot;$file&quot; if [[ &quot;${properties[debug]}&quot; = true ]]; then declare -p properties fi } function getBucketName { # Declare inside a function automatically makes the variable a local # variable. declare -a params params+=(--name &quot;${properties[bucket_parameter_name]}&quot;) params+=(--profile=&quot;${properties[aws_profile]}&quot;) # Get the bucket name from SSM Parameter Store, where it's stored. # Logic is: # 1) run the AWS CLI command # 2) grab 5th line from the output with sed # 3) grab the 2nd word of the line with awk # 4) substitute first all double quotes with empty string, # and then all commas with empty string, using sed local bucketName=$(aws ssm get-parameter &quot;${params[@]}&quot; | \ sed -n '5p' | \ awk '{ print $2 }' | \ sed -e 's/&quot;//g' -e 's/,//g') properties[s3_bucket]=&quot;$bucketName&quot; } function checkBucket { declare -a params params+=(--bucket &quot;${properties[s3_bucket]}&quot;) params+=(--profile=&quot;${properties[aws_profile]}&quot;) # Direct stderr to stdout by using 2&gt;&amp;1 local bucketStatus=$(aws s3api head-bucket &quot;${params[@]}&quot; 2&gt;&amp;1) # The 'aws s3api head-bucket' returns an empty response, if # everything's ok or an error message, if something went wrong. if [[ -z &quot;$bucketStatus&quot; ]]; then echo &quot;Bucket \&quot;${properties[s3_bucket]}\&quot; owned and exists&quot;; return 0 elif echo &quot;${bucketStatus}&quot; | grep 'Invalid bucket name'; then return 1 elif echo &quot;${bucketStatus}&quot; | grep 'Not Found'; then return 1 elif echo &quot;${bucketStatus}&quot; | grep 'Forbidden'; then echo &quot;Bucket exists but not owned&quot; return 1 elif echo &quot;${bucketStatus}&quot; | grep 'Bad Request'; then echo &quot;Bucket name specified is less than 3 or greater than 63 characters&quot; return 1 else return 1 fi } function create_params { local local_folder=&quot;$HOME/$1&quot; local bucket_folder=&quot;s3://${properties[s3_bucket]}$local_folder&quot; params+=(&quot;$local_folder&quot; &quot;$bucket_folder&quot;) if [[ ${excludes[@]} ]]; then params+=(&quot;${excludes[@]}&quot;) fi if [[ ${includes[@]} ]]; then params+=(&quot;${includes[@]}&quot;) fi params+=(&quot;--profile=${properties[aws_profile]}&quot;) if [[ &quot;${properties[dryrun]}&quot; = true ]]; then params+=(--dryrun) fi if [[ &quot;${properties[debug]}&quot; = true ]]; then declare -p params fi } # Sync is automatically recursive, and it can't be turned off. Sync # checks whether any files have changed since latest upload, and knows # to avoid uploading files, which are unchanged. function sync { aws s3 sync &quot;${params[@]}&quot; } # Copy can be ran for individual files, and recursion can be avoided, # when necessary. Copy doesn't check whether the file in source has # changed since the last upload to target, but will always upload # the files. Thus, use only when necessary to avoid sync. function copy { local basePath=&quot;${params[0]}*&quot; # Loop through files in given path. for file in $basePath; do # Check that file is not a folder or a symbolic link. if [[ ! -d &quot;$file&quot; &amp;&amp; ! -L &quot;$file&quot; ]]; then # Remove first parameter, i.e., local folder, since with # copy, we need to specify individual files instead of the # base folder. unset params[0] aws s3 cp &quot;$file&quot; &quot;${params[@]}&quot; fi done } function process_patterns { # If second parameter is not defined, then pointless to even read # anything, since there's no guidance on what to do with the data. if [[ -z &quot;$2&quot; ]]; then return 1; fi # If the file defined in the first parameter exists, then loop # through its content line by line, and process it. if [[ -f &quot;$1&quot; ]]; then while read line; do if [[ $2 == &quot;include&quot; ]]; then includes+=(--include &quot;$line&quot;) elif [[ $2 == &quot;exclude&quot; ]]; then excludes+=(--exclude &quot;$line&quot;) fi done &lt; $1 fi } # Reset the variables used in global scope. # To be called after each cycle of the main loop. function reset { unset includes excludes params } # The &quot;main loop&quot; that goes through folders that need to be # backed up. function handleFolder { process_patterns &quot;${1}/${properties[exclude_file_name]}&quot; exclude process_patterns &quot;${1}/${properties[include_file_name]}&quot; include # Remove the beginning of the path until the last forward slash. create_params &quot;${1##*/}&quot; if [[ &quot;$2&quot; == &quot;sync&quot; ]]; then sync elif [[ &quot;$2&quot; == &quot;copy&quot; ]]; then copy else echo &quot;Don't know what to do.&quot; fi reset } function usage { cat &lt;&lt; EOF Usage: ${0##*/} [-dDh] -d, --debug enable debug mode -D, --dryrun execute commands in dryrun mode, i.e., don't upload anything -h, --help display this help and exit EOF } while getopts &quot;:dDh-:&quot; option; do case &quot;$option&quot; in -) case &quot;${OPTARG}&quot; in debug) properties[debug]=true ;; dryrun) properties[dryrun]=true ;; help) # Send output to stderr instead of stdout by # using &gt;&amp;2. usage &gt;&amp;2 exit 2 ;; *) echo &quot;Unknown option --$OPTARG&quot; &gt;&amp;2 usage &gt;&amp;2 exit 2 ;; esac ;; d) properties[debug]=true ;; D) properties[dryrun]=true ;; h) usage &gt;&amp;2 exit 2 ;; *) echo &quot;Unknown option -$OPTARG&quot; &gt;&amp;2 usage &gt;&amp;2 exit 2 ;; esac done # set -x shows the actual commands executed by the script. Much better # than trying to run echo or printf with each command separately. if [[ &quot;${properties[debug]}&quot; = true ]]; then set -x fi loadProperties # $? gives the return value of previous function call, non-zero value # means that an error of some type occured if [[ $? != 0 ]]; then exit fi getBucketName if [[ $? != 0 ]]; then exit fi checkBucket if [[ $? != 0 ]]; then exit fi # Add an asterisk in the end for the loop to work, i.e., # to loop through all files in the folder. backup_config_path=&quot;$CONFIG_FOLDER/${properties[backup_folder]}*&quot; # Change shell options (shopt) to include filenames beginning with a # dot in the file name expansion. shopt -s dotglob # Loop through files in given path, i.e., subfolders of home folder. for folder in $backup_config_path; do # Check that file is a folder, and that it's not a symbolic link. if [[ -d &quot;$folder&quot; &amp;&amp; ! -L &quot;$folder&quot; ]]; then handleFolder &quot;$folder&quot; &quot;sync&quot; fi done # Also include the files in home folder itself, but use copy to avoid # recursion. Home folder &amp; all subfolders contain over 500k files, # and takes forever to go through them all with sync, even with an # exclusion pattern. # Remove the last character (asterisk) from the end of the config path. handleFolder &quot;${backup_config_path::-1}&quot; &quot;copy&quot; </code></pre> <p>Properties file (SSM parameter name censored):</p> <pre><code># AWS profile to be used aws_profile=personal # Bucket to sync files to bucket_parameter_name=[my_ssm_parameter_name] # Config folder where backup folders &amp; files are found. backup_folder=backup/ # Names of the files defining the include &amp; exclude patterns for each folder. include_file_name=includes.txt exclude_file_name=excludes.txt </code></pre> <p>Example include file:</p> <pre><code>*.gif *.jpg </code></pre> <p>Example exclude file to pair with above:</p> <pre><code>* </code></pre> <p>The script works, but I'm interested on how to improve it. For instance, the error handling feels a bit clumsy.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-20T22:35:47.703", "Id": "264223", "Score": "4", "Tags": [ "bash" ], "Title": "Shell script to backup local files to public cloud" }
264223
<p>This code models two vehicle types, with a method to accept a string representing a boost to change speed.</p> <ul> <li>How can I optimize performance in inheritance child class?</li> <li>How can I reduce the code inside BMW class?</li> <li>How can I use additional variables to reduce the child class code?</li> </ul> <pre><code>class Maruti{ public $currentSpeed; public function __construct($speed){ $this-&gt;currentSpeed = $speed; } public function increaseSpeed($boost){ if($boost == 'bad'){ $this-&gt;currentSpeed -=5; }elseif($boost == 'fair'){ $this-&gt;currentSpeed +=5; }elseif($boost == 'good'){ $this-&gt;currentSpeed +=10; }elseif($boost == 'turbo'){ $this-&gt;currentSpeed +=20; } if($this-&gt;currentSpeed == 100 || $this-&gt;currentSpeed == 125 || $this-&gt;currentSpeed == 150){ echo &quot;Congratulations! You have reached a speed of $this-&gt;currentSpeed&quot;; } } } class BMW extends Maruti{ public function increaseSpeed($boost){ if($boost == 'fair'){ $this-&gt;currentSpeed +=10; }elseif($boost == 'good'){ $this-&gt;currentSpeed +=15; }elseif($boost == 'turbo'){ $this-&gt;currentSpeed +=25; } if($this-&gt;currentSpeed == 100 || $this-&gt;currentSpeed == 125 || $this-&gt;currentSpeed == 150){ echo &quot;Congratulations! You have reached a speed of $this-&gt;currentSpeed&quot;; } } } $obj = new BMW(115); $obj-&gt;increaseSpeed('fair'); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-22T16:55:01.823", "Id": "521952", "Score": "1", "body": "Welcome to Code Review! I [changed the title](https://codereview.stackexchange.com/revisions/264228/3) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate." } ]
[ { "body": "<h1 id=\"suggestions-cr32\">Suggestions</h1>\n<p>Before addressing the main question, there are some suggestions to mention first.</p>\n<h2 id=\"s.o.l.i.d.principles-cgyu\">S.O.L.I.D. principles</h2>\n<p>If you aren't already familiar with them, look into the <a href=\"https://www.digitalocean.com/community/conceptual_articles/s-o-l-i-d-the-first-five-principles-of-object-oriented-design\" rel=\"nofollow noreferrer\">SOLID principles</a>. The <strong>S</strong> is for the <a href=\"https://www.digitalocean.com/community/conceptual_articles/s-o-l-i-d-the-first-five-principles-of-object-oriented-design#single-responsibility-principle\" rel=\"nofollow noreferrer\">Single-Responsibility Principle</a>:</p>\n<blockquote>\n<p>A class should have one and only one reason to change, meaning that a class should have only one job.</p>\n</blockquote>\n<p>The <code>increaseSpeed()</code> methods violate this principle because they handle:</p>\n<ul>\n<li>updating the <code>currentSpeed</code> property</li>\n<li>outputting text based on the value of the <code>currentSpeed</code> property</li>\n</ul>\n<p>the output of text should be handle elsewhere - e.g. a separate method, or in the code that interacts with the object.</p>\n<h2 id=\"formatting-hhmv\">Formatting</h2>\n<p>Before I address the question, I would suggest considering readability. Have you looked as <a href=\"https://www.php-fig.org/psr/psr-12/\" rel=\"nofollow noreferrer\">PSR-12</a>? The code adheres to it somewhat, except for a few recommendations like spacing for braces:</p>\n<blockquote>\n<p>The opening brace for the class MUST go on its own line; the closing brace for the class MUST go on the next line after the body.</p>\n</blockquote>\n<p>I honestly am not fond of having an opening brace go on its own line, having worked with JS for many years, but it should at least have a space after the class name for readability:</p>\n<pre><code>class Maruti { \n //^ adds separation \n</code></pre>\n<h2 id=\"type-hinting-dkrd\">Type hinting</h2>\n<p>&quot;<em>Type declarations can be added to function arguments, return values, and, as of PHP 7.4.0, class properties. They ensure that the value is of the specified type at call time, otherwise a TypeError is thrown.</em>&quot;<sup><a href=\"https://www.php.net/manual/en/language.types.declarations.php\" rel=\"nofollow noreferrer\">1</a></sup></p>\n<p>The constructors can expect <code>$speed</code> to be a numeric type - e.g. <code>int</code>, <code>float</code>, and the <code>increaseSpeed()</code> methods can expect <code>$boost</code> to be a string type - i.e. <code>string</code>.</p>\n<p>Additionally return types for the methods can be declared. &quot;<em>PHP 7 adds support for <a href=\"https://www.php.net/manual/en/language.types.declarations.php\" rel=\"nofollow noreferrer\">return type declarations</a>.</em>&quot;<sup><a href=\"https://www.php.net/manual/en/migration70.new-features.php#migration70.new-features.return-type-declarations\" rel=\"nofollow noreferrer\">2</a></sup> and as of PHP 7.1 <a href=\"https://www.php.net/manual/en/migration71.new-features.php#migration71.new-features.void-functions\" rel=\"nofollow noreferrer\"><code>void</code></a> can be used.</p>\n<h1 id=\"main-question-gipr\">Main Question</h1>\n<blockquote>\n<h3 id=\"how-can-i-reduce-the-code-inside-bmw-class-how-can-i-use-additional-variables-to-reduce-the-child-class-code-xpd5\">How Can I reduce the code inside BMW class? How can I use additional variables to reduce the child class code?</h3>\n</blockquote>\n<p>One way to reduce the code is to define a mapping of strings to numbers to be added - e.g.</p>\n<pre><code>class Maruti {\n protected const BOOST_MAPPING = [\n 'bad' =&gt; -5,\n 'fair' =&gt; 5,\n 'good' =&gt; 10,\n 'turbo' =&gt; 20\n ];\n</code></pre>\n<p>Then in the <code>increaseSpeed</code> method check to see if that mapping contains a key at <code>$boost</code> (e.g. one can use <a href=\"https://php.net/isset\" rel=\"nofollow noreferrer\"><code>isset()</code></a>) - if it does then add the value associated with that key within <code>static::BOOST_MAPPING</code>. Then check the value of the <code>currentSpeed</code> and if it is 100, 125 or 150 then echo the statement - hint: use <a href=\"https://php.net/in_array\" rel=\"nofollow noreferrer\"><code>in_array()</code></a> to eliminate the <em>or</em> operators.</p>\n<p>Then in the sub-class override the mapping, and then there will be no need to override the method <code>increaseSpeed()</code></p>\n<pre><code>class BMW extends Maruti {\n protected const BOOST_MAPPING = [\n 'fair' =&gt; 10,\n 'good' =&gt; 15,\n 'turbo' =&gt; 25\n ];\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-22T23:36:43.193", "Id": "521967", "Score": "1", "body": "@mickmackusa thanks - updated" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T06:30:00.283", "Id": "264229", "ParentId": "264228", "Score": "4" } }, { "body": "<p>You don't need inheritance for this. you don't even need 2 classes since the only difference is a config.\nTaking it from where <a href=\"https://codereview.stackexchange.com/a/264229/222948\">Sam got</a> I think you can do this:\n(Also did some other changes as class methods should not <code>echo</code> something. You should always separate the logic from presentation layer)</p>\n<pre><code>class Car\n{\n private int $currentSpeed;\n private array $boostMap;\n private array $targetSpeeds;\n \n public function __construct(int $speed, array $boostMap, array $targetSpeeds = [100, 125, 150])\n {\n $this-&gt;currentSpeed = $speed;\n $this-&gt;boostMap = $boostMap;\n $this-&gt;targetSpeeds = $targetSpeeds;\n }\n\n public function increaseSpeed(string $boost): void\n {\n $this-&gt;currentSpeed += ($this-&gt;boostMap[$boost] ?? 0);\n } \n\n public function isTargetSpeedReached(): bool\n {\n return in_array($this-&gt;currentSpeed, $this-&gt;targetSpeeds); \n }\n\n public function getCurrentSpeed(): int\n {\n return $this-&gt;currentSpeed;\n }\n}\n</code></pre>\n<p>Now using the class.</p>\n<pre><code>$marutiBoostMap = [\n 'bad' =&gt; -5,\n 'fair' =&gt; 5,\n 'good' =&gt; 10,\n 'turbo' =&gt; 20\n];\n$maruti = new Car(20, $marutiBoostMap);\n$maruti-&gt;increaseSpeed('good');\nif ($maruti-&gt;isTargetSpeedReached()) {\n echo &quot;Congratulations, you reached the speed &quot; . $maruti-&gt;getCurrentSpeed();\n}\n</code></pre>\n<p>You can do the same for bmw</p>\n<pre><code>$bmwBoostMap = [\n 'fair' =&gt; 10,\n 'good' =&gt; 15,\n 'turbo' =&gt; 25\n];\n$bmw = new Car(20, $bmwBoostMap);\n$bmw-&gt;increaseSpeed('good');\nif ($bmw-&gt;isTargetSpeedReached()) {\n echo &quot;Congratulations, you reached the speed &quot; . $bmw-&gt;getCurrentSpeed();\n}\n</code></pre>\n<p>You can use the code as it is if you need it for a car instance. Or you can use the code in a loop by reading the configs from and array of configs.</p>\n<p>here is a random example on how you can take it further.</p>\n<pre><code>class CarFactory\n{\n private array $config = [\n 'maruti' =&gt; [\n 'speed' =&gt; 10,\n 'boostMap' =&gt; [\n 'bad' =&gt; -5,\n 'fair' =&gt; 5,\n 'good' =&gt; 10,\n 'turbo' =&gt; 20\n ]\n ],\n 'bmw' =&gt; [\n 'speed' =&gt; 20,\n 'boostMap' =&gt; [\n 'fair' =&gt; 10,\n 'good' =&gt; 15,\n 'turbo' =&gt; 25\n ]\n ]\n ];\n\n public function create(string $model): Car\n {\n $config = $this-&gt;config[$model] ?? null;\n if ($config === null) {\n throw new \\InvalidArguemtException(&quot;Model {$model}&quot; is not supported);\n }\n return new Car($config['speed'] ?? 0, $config['boostMap'] ?? []);\n }\n}\n</code></pre>\n<p>then use this factory to create all kind of instances</p>\n<pre><code>$factory = new CarFactory();\n$maruti = $factory-&gt;create('maruti');\n$bmw = $factory-&gt;create('bmw');\n\n//do your magic with $maruti and $bmw.\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-22T06:34:12.303", "Id": "264267", "ParentId": "264228", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-21T06:01:19.133", "Id": "264228", "Score": "-1", "Tags": [ "performance", "php", "object-oriented", "inheritance" ], "Title": "Simple Vehicle speed representation" }
264228